blob: a9b49457badd91e28c3178b92a2bdeda00a39691 [file] [log] [blame]
Puyan Lotfia521c4ac52017-11-02 23:37:32 +00001//===-------------- MIRCanonicalizer.cpp - MIR Canonicalizer --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Puyan Lotfia521c4ac52017-11-02 23:37:32 +00006//
7//===----------------------------------------------------------------------===//
8//
9// The purpose of this pass is to employ a canonical code transformation so
10// that code compiled with slightly different IR passes can be diffed more
11// effectively than otherwise. This is done by renaming vregs in a given
12// LiveRange in a canonical way. This pass also does a pseudo-scheduling to
13// move defs closer to their use inorder to reduce diffs caused by slightly
14// different schedules.
15//
16// Basic Usage:
17//
18// llc -o - -run-pass mir-canonicalizer example.mir
19//
20// Reorders instructions canonically.
21// Renames virtual register operands canonically.
22// Strips certain MIR artifacts (optionally).
23//
24//===----------------------------------------------------------------------===//
25
26#include "llvm/ADT/PostOrderIterator.h"
27#include "llvm/ADT/STLExtras.h"
Puyan Lotfia521c4ac52017-11-02 23:37:32 +000028#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000031#include "llvm/CodeGen/Passes.h"
Puyan Lotfia521c4ac52017-11-02 23:37:32 +000032#include "llvm/Support/raw_ostream.h"
Puyan Lotfia521c4ac52017-11-02 23:37:32 +000033
34#include <queue>
35
36using namespace llvm;
37
38namespace llvm {
39extern char &MIRCanonicalizerID;
40} // namespace llvm
41
42#define DEBUG_TYPE "mir-canonicalizer"
43
44static cl::opt<unsigned>
Puyan Lotfi6ea89b42018-04-16 08:12:15 +000045 CanonicalizeFunctionNumber("canon-nth-function", cl::Hidden, cl::init(~0u),
46 cl::value_desc("N"),
47 cl::desc("Function number to canonicalize."));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +000048
Puyan Lotfi6ea89b42018-04-16 08:12:15 +000049static cl::opt<unsigned> CanonicalizeBasicBlockNumber(
50 "canon-nth-basicblock", cl::Hidden, cl::init(~0u), cl::value_desc("N"),
51 cl::desc("BasicBlock number to canonicalize."));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +000052
53namespace {
54
55class MIRCanonicalizer : public MachineFunctionPass {
56public:
57 static char ID;
58 MIRCanonicalizer() : MachineFunctionPass(ID) {}
59
60 StringRef getPassName() const override {
61 return "Rename register operands in a canonical ordering.";
62 }
63
64 void getAnalysisUsage(AnalysisUsage &AU) const override {
65 AU.setPreservesCFG();
66 MachineFunctionPass::getAnalysisUsage(AU);
67 }
68
69 bool runOnMachineFunction(MachineFunction &MF) override;
70};
71
72} // end anonymous namespace
73
74enum VRType { RSE_Reg = 0, RSE_FrameIndex, RSE_NewCandidate };
75class TypedVReg {
76 VRType type;
77 unsigned reg;
78
79public:
80 TypedVReg(unsigned reg) : type(RSE_Reg), reg(reg) {}
81 TypedVReg(VRType type) : type(type), reg(~0U) {
82 assert(type != RSE_Reg && "Expected a non-register type.");
83 }
84
Puyan Lotfi6ea89b42018-04-16 08:12:15 +000085 bool isReg() const { return type == RSE_Reg; }
86 bool isFrameIndex() const { return type == RSE_FrameIndex; }
87 bool isCandidate() const { return type == RSE_NewCandidate; }
Puyan Lotfia521c4ac52017-11-02 23:37:32 +000088
89 VRType getType() const { return type; }
90 unsigned getReg() const {
91 assert(this->isReg() && "Expected a virtual or physical register.");
92 return reg;
93 }
94};
95
96char MIRCanonicalizer::ID;
97
98char &llvm::MIRCanonicalizerID = MIRCanonicalizer::ID;
99
100INITIALIZE_PASS_BEGIN(MIRCanonicalizer, "mir-canonicalizer",
Craig Topper666e23b2017-11-03 18:02:46 +0000101 "Rename Register Operands Canonically", false, false)
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000102
103INITIALIZE_PASS_END(MIRCanonicalizer, "mir-canonicalizer",
Craig Topper666e23b2017-11-03 18:02:46 +0000104 "Rename Register Operands Canonically", false, false)
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000105
106static std::vector<MachineBasicBlock *> GetRPOList(MachineFunction &MF) {
Puyan Lotfidaaecf92019-05-30 21:37:25 +0000107 if (MF.empty())
108 return {};
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000109 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
110 std::vector<MachineBasicBlock *> RPOList;
111 for (auto MBB : RPOT) {
112 RPOList.push_back(MBB);
113 }
114
115 return RPOList;
116}
117
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000118static bool
119rescheduleLexographically(std::vector<MachineInstr *> instructions,
120 MachineBasicBlock *MBB,
121 std::function<MachineBasicBlock::iterator()> getPos) {
122
123 bool Changed = false;
Puyan Lotfi380a6f52018-05-13 06:07:20 +0000124 using StringInstrPair = std::pair<std::string, MachineInstr *>;
125 std::vector<StringInstrPair> StringInstrMap;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000126
127 for (auto *II : instructions) {
128 std::string S;
129 raw_string_ostream OS(S);
130 II->print(OS);
131 OS.flush();
132
133 // Trim the assignment, or start from the begining in the case of a store.
134 const size_t i = S.find("=");
Puyan Lotfi380a6f52018-05-13 06:07:20 +0000135 StringInstrMap.push_back({(i == std::string::npos) ? S : S.substr(i), II});
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000136 }
137
Fangrui Song0cac7262018-09-27 02:13:45 +0000138 llvm::sort(StringInstrMap,
139 [](const StringInstrPair &a, const StringInstrPair &b) -> bool {
140 return (a.first < b.first);
141 });
Puyan Lotfi380a6f52018-05-13 06:07:20 +0000142
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000143 for (auto &II : StringInstrMap) {
144
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000145 LLVM_DEBUG({
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000146 dbgs() << "Splicing ";
147 II.second->dump();
148 dbgs() << " right before: ";
149 getPos()->dump();
150 });
151
152 Changed = true;
153 MBB->splice(getPos(), MBB, II.second);
154 }
155
156 return Changed;
157}
158
159static bool rescheduleCanonically(unsigned &PseudoIdempotentInstCount,
160 MachineBasicBlock *MBB) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000161
162 bool Changed = false;
163
164 // Calculates the distance of MI from the begining of its parent BB.
165 auto getInstrIdx = [](const MachineInstr &MI) {
166 unsigned i = 0;
167 for (auto &CurMI : *MI.getParent()) {
168 if (&CurMI == &MI)
169 return i;
170 i++;
171 }
172 return ~0U;
173 };
174
175 // Pre-Populate vector of instructions to reschedule so that we don't
176 // clobber the iterator.
177 std::vector<MachineInstr *> Instructions;
178 for (auto &MI : *MBB) {
179 Instructions.push_back(&MI);
180 }
181
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000182 std::map<MachineInstr *, std::vector<MachineInstr *>> MultiUsers;
Puyan Lotfi4d894622019-06-11 00:00:25 +0000183 std::map<unsigned, MachineInstr *> MultiUserLookup;
184 unsigned UseToBringDefCloserToCount = 0;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000185 std::vector<MachineInstr *> PseudoIdempotentInstructions;
186 std::vector<unsigned> PhysRegDefs;
187 for (auto *II : Instructions) {
188 for (unsigned i = 1; i < II->getNumOperands(); i++) {
189 MachineOperand &MO = II->getOperand(i);
190 if (!MO.isReg())
191 continue;
192
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000193 if (Register::isVirtualRegister(MO.getReg()))
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000194 continue;
195
196 if (!MO.isDef())
197 continue;
198
199 PhysRegDefs.push_back(MO.getReg());
200 }
201 }
202
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000203 for (auto *II : Instructions) {
204 if (II->getNumOperands() == 0)
205 continue;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000206 if (II->mayLoadOrStore())
207 continue;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000208
209 MachineOperand &MO = II->getOperand(0);
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000210 if (!MO.isReg() || !Register::isVirtualRegister(MO.getReg()))
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000211 continue;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000212 if (!MO.isDef())
213 continue;
214
215 bool IsPseudoIdempotent = true;
216 for (unsigned i = 1; i < II->getNumOperands(); i++) {
217
218 if (II->getOperand(i).isImm()) {
219 continue;
220 }
221
222 if (II->getOperand(i).isReg()) {
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000223 if (!Register::isVirtualRegister(II->getOperand(i).getReg()))
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000224 if (llvm::find(PhysRegDefs, II->getOperand(i).getReg()) ==
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000225 PhysRegDefs.end()) {
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000226 continue;
227 }
228 }
229
230 IsPseudoIdempotent = false;
231 break;
232 }
233
234 if (IsPseudoIdempotent) {
235 PseudoIdempotentInstructions.push_back(II);
236 continue;
237 }
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000238
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000239 LLVM_DEBUG(dbgs() << "Operand " << 0 << " of "; II->dump(); MO.dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000240
241 MachineInstr *Def = II;
242 unsigned Distance = ~0U;
243 MachineInstr *UseToBringDefCloserTo = nullptr;
244 MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
245 for (auto &UO : MRI->use_nodbg_operands(MO.getReg())) {
246 MachineInstr *UseInst = UO.getParent();
247
248 const unsigned DefLoc = getInstrIdx(*Def);
249 const unsigned UseLoc = getInstrIdx(*UseInst);
250 const unsigned Delta = (UseLoc - DefLoc);
251
252 if (UseInst->getParent() != Def->getParent())
253 continue;
254 if (DefLoc >= UseLoc)
255 continue;
256
257 if (Delta < Distance) {
258 Distance = Delta;
259 UseToBringDefCloserTo = UseInst;
Puyan Lotfi4d894622019-06-11 00:00:25 +0000260 MultiUserLookup[UseToBringDefCloserToCount++] = UseToBringDefCloserTo;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000261 }
262 }
263
264 const auto BBE = MBB->instr_end();
265 MachineBasicBlock::iterator DefI = BBE;
266 MachineBasicBlock::iterator UseI = BBE;
267
268 for (auto BBI = MBB->instr_begin(); BBI != BBE; ++BBI) {
269
270 if (DefI != BBE && UseI != BBE)
271 break;
272
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000273 if (&*BBI == Def) {
274 DefI = BBI;
275 continue;
276 }
277
278 if (&*BBI == UseToBringDefCloserTo) {
279 UseI = BBI;
280 continue;
281 }
282 }
283
284 if (DefI == BBE || UseI == BBE)
285 continue;
286
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000287 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000288 dbgs() << "Splicing ";
289 DefI->dump();
290 dbgs() << " right before: ";
291 UseI->dump();
292 });
293
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000294 MultiUsers[UseToBringDefCloserTo].push_back(Def);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000295 Changed = true;
296 MBB->splice(UseI, MBB, DefI);
297 }
298
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000299 // Sort the defs for users of multiple defs lexographically.
Puyan Lotfi4d894622019-06-11 00:00:25 +0000300 for (const auto &E : MultiUserLookup) {
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000301
302 auto UseI =
303 std::find_if(MBB->instr_begin(), MBB->instr_end(),
Puyan Lotfi4d894622019-06-11 00:00:25 +0000304 [&](MachineInstr &MI) -> bool { return &MI == E.second; });
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000305
306 if (UseI == MBB->instr_end())
307 continue;
308
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000309 LLVM_DEBUG(
310 dbgs() << "Rescheduling Multi-Use Instructions Lexographically.";);
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000311 Changed |= rescheduleLexographically(
Puyan Lotfi4d894622019-06-11 00:00:25 +0000312 MultiUsers[E.second], MBB,
313 [&]() -> MachineBasicBlock::iterator { return UseI; });
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000314 }
315
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000316 PseudoIdempotentInstCount = PseudoIdempotentInstructions.size();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000317 LLVM_DEBUG(
318 dbgs() << "Rescheduling Idempotent Instructions Lexographically.";);
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000319 Changed |= rescheduleLexographically(
320 PseudoIdempotentInstructions, MBB,
321 [&]() -> MachineBasicBlock::iterator { return MBB->begin(); });
322
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000323 return Changed;
324}
325
Benjamin Kramer651d0bf2018-05-15 21:26:47 +0000326static bool propagateLocalCopies(MachineBasicBlock *MBB) {
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000327 bool Changed = false;
328 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
329
330 std::vector<MachineInstr *> Copies;
331 for (MachineInstr &MI : MBB->instrs()) {
332 if (MI.isCopy())
333 Copies.push_back(&MI);
334 }
335
336 for (MachineInstr *MI : Copies) {
337
338 if (!MI->getOperand(0).isReg())
339 continue;
340 if (!MI->getOperand(1).isReg())
341 continue;
342
Daniel Sanders0c476112019-08-15 19:22:08 +0000343 const Register Dst = MI->getOperand(0).getReg();
344 const Register Src = MI->getOperand(1).getReg();
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000345
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000346 if (!Register::isVirtualRegister(Dst))
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000347 continue;
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000348 if (!Register::isVirtualRegister(Src))
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000349 continue;
Puyan Lotfi2a901402019-05-31 04:49:58 +0000350 // Not folding COPY instructions if regbankselect has not set the RCs.
351 // Why are we only considering Register Classes? Because the verifier
352 // sometimes gets upset if the register classes don't match even if the
353 // types do. A future patch might add COPY folding for matching types in
354 // pre-registerbankselect code.
355 if (!MRI.getRegClassOrNull(Dst))
356 continue;
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000357 if (MRI.getRegClass(Dst) != MRI.getRegClass(Src))
358 continue;
359
Puyan Lotfi2a901402019-05-31 04:49:58 +0000360 std::vector<MachineOperand *> Uses;
361 for (auto UI = MRI.use_begin(Dst); UI != MRI.use_end(); ++UI)
362 Uses.push_back(&*UI);
363 for (auto *MO : Uses)
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000364 MO->setReg(Src);
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000365
Puyan Lotfi2a901402019-05-31 04:49:58 +0000366 Changed = true;
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000367 MI->eraseFromParent();
368 }
369
370 return Changed;
371}
372
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000373/// Here we find our candidates. What makes an interesting candidate?
374/// An candidate for a canonicalization tree root is normally any kind of
375/// instruction that causes side effects such as a store to memory or a copy to
376/// a physical register or a return instruction. We use these as an expression
377/// tree root that we walk inorder to build a canonical walk which should result
378/// in canoncal vreg renaming.
379static std::vector<MachineInstr *> populateCandidates(MachineBasicBlock *MBB) {
380 std::vector<MachineInstr *> Candidates;
381 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
382
383 for (auto II = MBB->begin(), IE = MBB->end(); II != IE; ++II) {
384 MachineInstr *MI = &*II;
385
386 bool DoesMISideEffect = false;
387
388 if (MI->getNumOperands() > 0 && MI->getOperand(0).isReg()) {
Daniel Sanders0c476112019-08-15 19:22:08 +0000389 const Register Dst = MI->getOperand(0).getReg();
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000390 DoesMISideEffect |= !Register::isVirtualRegister(Dst);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000391
392 for (auto UI = MRI.use_begin(Dst); UI != MRI.use_end(); ++UI) {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000393 if (DoesMISideEffect)
394 break;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000395 DoesMISideEffect |= (UI->getParent()->getParent() != MI->getParent());
396 }
397 }
398
399 if (!MI->mayStore() && !MI->isBranch() && !DoesMISideEffect)
400 continue;
401
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000402 LLVM_DEBUG(dbgs() << "Found Candidate: "; MI->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000403 Candidates.push_back(MI);
404 }
405
406 return Candidates;
407}
408
Benjamin Kramer51ebcaa2017-11-24 14:55:41 +0000409static void doCandidateWalk(std::vector<TypedVReg> &VRegs,
410 std::queue<TypedVReg> &RegQueue,
411 std::vector<MachineInstr *> &VisitedMIs,
412 const MachineBasicBlock *MBB) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000413
414 const MachineFunction &MF = *MBB->getParent();
415 const MachineRegisterInfo &MRI = MF.getRegInfo();
416
417 while (!RegQueue.empty()) {
418
419 auto TReg = RegQueue.front();
420 RegQueue.pop();
421
422 if (TReg.isFrameIndex()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000423 LLVM_DEBUG(dbgs() << "Popping frame index.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000424 VRegs.push_back(TypedVReg(RSE_FrameIndex));
425 continue;
426 }
427
428 assert(TReg.isReg() && "Expected vreg or physreg.");
429 unsigned Reg = TReg.getReg();
430
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000431 if (Register::isVirtualRegister(Reg)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000432 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000433 dbgs() << "Popping vreg ";
434 MRI.def_begin(Reg)->dump();
435 dbgs() << "\n";
436 });
437
438 if (!llvm::any_of(VRegs, [&](const TypedVReg &TR) {
439 return TR.isReg() && TR.getReg() == Reg;
440 })) {
441 VRegs.push_back(TypedVReg(Reg));
442 }
443 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000444 LLVM_DEBUG(dbgs() << "Popping physreg.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000445 VRegs.push_back(TypedVReg(Reg));
446 continue;
447 }
448
449 for (auto RI = MRI.def_begin(Reg), RE = MRI.def_end(); RI != RE; ++RI) {
450 MachineInstr *Def = RI->getParent();
451
452 if (Def->getParent() != MBB)
453 continue;
454
455 if (llvm::any_of(VisitedMIs,
456 [&](const MachineInstr *VMI) { return Def == VMI; })) {
457 break;
458 }
459
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000460 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000461 dbgs() << "\n========================\n";
462 dbgs() << "Visited MI: ";
463 Def->dump();
464 dbgs() << "BB Name: " << Def->getParent()->getName() << "\n";
465 dbgs() << "\n========================\n";
466 });
467 VisitedMIs.push_back(Def);
468 for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
469
470 MachineOperand &MO = Def->getOperand(I);
471 if (MO.isFI()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000472 LLVM_DEBUG(dbgs() << "Pushing frame index.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000473 RegQueue.push(TypedVReg(RSE_FrameIndex));
474 }
475
476 if (!MO.isReg())
477 continue;
478 RegQueue.push(TypedVReg(MO.getReg()));
479 }
480 }
481 }
482}
483
Benjamin Kramer651d0bf2018-05-15 21:26:47 +0000484namespace {
Puyan Lotfid6f73132018-04-05 00:27:15 +0000485class NamedVRegCursor {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000486 MachineRegisterInfo &MRI;
487 unsigned virtualVRegNumber;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000488
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000489public:
Puyan Lotfi0d63cef2019-05-31 06:02:38 +0000490 NamedVRegCursor(MachineRegisterInfo &MRI) : MRI(MRI), virtualVRegNumber(0) {}
Puyan Lotfid6f73132018-04-05 00:27:15 +0000491
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000492 void SkipVRegs() {
493 unsigned VRegGapIndex = 1;
Puyan Lotfi0d63cef2019-05-31 06:02:38 +0000494 if (!virtualVRegNumber) {
495 VRegGapIndex = 0;
496 virtualVRegNumber = MRI.createIncompleteVirtualRegister();
497 }
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000498 const unsigned VR_GAP = (++VRegGapIndex * 1000);
Puyan Lotfid6f73132018-04-05 00:27:15 +0000499
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000500 unsigned I = virtualVRegNumber;
501 const unsigned E = (((I + VR_GAP) / VR_GAP) + 1) * VR_GAP;
Puyan Lotfid6f73132018-04-05 00:27:15 +0000502
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000503 virtualVRegNumber = E;
504 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000505
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000506 unsigned getVirtualVReg() const { return virtualVRegNumber; }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000507
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000508 unsigned incrementVirtualVReg(unsigned incr = 1) {
509 virtualVRegNumber += incr;
510 return virtualVRegNumber;
511 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000512
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000513 unsigned createVirtualRegister(unsigned VReg) {
Puyan Lotfi0d63cef2019-05-31 06:02:38 +0000514 if (!virtualVRegNumber)
515 SkipVRegs();
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000516 std::string S;
517 raw_string_ostream OS(S);
518 OS << "namedVReg" << (virtualVRegNumber & ~0x80000000);
519 OS.flush();
520 virtualVRegNumber++;
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000521 if (auto RC = MRI.getRegClassOrNull(VReg))
522 return MRI.createVirtualRegister(RC, OS.str());
523 return MRI.createGenericVirtualRegister(MRI.getType(VReg), OS.str());
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000524 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000525};
Benjamin Kramer651d0bf2018-05-15 21:26:47 +0000526} // namespace
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000527
528static std::map<unsigned, unsigned>
529GetVRegRenameMap(const std::vector<TypedVReg> &VRegs,
530 const std::vector<unsigned> &renamedInOtherBB,
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000531 MachineRegisterInfo &MRI, NamedVRegCursor &NVC) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000532 std::map<unsigned, unsigned> VRegRenameMap;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000533 bool FirstCandidate = true;
534
535 for (auto &vreg : VRegs) {
536 if (vreg.isFrameIndex()) {
537 // We skip one vreg for any frame index because there is a good chance
538 // (especially when comparing SelectionDAG to GlobalISel generated MIR)
539 // that in the other file we are just getting an incoming vreg that comes
540 // from a copy from a frame index. So it's safe to skip by one.
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000541 unsigned LastRenameReg = NVC.incrementVirtualVReg();
542 (void)LastRenameReg;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000543 LLVM_DEBUG(dbgs() << "Skipping rename for FI " << LastRenameReg << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000544 continue;
545 } else if (vreg.isCandidate()) {
546
547 // After the first candidate, for every subsequent candidate, we skip mod
548 // 10 registers so that the candidates are more likely to start at the
549 // same vreg number making it more likely that the canonical walk from the
550 // candidate insruction. We don't need to skip from the first candidate of
551 // the BasicBlock because we already skip ahead several vregs for each BB.
Puyan Lotfid6f73132018-04-05 00:27:15 +0000552 unsigned LastRenameReg = NVC.getVirtualVReg();
553 if (FirstCandidate)
554 NVC.incrementVirtualVReg(LastRenameReg % 10);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000555 FirstCandidate = false;
556 continue;
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000557 } else if (!Register::isVirtualRegister(vreg.getReg())) {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000558 unsigned LastRenameReg = NVC.incrementVirtualVReg();
559 (void)LastRenameReg;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000560 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000561 dbgs() << "Skipping rename for Phys Reg " << LastRenameReg << "\n";
562 });
563 continue;
564 }
565
566 auto Reg = vreg.getReg();
567 if (llvm::find(renamedInOtherBB, Reg) != renamedInOtherBB.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000568 LLVM_DEBUG(dbgs() << "Vreg " << Reg
569 << " already renamed in other BB.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000570 continue;
571 }
572
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000573 auto Rename = NVC.createVirtualRegister(Reg);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000574
575 if (VRegRenameMap.find(Reg) == VRegRenameMap.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000576 LLVM_DEBUG(dbgs() << "Mapping vreg ";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000577 if (MRI.reg_begin(Reg) != MRI.reg_end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000578 LLVM_DEBUG(auto foo = &*MRI.reg_begin(Reg); foo->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000579 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000580 LLVM_DEBUG(dbgs() << Reg;);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000581 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000582 LLVM_DEBUG(dbgs() << " to ";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000583 if (MRI.reg_begin(Rename) != MRI.reg_end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000584 LLVM_DEBUG(auto foo = &*MRI.reg_begin(Rename); foo->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000585 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000586 LLVM_DEBUG(dbgs() << Rename;);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000587 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000588 LLVM_DEBUG(dbgs() << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000589
590 VRegRenameMap.insert(std::pair<unsigned, unsigned>(Reg, Rename));
591 }
592 }
593
594 return VRegRenameMap;
595}
596
597static bool doVRegRenaming(std::vector<unsigned> &RenamedInOtherBB,
598 const std::map<unsigned, unsigned> &VRegRenameMap,
599 MachineRegisterInfo &MRI) {
600 bool Changed = false;
601 for (auto I = VRegRenameMap.begin(), E = VRegRenameMap.end(); I != E; ++I) {
602
603 auto VReg = I->first;
604 auto Rename = I->second;
605
606 RenamedInOtherBB.push_back(Rename);
607
608 std::vector<MachineOperand *> RenameMOs;
609 for (auto &MO : MRI.reg_operands(VReg)) {
610 RenameMOs.push_back(&MO);
611 }
612
613 for (auto *MO : RenameMOs) {
614 Changed = true;
615 MO->setReg(Rename);
616
617 if (!MO->isDef())
618 MO->setIsKill(false);
619 }
620 }
621
622 return Changed;
623}
624
625static bool doDefKillClear(MachineBasicBlock *MBB) {
626 bool Changed = false;
627
628 for (auto &MI : *MBB) {
629 for (auto &MO : MI.operands()) {
630 if (!MO.isReg())
631 continue;
632 if (!MO.isDef() && MO.isKill()) {
633 Changed = true;
634 MO.setIsKill(false);
635 }
636
637 if (MO.isDef() && MO.isDead()) {
638 Changed = true;
639 MO.setIsDead(false);
640 }
641 }
642 }
643
644 return Changed;
645}
646
647static bool runOnBasicBlock(MachineBasicBlock *MBB,
648 std::vector<StringRef> &bbNames,
649 std::vector<unsigned> &renamedInOtherBB,
Puyan Lotfid6f73132018-04-05 00:27:15 +0000650 unsigned &basicBlockNum, unsigned &VRegGapIndex,
651 NamedVRegCursor &NVC) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000652
653 if (CanonicalizeBasicBlockNumber != ~0U) {
654 if (CanonicalizeBasicBlockNumber != basicBlockNum++)
655 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000656 LLVM_DEBUG(dbgs() << "\n Canonicalizing BasicBlock " << MBB->getName()
657 << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000658 }
659
660 if (llvm::find(bbNames, MBB->getName()) != bbNames.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000661 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000662 dbgs() << "Found potentially duplicate BasicBlocks: " << MBB->getName()
663 << "\n";
664 });
665 return false;
666 }
667
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000668 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000669 dbgs() << "\n\n NEW BASIC BLOCK: " << MBB->getName() << " \n\n";
670 dbgs() << "\n\n================================================\n\n";
671 });
672
673 bool Changed = false;
674 MachineFunction &MF = *MBB->getParent();
675 MachineRegisterInfo &MRI = MF.getRegInfo();
676
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000677 bbNames.push_back(MBB->getName());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000678 LLVM_DEBUG(dbgs() << "\n\n NEW BASIC BLOCK: " << MBB->getName() << "\n\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000679
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000680 LLVM_DEBUG(dbgs() << "MBB Before Canonical Copy Propagation:\n";
681 MBB->dump(););
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000682 Changed |= propagateLocalCopies(MBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000683 LLVM_DEBUG(dbgs() << "MBB After Canonical Copy Propagation:\n"; MBB->dump(););
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000684
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000685 LLVM_DEBUG(dbgs() << "MBB Before Scheduling:\n"; MBB->dump(););
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000686 unsigned IdempotentInstCount = 0;
687 Changed |= rescheduleCanonically(IdempotentInstCount, MBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000688 LLVM_DEBUG(dbgs() << "MBB After Scheduling:\n"; MBB->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000689
690 std::vector<MachineInstr *> Candidates = populateCandidates(MBB);
691 std::vector<MachineInstr *> VisitedMIs;
Fangrui Song75709322018-11-17 01:44:25 +0000692 llvm::copy(Candidates, std::back_inserter(VisitedMIs));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000693
694 std::vector<TypedVReg> VRegs;
695 for (auto candidate : Candidates) {
696 VRegs.push_back(TypedVReg(RSE_NewCandidate));
697
698 std::queue<TypedVReg> RegQueue;
699
700 // Here we walk the vreg operands of a non-root node along our walk.
701 // The root nodes are the original candidates (stores normally).
702 // These are normally not the root nodes (except for the case of copies to
703 // physical registers).
704 for (unsigned i = 1; i < candidate->getNumOperands(); i++) {
705 if (candidate->mayStore() || candidate->isBranch())
706 break;
707
708 MachineOperand &MO = candidate->getOperand(i);
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000709 if (!(MO.isReg() && Register::isVirtualRegister(MO.getReg())))
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000710 continue;
711
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000712 LLVM_DEBUG(dbgs() << "Enqueue register"; MO.dump(); dbgs() << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000713 RegQueue.push(TypedVReg(MO.getReg()));
714 }
715
716 // Here we walk the root candidates. We start from the 0th operand because
717 // the root is normally a store to a vreg.
718 for (unsigned i = 0; i < candidate->getNumOperands(); i++) {
719
720 if (!candidate->mayStore() && !candidate->isBranch())
721 break;
722
723 MachineOperand &MO = candidate->getOperand(i);
724
725 // TODO: Do we want to only add vregs here?
726 if (!MO.isReg() && !MO.isFI())
727 continue;
728
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000729 LLVM_DEBUG(dbgs() << "Enqueue Reg/FI"; MO.dump(); dbgs() << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000730
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000731 RegQueue.push(MO.isReg() ? TypedVReg(MO.getReg())
732 : TypedVReg(RSE_FrameIndex));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000733 }
734
735 doCandidateWalk(VRegs, RegQueue, VisitedMIs, MBB);
736 }
737
738 // If we have populated no vregs to rename then bail.
739 // The rest of this function does the vreg remaping.
740 if (VRegs.size() == 0)
741 return Changed;
742
Puyan Lotfid6f73132018-04-05 00:27:15 +0000743 auto VRegRenameMap = GetVRegRenameMap(VRegs, renamedInOtherBB, MRI, NVC);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000744 Changed |= doVRegRenaming(renamedInOtherBB, VRegRenameMap, MRI);
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000745
746 // Here we renumber the def vregs for the idempotent instructions from the top
747 // of the MachineBasicBlock so that they are named in the order that we sorted
748 // them alphabetically. Eventually we wont need SkipVRegs because we will use
749 // named vregs instead.
Puyan Lotfi3ea6b242019-05-31 17:34:25 +0000750 if (IdempotentInstCount)
751 NVC.SkipVRegs();
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000752
753 auto MII = MBB->begin();
754 for (unsigned i = 0; i < IdempotentInstCount && MII != MBB->end(); ++i) {
755 MachineInstr &MI = *MII++;
756 Changed = true;
Daniel Sanders0c476112019-08-15 19:22:08 +0000757 Register vRegToRename = MI.getOperand(0).getReg();
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000758 auto Rename = NVC.createVirtualRegister(vRegToRename);
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000759
760 std::vector<MachineOperand *> RenameMOs;
761 for (auto &MO : MRI.reg_operands(vRegToRename)) {
762 RenameMOs.push_back(&MO);
763 }
764
765 for (auto *MO : RenameMOs) {
766 MO->setReg(Rename);
767 }
768 }
769
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000770 Changed |= doDefKillClear(MBB);
771
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000772 LLVM_DEBUG(dbgs() << "Updated MachineBasicBlock:\n"; MBB->dump();
773 dbgs() << "\n";);
774 LLVM_DEBUG(
775 dbgs() << "\n\n================================================\n\n");
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000776 return Changed;
777}
778
779bool MIRCanonicalizer::runOnMachineFunction(MachineFunction &MF) {
780
781 static unsigned functionNum = 0;
782 if (CanonicalizeFunctionNumber != ~0U) {
783 if (CanonicalizeFunctionNumber != functionNum++)
784 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000785 LLVM_DEBUG(dbgs() << "\n Canonicalizing Function " << MF.getName()
786 << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000787 }
788
789 // we need a valid vreg to create a vreg type for skipping all those
790 // stray vreg numbers so reach alignment/canonical vreg values.
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000791 std::vector<MachineBasicBlock *> RPOList = GetRPOList(MF);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000792
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000793 LLVM_DEBUG(
794 dbgs() << "\n\n NEW MACHINE FUNCTION: " << MF.getName() << " \n\n";
795 dbgs() << "\n\n================================================\n\n";
796 dbgs() << "Total Basic Blocks: " << RPOList.size() << "\n";
797 for (auto MBB
798 : RPOList) { dbgs() << MBB->getName() << "\n"; } dbgs()
799 << "\n\n================================================\n\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000800
801 std::vector<StringRef> BBNames;
802 std::vector<unsigned> RenamedInOtherBB;
803
804 unsigned GapIdx = 0;
805 unsigned BBNum = 0;
806
807 bool Changed = false;
808
Puyan Lotfid6f73132018-04-05 00:27:15 +0000809 MachineRegisterInfo &MRI = MF.getRegInfo();
810 NamedVRegCursor NVC(MRI);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000811 for (auto MBB : RPOList)
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000812 Changed |=
813 runOnBasicBlock(MBB, BBNames, RenamedInOtherBB, BBNum, GapIdx, NVC);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000814
815 return Changed;
816}