blob: f17c23619ed58b7c7a5184c4e0bcbf2e8abe8e29 [file] [log] [blame]
Puyan Lotfi0ae3f322017-11-02 23:37:32 +00001//===-------------- MIRCanonicalizer.cpp - MIR Canonicalizer --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The purpose of this pass is to employ a canonical code transformation so
11// that code compiled with slightly different IR passes can be diffed more
12// effectively than otherwise. This is done by renaming vregs in a given
13// LiveRange in a canonical way. This pass also does a pseudo-scheduling to
14// move defs closer to their use inorder to reduce diffs caused by slightly
15// different schedules.
16//
17// Basic Usage:
18//
19// llc -o - -run-pass mir-canonicalizer example.mir
20//
21// Reorders instructions canonically.
22// Renames virtual register operands canonically.
23// Strips certain MIR artifacts (optionally).
24//
25//===----------------------------------------------------------------------===//
26
27#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/ADT/STLExtras.h"
Puyan Lotfi0ae3f322017-11-02 23:37:32 +000029#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstrBuilder.h"
31#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikie48319232017-11-08 01:01:31 +000032#include "llvm/CodeGen/Passes.h"
Puyan Lotfi0ae3f322017-11-02 23:37:32 +000033#include "llvm/Support/raw_ostream.h"
Puyan Lotfi0ae3f322017-11-02 23:37:32 +000034
35#include <queue>
36
37using namespace llvm;
38
39namespace llvm {
40extern char &MIRCanonicalizerID;
41} // namespace llvm
42
43#define DEBUG_TYPE "mir-canonicalizer"
44
45static cl::opt<unsigned>
Puyan Lotfi388ad3d2018-04-16 08:12:15 +000046 CanonicalizeFunctionNumber("canon-nth-function", cl::Hidden, cl::init(~0u),
47 cl::value_desc("N"),
48 cl::desc("Function number to canonicalize."));
Puyan Lotfi0ae3f322017-11-02 23:37:32 +000049
Puyan Lotfi388ad3d2018-04-16 08:12:15 +000050static cl::opt<unsigned> CanonicalizeBasicBlockNumber(
51 "canon-nth-basicblock", cl::Hidden, cl::init(~0u), cl::value_desc("N"),
52 cl::desc("BasicBlock number to canonicalize."));
Puyan Lotfi0ae3f322017-11-02 23:37:32 +000053
54namespace {
55
56class MIRCanonicalizer : public MachineFunctionPass {
57public:
58 static char ID;
59 MIRCanonicalizer() : MachineFunctionPass(ID) {}
60
61 StringRef getPassName() const override {
62 return "Rename register operands in a canonical ordering.";
63 }
64
65 void getAnalysisUsage(AnalysisUsage &AU) const override {
66 AU.setPreservesCFG();
67 MachineFunctionPass::getAnalysisUsage(AU);
68 }
69
70 bool runOnMachineFunction(MachineFunction &MF) override;
71};
72
73} // end anonymous namespace
74
75enum VRType { RSE_Reg = 0, RSE_FrameIndex, RSE_NewCandidate };
76class TypedVReg {
77 VRType type;
78 unsigned reg;
79
80public:
81 TypedVReg(unsigned reg) : type(RSE_Reg), reg(reg) {}
82 TypedVReg(VRType type) : type(type), reg(~0U) {
83 assert(type != RSE_Reg && "Expected a non-register type.");
84 }
85
Puyan Lotfi388ad3d2018-04-16 08:12:15 +000086 bool isReg() const { return type == RSE_Reg; }
87 bool isFrameIndex() const { return type == RSE_FrameIndex; }
88 bool isCandidate() const { return type == RSE_NewCandidate; }
Puyan Lotfi0ae3f322017-11-02 23:37:32 +000089
90 VRType getType() const { return type; }
91 unsigned getReg() const {
92 assert(this->isReg() && "Expected a virtual or physical register.");
93 return reg;
94 }
95};
96
97char MIRCanonicalizer::ID;
98
99char &llvm::MIRCanonicalizerID = MIRCanonicalizer::ID;
100
101INITIALIZE_PASS_BEGIN(MIRCanonicalizer, "mir-canonicalizer",
Craig Topperaaf1db12017-11-03 18:02:46 +0000102 "Rename Register Operands Canonically", false, false)
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000103
104INITIALIZE_PASS_END(MIRCanonicalizer, "mir-canonicalizer",
Craig Topperaaf1db12017-11-03 18:02:46 +0000105 "Rename Register Operands Canonically", false, false)
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000106
107static std::vector<MachineBasicBlock *> GetRPOList(MachineFunction &MF) {
108 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
109 std::vector<MachineBasicBlock *> RPOList;
110 for (auto MBB : RPOT) {
111 RPOList.push_back(MBB);
112 }
113
114 return RPOList;
115}
116
Puyan Lotfia96b9332018-03-31 05:48:51 +0000117static bool
118rescheduleLexographically(std::vector<MachineInstr *> instructions,
119 MachineBasicBlock *MBB,
120 std::function<MachineBasicBlock::iterator()> getPos) {
121
122 bool Changed = false;
Puyan Lotfid8ca4dd2018-05-13 06:07:20 +0000123 using StringInstrPair = std::pair<std::string, MachineInstr *>;
124 std::vector<StringInstrPair> StringInstrMap;
Puyan Lotfia96b9332018-03-31 05:48:51 +0000125
126 for (auto *II : instructions) {
127 std::string S;
128 raw_string_ostream OS(S);
129 II->print(OS);
130 OS.flush();
131
132 // Trim the assignment, or start from the begining in the case of a store.
133 const size_t i = S.find("=");
Puyan Lotfid8ca4dd2018-05-13 06:07:20 +0000134 StringInstrMap.push_back({(i == std::string::npos) ? S : S.substr(i), II});
Puyan Lotfia96b9332018-03-31 05:48:51 +0000135 }
136
Fangrui Song3b35e172018-09-27 02:13:45 +0000137 llvm::sort(StringInstrMap,
138 [](const StringInstrPair &a, const StringInstrPair &b) -> bool {
139 return (a.first < b.first);
140 });
Puyan Lotfid8ca4dd2018-05-13 06:07:20 +0000141
Puyan Lotfia96b9332018-03-31 05:48:51 +0000142 for (auto &II : StringInstrMap) {
143
Nicola Zaghen0818e782018-05-14 12:53:11 +0000144 LLVM_DEBUG({
Puyan Lotfia96b9332018-03-31 05:48:51 +0000145 dbgs() << "Splicing ";
146 II.second->dump();
147 dbgs() << " right before: ";
148 getPos()->dump();
149 });
150
151 Changed = true;
152 MBB->splice(getPos(), MBB, II.second);
153 }
154
155 return Changed;
156}
157
158static bool rescheduleCanonically(unsigned &PseudoIdempotentInstCount,
159 MachineBasicBlock *MBB) {
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000160
161 bool Changed = false;
162
163 // Calculates the distance of MI from the begining of its parent BB.
164 auto getInstrIdx = [](const MachineInstr &MI) {
165 unsigned i = 0;
166 for (auto &CurMI : *MI.getParent()) {
167 if (&CurMI == &MI)
168 return i;
169 i++;
170 }
171 return ~0U;
172 };
173
174 // Pre-Populate vector of instructions to reschedule so that we don't
175 // clobber the iterator.
176 std::vector<MachineInstr *> Instructions;
177 for (auto &MI : *MBB) {
178 Instructions.push_back(&MI);
179 }
180
Puyan Lotfi29bc6472018-04-05 00:08:15 +0000181 std::map<MachineInstr *, std::vector<MachineInstr *>> MultiUsers;
Puyan Lotfia96b9332018-03-31 05:48:51 +0000182 std::vector<MachineInstr *> PseudoIdempotentInstructions;
183 std::vector<unsigned> PhysRegDefs;
184 for (auto *II : Instructions) {
185 for (unsigned i = 1; i < II->getNumOperands(); i++) {
186 MachineOperand &MO = II->getOperand(i);
187 if (!MO.isReg())
188 continue;
189
190 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
191 continue;
192
193 if (!MO.isDef())
194 continue;
195
196 PhysRegDefs.push_back(MO.getReg());
197 }
198 }
199
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000200 for (auto *II : Instructions) {
201 if (II->getNumOperands() == 0)
202 continue;
Puyan Lotfia96b9332018-03-31 05:48:51 +0000203 if (II->mayLoadOrStore())
204 continue;
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000205
206 MachineOperand &MO = II->getOperand(0);
207 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
208 continue;
Puyan Lotfia96b9332018-03-31 05:48:51 +0000209 if (!MO.isDef())
210 continue;
211
212 bool IsPseudoIdempotent = true;
213 for (unsigned i = 1; i < II->getNumOperands(); i++) {
214
215 if (II->getOperand(i).isImm()) {
216 continue;
217 }
218
219 if (II->getOperand(i).isReg()) {
220 if (!TargetRegisterInfo::isVirtualRegister(II->getOperand(i).getReg()))
221 if (llvm::find(PhysRegDefs, II->getOperand(i).getReg()) ==
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000222 PhysRegDefs.end()) {
Puyan Lotfia96b9332018-03-31 05:48:51 +0000223 continue;
224 }
225 }
226
227 IsPseudoIdempotent = false;
228 break;
229 }
230
231 if (IsPseudoIdempotent) {
232 PseudoIdempotentInstructions.push_back(II);
233 continue;
234 }
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000235
Nicola Zaghen0818e782018-05-14 12:53:11 +0000236 LLVM_DEBUG(dbgs() << "Operand " << 0 << " of "; II->dump(); MO.dump(););
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000237
238 MachineInstr *Def = II;
239 unsigned Distance = ~0U;
240 MachineInstr *UseToBringDefCloserTo = nullptr;
241 MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
242 for (auto &UO : MRI->use_nodbg_operands(MO.getReg())) {
243 MachineInstr *UseInst = UO.getParent();
244
245 const unsigned DefLoc = getInstrIdx(*Def);
246 const unsigned UseLoc = getInstrIdx(*UseInst);
247 const unsigned Delta = (UseLoc - DefLoc);
248
249 if (UseInst->getParent() != Def->getParent())
250 continue;
251 if (DefLoc >= UseLoc)
252 continue;
253
254 if (Delta < Distance) {
255 Distance = Delta;
256 UseToBringDefCloserTo = UseInst;
257 }
258 }
259
260 const auto BBE = MBB->instr_end();
261 MachineBasicBlock::iterator DefI = BBE;
262 MachineBasicBlock::iterator UseI = BBE;
263
264 for (auto BBI = MBB->instr_begin(); BBI != BBE; ++BBI) {
265
266 if (DefI != BBE && UseI != BBE)
267 break;
268
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000269 if (&*BBI == Def) {
270 DefI = BBI;
271 continue;
272 }
273
274 if (&*BBI == UseToBringDefCloserTo) {
275 UseI = BBI;
276 continue;
277 }
278 }
279
280 if (DefI == BBE || UseI == BBE)
281 continue;
282
Nicola Zaghen0818e782018-05-14 12:53:11 +0000283 LLVM_DEBUG({
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000284 dbgs() << "Splicing ";
285 DefI->dump();
286 dbgs() << " right before: ";
287 UseI->dump();
288 });
289
Puyan Lotfi29bc6472018-04-05 00:08:15 +0000290 MultiUsers[UseToBringDefCloserTo].push_back(Def);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000291 Changed = true;
292 MBB->splice(UseI, MBB, DefI);
293 }
294
Puyan Lotfi29bc6472018-04-05 00:08:15 +0000295 // Sort the defs for users of multiple defs lexographically.
296 for (const auto &E : MultiUsers) {
297
298 auto UseI =
299 std::find_if(MBB->instr_begin(), MBB->instr_end(),
300 [&](MachineInstr &MI) -> bool { return &MI == E.first; });
301
302 if (UseI == MBB->instr_end())
303 continue;
304
Nicola Zaghen0818e782018-05-14 12:53:11 +0000305 LLVM_DEBUG(
306 dbgs() << "Rescheduling Multi-Use Instructions Lexographically.";);
Puyan Lotfi29bc6472018-04-05 00:08:15 +0000307 Changed |= rescheduleLexographically(
308 E.second, MBB, [&]() -> MachineBasicBlock::iterator { return UseI; });
309 }
310
Puyan Lotfia96b9332018-03-31 05:48:51 +0000311 PseudoIdempotentInstCount = PseudoIdempotentInstructions.size();
Nicola Zaghen0818e782018-05-14 12:53:11 +0000312 LLVM_DEBUG(
313 dbgs() << "Rescheduling Idempotent Instructions Lexographically.";);
Puyan Lotfia96b9332018-03-31 05:48:51 +0000314 Changed |= rescheduleLexographically(
315 PseudoIdempotentInstructions, MBB,
316 [&]() -> MachineBasicBlock::iterator { return MBB->begin(); });
317
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000318 return Changed;
319}
320
Benjamin Kramerfd838282018-05-15 21:26:47 +0000321static bool propagateLocalCopies(MachineBasicBlock *MBB) {
Puyan Lotfif1f8a6d2018-04-16 09:03:03 +0000322 bool Changed = false;
323 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
324
325 std::vector<MachineInstr *> Copies;
326 for (MachineInstr &MI : MBB->instrs()) {
327 if (MI.isCopy())
328 Copies.push_back(&MI);
329 }
330
331 for (MachineInstr *MI : Copies) {
332
333 if (!MI->getOperand(0).isReg())
334 continue;
335 if (!MI->getOperand(1).isReg())
336 continue;
337
338 const unsigned Dst = MI->getOperand(0).getReg();
339 const unsigned Src = MI->getOperand(1).getReg();
340
341 if (!TargetRegisterInfo::isVirtualRegister(Dst))
342 continue;
343 if (!TargetRegisterInfo::isVirtualRegister(Src))
344 continue;
345 if (MRI.getRegClass(Dst) != MRI.getRegClass(Src))
346 continue;
347
348 for (auto UI = MRI.use_begin(Dst); UI != MRI.use_end(); ++UI) {
349 MachineOperand *MO = &*UI;
350 MO->setReg(Src);
351 Changed = true;
352 }
353
354 MI->eraseFromParent();
355 }
356
357 return Changed;
358}
359
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000360/// Here we find our candidates. What makes an interesting candidate?
361/// An candidate for a canonicalization tree root is normally any kind of
362/// instruction that causes side effects such as a store to memory or a copy to
363/// a physical register or a return instruction. We use these as an expression
364/// tree root that we walk inorder to build a canonical walk which should result
365/// in canoncal vreg renaming.
366static std::vector<MachineInstr *> populateCandidates(MachineBasicBlock *MBB) {
367 std::vector<MachineInstr *> Candidates;
368 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
369
370 for (auto II = MBB->begin(), IE = MBB->end(); II != IE; ++II) {
371 MachineInstr *MI = &*II;
372
373 bool DoesMISideEffect = false;
374
375 if (MI->getNumOperands() > 0 && MI->getOperand(0).isReg()) {
376 const unsigned Dst = MI->getOperand(0).getReg();
377 DoesMISideEffect |= !TargetRegisterInfo::isVirtualRegister(Dst);
378
379 for (auto UI = MRI.use_begin(Dst); UI != MRI.use_end(); ++UI) {
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000380 if (DoesMISideEffect)
381 break;
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000382 DoesMISideEffect |= (UI->getParent()->getParent() != MI->getParent());
383 }
384 }
385
386 if (!MI->mayStore() && !MI->isBranch() && !DoesMISideEffect)
387 continue;
388
Nicola Zaghen0818e782018-05-14 12:53:11 +0000389 LLVM_DEBUG(dbgs() << "Found Candidate: "; MI->dump(););
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000390 Candidates.push_back(MI);
391 }
392
393 return Candidates;
394}
395
Benjamin Kramer9a31efb2017-11-24 14:55:41 +0000396static void doCandidateWalk(std::vector<TypedVReg> &VRegs,
397 std::queue<TypedVReg> &RegQueue,
398 std::vector<MachineInstr *> &VisitedMIs,
399 const MachineBasicBlock *MBB) {
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000400
401 const MachineFunction &MF = *MBB->getParent();
402 const MachineRegisterInfo &MRI = MF.getRegInfo();
403
404 while (!RegQueue.empty()) {
405
406 auto TReg = RegQueue.front();
407 RegQueue.pop();
408
409 if (TReg.isFrameIndex()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000410 LLVM_DEBUG(dbgs() << "Popping frame index.\n";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000411 VRegs.push_back(TypedVReg(RSE_FrameIndex));
412 continue;
413 }
414
415 assert(TReg.isReg() && "Expected vreg or physreg.");
416 unsigned Reg = TReg.getReg();
417
418 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000419 LLVM_DEBUG({
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000420 dbgs() << "Popping vreg ";
421 MRI.def_begin(Reg)->dump();
422 dbgs() << "\n";
423 });
424
425 if (!llvm::any_of(VRegs, [&](const TypedVReg &TR) {
426 return TR.isReg() && TR.getReg() == Reg;
427 })) {
428 VRegs.push_back(TypedVReg(Reg));
429 }
430 } else {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000431 LLVM_DEBUG(dbgs() << "Popping physreg.\n";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000432 VRegs.push_back(TypedVReg(Reg));
433 continue;
434 }
435
436 for (auto RI = MRI.def_begin(Reg), RE = MRI.def_end(); RI != RE; ++RI) {
437 MachineInstr *Def = RI->getParent();
438
439 if (Def->getParent() != MBB)
440 continue;
441
442 if (llvm::any_of(VisitedMIs,
443 [&](const MachineInstr *VMI) { return Def == VMI; })) {
444 break;
445 }
446
Nicola Zaghen0818e782018-05-14 12:53:11 +0000447 LLVM_DEBUG({
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000448 dbgs() << "\n========================\n";
449 dbgs() << "Visited MI: ";
450 Def->dump();
451 dbgs() << "BB Name: " << Def->getParent()->getName() << "\n";
452 dbgs() << "\n========================\n";
453 });
454 VisitedMIs.push_back(Def);
455 for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
456
457 MachineOperand &MO = Def->getOperand(I);
458 if (MO.isFI()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000459 LLVM_DEBUG(dbgs() << "Pushing frame index.\n";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000460 RegQueue.push(TypedVReg(RSE_FrameIndex));
461 }
462
463 if (!MO.isReg())
464 continue;
465 RegQueue.push(TypedVReg(MO.getReg()));
466 }
467 }
468 }
469}
470
Benjamin Kramerfd838282018-05-15 21:26:47 +0000471namespace {
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000472class NamedVRegCursor {
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000473 MachineRegisterInfo &MRI;
474 unsigned virtualVRegNumber;
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000475
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000476public:
477 NamedVRegCursor(MachineRegisterInfo &MRI) : MRI(MRI) {
478 unsigned VRegGapIndex = 0;
479 const unsigned VR_GAP = (++VRegGapIndex * 1000);
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000480
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000481 unsigned I = MRI.createIncompleteVirtualRegister();
482 const unsigned E = (((I + VR_GAP) / VR_GAP) + 1) * VR_GAP;
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000483
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000484 virtualVRegNumber = E;
485 }
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000486
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000487 void SkipVRegs() {
488 unsigned VRegGapIndex = 1;
489 const unsigned VR_GAP = (++VRegGapIndex * 1000);
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000490
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000491 unsigned I = virtualVRegNumber;
492 const unsigned E = (((I + VR_GAP) / VR_GAP) + 1) * VR_GAP;
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000493
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000494 virtualVRegNumber = E;
495 }
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000496
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000497 unsigned getVirtualVReg() const { return virtualVRegNumber; }
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000498
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000499 unsigned incrementVirtualVReg(unsigned incr = 1) {
500 virtualVRegNumber += incr;
501 return virtualVRegNumber;
502 }
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000503
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000504 unsigned createVirtualRegister(const TargetRegisterClass *RC) {
505 std::string S;
506 raw_string_ostream OS(S);
507 OS << "namedVReg" << (virtualVRegNumber & ~0x80000000);
508 OS.flush();
509 virtualVRegNumber++;
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000510
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000511 return MRI.createVirtualRegister(RC, OS.str());
512 }
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000513};
Benjamin Kramerfd838282018-05-15 21:26:47 +0000514} // namespace
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000515
516static std::map<unsigned, unsigned>
517GetVRegRenameMap(const std::vector<TypedVReg> &VRegs,
518 const std::vector<unsigned> &renamedInOtherBB,
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000519 MachineRegisterInfo &MRI, NamedVRegCursor &NVC) {
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000520 std::map<unsigned, unsigned> VRegRenameMap;
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000521 bool FirstCandidate = true;
522
523 for (auto &vreg : VRegs) {
524 if (vreg.isFrameIndex()) {
525 // We skip one vreg for any frame index because there is a good chance
526 // (especially when comparing SelectionDAG to GlobalISel generated MIR)
527 // that in the other file we are just getting an incoming vreg that comes
528 // from a copy from a frame index. So it's safe to skip by one.
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000529 unsigned LastRenameReg = NVC.incrementVirtualVReg();
530 (void)LastRenameReg;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000531 LLVM_DEBUG(dbgs() << "Skipping rename for FI " << LastRenameReg << "\n";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000532 continue;
533 } else if (vreg.isCandidate()) {
534
535 // After the first candidate, for every subsequent candidate, we skip mod
536 // 10 registers so that the candidates are more likely to start at the
537 // same vreg number making it more likely that the canonical walk from the
538 // candidate insruction. We don't need to skip from the first candidate of
539 // the BasicBlock because we already skip ahead several vregs for each BB.
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000540 unsigned LastRenameReg = NVC.getVirtualVReg();
541 if (FirstCandidate)
542 NVC.incrementVirtualVReg(LastRenameReg % 10);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000543 FirstCandidate = false;
544 continue;
545 } else if (!TargetRegisterInfo::isVirtualRegister(vreg.getReg())) {
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000546 unsigned LastRenameReg = NVC.incrementVirtualVReg();
547 (void)LastRenameReg;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000548 LLVM_DEBUG({
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000549 dbgs() << "Skipping rename for Phys Reg " << LastRenameReg << "\n";
550 });
551 continue;
552 }
553
554 auto Reg = vreg.getReg();
555 if (llvm::find(renamedInOtherBB, Reg) != renamedInOtherBB.end()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000556 LLVM_DEBUG(dbgs() << "Vreg " << Reg
557 << " already renamed in other BB.\n";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000558 continue;
559 }
560
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000561 auto Rename = NVC.createVirtualRegister(MRI.getRegClass(Reg));
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000562
563 if (VRegRenameMap.find(Reg) == VRegRenameMap.end()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000564 LLVM_DEBUG(dbgs() << "Mapping vreg ";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000565 if (MRI.reg_begin(Reg) != MRI.reg_end()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000566 LLVM_DEBUG(auto foo = &*MRI.reg_begin(Reg); foo->dump(););
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000567 } else {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000568 LLVM_DEBUG(dbgs() << Reg;);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000569 }
Nicola Zaghen0818e782018-05-14 12:53:11 +0000570 LLVM_DEBUG(dbgs() << " to ";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000571 if (MRI.reg_begin(Rename) != MRI.reg_end()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000572 LLVM_DEBUG(auto foo = &*MRI.reg_begin(Rename); foo->dump(););
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000573 } else {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000574 LLVM_DEBUG(dbgs() << Rename;);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000575 }
Nicola Zaghen0818e782018-05-14 12:53:11 +0000576 LLVM_DEBUG(dbgs() << "\n";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000577
578 VRegRenameMap.insert(std::pair<unsigned, unsigned>(Reg, Rename));
579 }
580 }
581
582 return VRegRenameMap;
583}
584
585static bool doVRegRenaming(std::vector<unsigned> &RenamedInOtherBB,
586 const std::map<unsigned, unsigned> &VRegRenameMap,
587 MachineRegisterInfo &MRI) {
588 bool Changed = false;
589 for (auto I = VRegRenameMap.begin(), E = VRegRenameMap.end(); I != E; ++I) {
590
591 auto VReg = I->first;
592 auto Rename = I->second;
593
594 RenamedInOtherBB.push_back(Rename);
595
596 std::vector<MachineOperand *> RenameMOs;
597 for (auto &MO : MRI.reg_operands(VReg)) {
598 RenameMOs.push_back(&MO);
599 }
600
601 for (auto *MO : RenameMOs) {
602 Changed = true;
603 MO->setReg(Rename);
604
605 if (!MO->isDef())
606 MO->setIsKill(false);
607 }
608 }
609
610 return Changed;
611}
612
613static bool doDefKillClear(MachineBasicBlock *MBB) {
614 bool Changed = false;
615
616 for (auto &MI : *MBB) {
617 for (auto &MO : MI.operands()) {
618 if (!MO.isReg())
619 continue;
620 if (!MO.isDef() && MO.isKill()) {
621 Changed = true;
622 MO.setIsKill(false);
623 }
624
625 if (MO.isDef() && MO.isDead()) {
626 Changed = true;
627 MO.setIsDead(false);
628 }
629 }
630 }
631
632 return Changed;
633}
634
635static bool runOnBasicBlock(MachineBasicBlock *MBB,
636 std::vector<StringRef> &bbNames,
637 std::vector<unsigned> &renamedInOtherBB,
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000638 unsigned &basicBlockNum, unsigned &VRegGapIndex,
639 NamedVRegCursor &NVC) {
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000640
641 if (CanonicalizeBasicBlockNumber != ~0U) {
642 if (CanonicalizeBasicBlockNumber != basicBlockNum++)
643 return false;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000644 LLVM_DEBUG(dbgs() << "\n Canonicalizing BasicBlock " << MBB->getName()
645 << "\n";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000646 }
647
648 if (llvm::find(bbNames, MBB->getName()) != bbNames.end()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000649 LLVM_DEBUG({
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000650 dbgs() << "Found potentially duplicate BasicBlocks: " << MBB->getName()
651 << "\n";
652 });
653 return false;
654 }
655
Nicola Zaghen0818e782018-05-14 12:53:11 +0000656 LLVM_DEBUG({
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000657 dbgs() << "\n\n NEW BASIC BLOCK: " << MBB->getName() << " \n\n";
658 dbgs() << "\n\n================================================\n\n";
659 });
660
661 bool Changed = false;
662 MachineFunction &MF = *MBB->getParent();
663 MachineRegisterInfo &MRI = MF.getRegInfo();
664
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000665 bbNames.push_back(MBB->getName());
Nicola Zaghen0818e782018-05-14 12:53:11 +0000666 LLVM_DEBUG(dbgs() << "\n\n NEW BASIC BLOCK: " << MBB->getName() << "\n\n";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000667
Nicola Zaghen0818e782018-05-14 12:53:11 +0000668 LLVM_DEBUG(dbgs() << "MBB Before Canonical Copy Propagation:\n";
669 MBB->dump(););
Puyan Lotfif1f8a6d2018-04-16 09:03:03 +0000670 Changed |= propagateLocalCopies(MBB);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000671 LLVM_DEBUG(dbgs() << "MBB After Canonical Copy Propagation:\n"; MBB->dump(););
Puyan Lotfif1f8a6d2018-04-16 09:03:03 +0000672
Nicola Zaghen0818e782018-05-14 12:53:11 +0000673 LLVM_DEBUG(dbgs() << "MBB Before Scheduling:\n"; MBB->dump(););
Puyan Lotfia96b9332018-03-31 05:48:51 +0000674 unsigned IdempotentInstCount = 0;
675 Changed |= rescheduleCanonically(IdempotentInstCount, MBB);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000676 LLVM_DEBUG(dbgs() << "MBB After Scheduling:\n"; MBB->dump(););
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000677
678 std::vector<MachineInstr *> Candidates = populateCandidates(MBB);
679 std::vector<MachineInstr *> VisitedMIs;
Fangrui Song53a62242018-11-17 01:44:25 +0000680 llvm::copy(Candidates, std::back_inserter(VisitedMIs));
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000681
682 std::vector<TypedVReg> VRegs;
683 for (auto candidate : Candidates) {
684 VRegs.push_back(TypedVReg(RSE_NewCandidate));
685
686 std::queue<TypedVReg> RegQueue;
687
688 // Here we walk the vreg operands of a non-root node along our walk.
689 // The root nodes are the original candidates (stores normally).
690 // These are normally not the root nodes (except for the case of copies to
691 // physical registers).
692 for (unsigned i = 1; i < candidate->getNumOperands(); i++) {
693 if (candidate->mayStore() || candidate->isBranch())
694 break;
695
696 MachineOperand &MO = candidate->getOperand(i);
697 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
698 continue;
699
Nicola Zaghen0818e782018-05-14 12:53:11 +0000700 LLVM_DEBUG(dbgs() << "Enqueue register"; MO.dump(); dbgs() << "\n";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000701 RegQueue.push(TypedVReg(MO.getReg()));
702 }
703
704 // Here we walk the root candidates. We start from the 0th operand because
705 // the root is normally a store to a vreg.
706 for (unsigned i = 0; i < candidate->getNumOperands(); i++) {
707
708 if (!candidate->mayStore() && !candidate->isBranch())
709 break;
710
711 MachineOperand &MO = candidate->getOperand(i);
712
713 // TODO: Do we want to only add vregs here?
714 if (!MO.isReg() && !MO.isFI())
715 continue;
716
Nicola Zaghen0818e782018-05-14 12:53:11 +0000717 LLVM_DEBUG(dbgs() << "Enqueue Reg/FI"; MO.dump(); dbgs() << "\n";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000718
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000719 RegQueue.push(MO.isReg() ? TypedVReg(MO.getReg())
720 : TypedVReg(RSE_FrameIndex));
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000721 }
722
723 doCandidateWalk(VRegs, RegQueue, VisitedMIs, MBB);
724 }
725
726 // If we have populated no vregs to rename then bail.
727 // The rest of this function does the vreg remaping.
728 if (VRegs.size() == 0)
729 return Changed;
730
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000731 auto VRegRenameMap = GetVRegRenameMap(VRegs, renamedInOtherBB, MRI, NVC);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000732 Changed |= doVRegRenaming(renamedInOtherBB, VRegRenameMap, MRI);
Puyan Lotfia96b9332018-03-31 05:48:51 +0000733
734 // Here we renumber the def vregs for the idempotent instructions from the top
735 // of the MachineBasicBlock so that they are named in the order that we sorted
736 // them alphabetically. Eventually we wont need SkipVRegs because we will use
737 // named vregs instead.
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000738 NVC.SkipVRegs();
Puyan Lotfia96b9332018-03-31 05:48:51 +0000739
740 auto MII = MBB->begin();
741 for (unsigned i = 0; i < IdempotentInstCount && MII != MBB->end(); ++i) {
742 MachineInstr &MI = *MII++;
743 Changed = true;
744 unsigned vRegToRename = MI.getOperand(0).getReg();
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000745 auto Rename = NVC.createVirtualRegister(MRI.getRegClass(vRegToRename));
Puyan Lotfia96b9332018-03-31 05:48:51 +0000746
747 std::vector<MachineOperand *> RenameMOs;
748 for (auto &MO : MRI.reg_operands(vRegToRename)) {
749 RenameMOs.push_back(&MO);
750 }
751
752 for (auto *MO : RenameMOs) {
753 MO->setReg(Rename);
754 }
755 }
756
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000757 Changed |= doDefKillClear(MBB);
758
Nicola Zaghen0818e782018-05-14 12:53:11 +0000759 LLVM_DEBUG(dbgs() << "Updated MachineBasicBlock:\n"; MBB->dump();
760 dbgs() << "\n";);
761 LLVM_DEBUG(
762 dbgs() << "\n\n================================================\n\n");
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000763 return Changed;
764}
765
766bool MIRCanonicalizer::runOnMachineFunction(MachineFunction &MF) {
767
768 static unsigned functionNum = 0;
769 if (CanonicalizeFunctionNumber != ~0U) {
770 if (CanonicalizeFunctionNumber != functionNum++)
771 return false;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000772 LLVM_DEBUG(dbgs() << "\n Canonicalizing Function " << MF.getName()
773 << "\n";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000774 }
775
776 // we need a valid vreg to create a vreg type for skipping all those
777 // stray vreg numbers so reach alignment/canonical vreg values.
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000778 std::vector<MachineBasicBlock *> RPOList = GetRPOList(MF);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000779
Nicola Zaghen0818e782018-05-14 12:53:11 +0000780 LLVM_DEBUG(
781 dbgs() << "\n\n NEW MACHINE FUNCTION: " << MF.getName() << " \n\n";
782 dbgs() << "\n\n================================================\n\n";
783 dbgs() << "Total Basic Blocks: " << RPOList.size() << "\n";
784 for (auto MBB
785 : RPOList) { dbgs() << MBB->getName() << "\n"; } dbgs()
786 << "\n\n================================================\n\n";);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000787
788 std::vector<StringRef> BBNames;
789 std::vector<unsigned> RenamedInOtherBB;
790
791 unsigned GapIdx = 0;
792 unsigned BBNum = 0;
793
794 bool Changed = false;
795
Puyan Lotfia7f9b6a2018-04-05 00:27:15 +0000796 MachineRegisterInfo &MRI = MF.getRegInfo();
797 NamedVRegCursor NVC(MRI);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000798 for (auto MBB : RPOList)
Puyan Lotfi388ad3d2018-04-16 08:12:15 +0000799 Changed |=
800 runOnBasicBlock(MBB, BBNames, RenamedInOtherBB, BBNum, GapIdx, NVC);
Puyan Lotfi0ae3f322017-11-02 23:37:32 +0000801
802 return Changed;
803}