blob: a4097232d7d5921b0b59a0d7c6fb499926f3415d [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 Lotfi57c4f382018-03-31 05:48:51 +0000183 std::vector<MachineInstr *> PseudoIdempotentInstructions;
184 std::vector<unsigned> PhysRegDefs;
185 for (auto *II : Instructions) {
186 for (unsigned i = 1; i < II->getNumOperands(); i++) {
187 MachineOperand &MO = II->getOperand(i);
188 if (!MO.isReg())
189 continue;
190
191 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
192 continue;
193
194 if (!MO.isDef())
195 continue;
196
197 PhysRegDefs.push_back(MO.getReg());
198 }
199 }
200
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000201 for (auto *II : Instructions) {
202 if (II->getNumOperands() == 0)
203 continue;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000204 if (II->mayLoadOrStore())
205 continue;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000206
207 MachineOperand &MO = II->getOperand(0);
208 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
209 continue;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000210 if (!MO.isDef())
211 continue;
212
213 bool IsPseudoIdempotent = true;
214 for (unsigned i = 1; i < II->getNumOperands(); i++) {
215
216 if (II->getOperand(i).isImm()) {
217 continue;
218 }
219
220 if (II->getOperand(i).isReg()) {
221 if (!TargetRegisterInfo::isVirtualRegister(II->getOperand(i).getReg()))
222 if (llvm::find(PhysRegDefs, II->getOperand(i).getReg()) ==
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000223 PhysRegDefs.end()) {
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000224 continue;
225 }
226 }
227
228 IsPseudoIdempotent = false;
229 break;
230 }
231
232 if (IsPseudoIdempotent) {
233 PseudoIdempotentInstructions.push_back(II);
234 continue;
235 }
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000236
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000237 LLVM_DEBUG(dbgs() << "Operand " << 0 << " of "; II->dump(); MO.dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000238
239 MachineInstr *Def = II;
240 unsigned Distance = ~0U;
241 MachineInstr *UseToBringDefCloserTo = nullptr;
242 MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
243 for (auto &UO : MRI->use_nodbg_operands(MO.getReg())) {
244 MachineInstr *UseInst = UO.getParent();
245
246 const unsigned DefLoc = getInstrIdx(*Def);
247 const unsigned UseLoc = getInstrIdx(*UseInst);
248 const unsigned Delta = (UseLoc - DefLoc);
249
250 if (UseInst->getParent() != Def->getParent())
251 continue;
252 if (DefLoc >= UseLoc)
253 continue;
254
255 if (Delta < Distance) {
256 Distance = Delta;
257 UseToBringDefCloserTo = UseInst;
258 }
259 }
260
261 const auto BBE = MBB->instr_end();
262 MachineBasicBlock::iterator DefI = BBE;
263 MachineBasicBlock::iterator UseI = BBE;
264
265 for (auto BBI = MBB->instr_begin(); BBI != BBE; ++BBI) {
266
267 if (DefI != BBE && UseI != BBE)
268 break;
269
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000270 if (&*BBI == Def) {
271 DefI = BBI;
272 continue;
273 }
274
275 if (&*BBI == UseToBringDefCloserTo) {
276 UseI = BBI;
277 continue;
278 }
279 }
280
281 if (DefI == BBE || UseI == BBE)
282 continue;
283
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000284 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000285 dbgs() << "Splicing ";
286 DefI->dump();
287 dbgs() << " right before: ";
288 UseI->dump();
289 });
290
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000291 MultiUsers[UseToBringDefCloserTo].push_back(Def);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000292 Changed = true;
293 MBB->splice(UseI, MBB, DefI);
294 }
295
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000296 // Sort the defs for users of multiple defs lexographically.
297 for (const auto &E : MultiUsers) {
298
299 auto UseI =
300 std::find_if(MBB->instr_begin(), MBB->instr_end(),
301 [&](MachineInstr &MI) -> bool { return &MI == E.first; });
302
303 if (UseI == MBB->instr_end())
304 continue;
305
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000306 LLVM_DEBUG(
307 dbgs() << "Rescheduling Multi-Use Instructions Lexographically.";);
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000308 Changed |= rescheduleLexographically(
309 E.second, MBB, [&]() -> MachineBasicBlock::iterator { return UseI; });
310 }
311
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000312 PseudoIdempotentInstCount = PseudoIdempotentInstructions.size();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000313 LLVM_DEBUG(
314 dbgs() << "Rescheduling Idempotent Instructions Lexographically.";);
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000315 Changed |= rescheduleLexographically(
316 PseudoIdempotentInstructions, MBB,
317 [&]() -> MachineBasicBlock::iterator { return MBB->begin(); });
318
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000319 return Changed;
320}
321
Benjamin Kramer651d0bf2018-05-15 21:26:47 +0000322static bool propagateLocalCopies(MachineBasicBlock *MBB) {
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000323 bool Changed = false;
324 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
325
326 std::vector<MachineInstr *> Copies;
327 for (MachineInstr &MI : MBB->instrs()) {
328 if (MI.isCopy())
329 Copies.push_back(&MI);
330 }
331
332 for (MachineInstr *MI : Copies) {
333
334 if (!MI->getOperand(0).isReg())
335 continue;
336 if (!MI->getOperand(1).isReg())
337 continue;
338
339 const unsigned Dst = MI->getOperand(0).getReg();
340 const unsigned Src = MI->getOperand(1).getReg();
341
342 if (!TargetRegisterInfo::isVirtualRegister(Dst))
343 continue;
344 if (!TargetRegisterInfo::isVirtualRegister(Src))
345 continue;
Puyan Lotfi2a901402019-05-31 04:49:58 +0000346 // Not folding COPY instructions if regbankselect has not set the RCs.
347 // Why are we only considering Register Classes? Because the verifier
348 // sometimes gets upset if the register classes don't match even if the
349 // types do. A future patch might add COPY folding for matching types in
350 // pre-registerbankselect code.
351 if (!MRI.getRegClassOrNull(Dst))
352 continue;
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000353 if (MRI.getRegClass(Dst) != MRI.getRegClass(Src))
354 continue;
355
Puyan Lotfi2a901402019-05-31 04:49:58 +0000356 std::vector<MachineOperand *> Uses;
357 for (auto UI = MRI.use_begin(Dst); UI != MRI.use_end(); ++UI)
358 Uses.push_back(&*UI);
359 for (auto *MO : Uses)
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000360 MO->setReg(Src);
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000361
Puyan Lotfi2a901402019-05-31 04:49:58 +0000362 Changed = true;
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000363 MI->eraseFromParent();
364 }
365
366 return Changed;
367}
368
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000369/// Here we find our candidates. What makes an interesting candidate?
370/// An candidate for a canonicalization tree root is normally any kind of
371/// instruction that causes side effects such as a store to memory or a copy to
372/// a physical register or a return instruction. We use these as an expression
373/// tree root that we walk inorder to build a canonical walk which should result
374/// in canoncal vreg renaming.
375static std::vector<MachineInstr *> populateCandidates(MachineBasicBlock *MBB) {
376 std::vector<MachineInstr *> Candidates;
377 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
378
379 for (auto II = MBB->begin(), IE = MBB->end(); II != IE; ++II) {
380 MachineInstr *MI = &*II;
381
382 bool DoesMISideEffect = false;
383
384 if (MI->getNumOperands() > 0 && MI->getOperand(0).isReg()) {
385 const unsigned Dst = MI->getOperand(0).getReg();
386 DoesMISideEffect |= !TargetRegisterInfo::isVirtualRegister(Dst);
387
388 for (auto UI = MRI.use_begin(Dst); UI != MRI.use_end(); ++UI) {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000389 if (DoesMISideEffect)
390 break;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000391 DoesMISideEffect |= (UI->getParent()->getParent() != MI->getParent());
392 }
393 }
394
395 if (!MI->mayStore() && !MI->isBranch() && !DoesMISideEffect)
396 continue;
397
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000398 LLVM_DEBUG(dbgs() << "Found Candidate: "; MI->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000399 Candidates.push_back(MI);
400 }
401
402 return Candidates;
403}
404
Benjamin Kramer51ebcaa2017-11-24 14:55:41 +0000405static void doCandidateWalk(std::vector<TypedVReg> &VRegs,
406 std::queue<TypedVReg> &RegQueue,
407 std::vector<MachineInstr *> &VisitedMIs,
408 const MachineBasicBlock *MBB) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000409
410 const MachineFunction &MF = *MBB->getParent();
411 const MachineRegisterInfo &MRI = MF.getRegInfo();
412
413 while (!RegQueue.empty()) {
414
415 auto TReg = RegQueue.front();
416 RegQueue.pop();
417
418 if (TReg.isFrameIndex()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000419 LLVM_DEBUG(dbgs() << "Popping frame index.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000420 VRegs.push_back(TypedVReg(RSE_FrameIndex));
421 continue;
422 }
423
424 assert(TReg.isReg() && "Expected vreg or physreg.");
425 unsigned Reg = TReg.getReg();
426
427 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000428 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000429 dbgs() << "Popping vreg ";
430 MRI.def_begin(Reg)->dump();
431 dbgs() << "\n";
432 });
433
434 if (!llvm::any_of(VRegs, [&](const TypedVReg &TR) {
435 return TR.isReg() && TR.getReg() == Reg;
436 })) {
437 VRegs.push_back(TypedVReg(Reg));
438 }
439 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000440 LLVM_DEBUG(dbgs() << "Popping physreg.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000441 VRegs.push_back(TypedVReg(Reg));
442 continue;
443 }
444
445 for (auto RI = MRI.def_begin(Reg), RE = MRI.def_end(); RI != RE; ++RI) {
446 MachineInstr *Def = RI->getParent();
447
448 if (Def->getParent() != MBB)
449 continue;
450
451 if (llvm::any_of(VisitedMIs,
452 [&](const MachineInstr *VMI) { return Def == VMI; })) {
453 break;
454 }
455
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000456 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000457 dbgs() << "\n========================\n";
458 dbgs() << "Visited MI: ";
459 Def->dump();
460 dbgs() << "BB Name: " << Def->getParent()->getName() << "\n";
461 dbgs() << "\n========================\n";
462 });
463 VisitedMIs.push_back(Def);
464 for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
465
466 MachineOperand &MO = Def->getOperand(I);
467 if (MO.isFI()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000468 LLVM_DEBUG(dbgs() << "Pushing frame index.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000469 RegQueue.push(TypedVReg(RSE_FrameIndex));
470 }
471
472 if (!MO.isReg())
473 continue;
474 RegQueue.push(TypedVReg(MO.getReg()));
475 }
476 }
477 }
478}
479
Benjamin Kramer651d0bf2018-05-15 21:26:47 +0000480namespace {
Puyan Lotfid6f73132018-04-05 00:27:15 +0000481class NamedVRegCursor {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000482 MachineRegisterInfo &MRI;
483 unsigned virtualVRegNumber;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000484
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000485public:
Puyan Lotfi0d63cef2019-05-31 06:02:38 +0000486 NamedVRegCursor(MachineRegisterInfo &MRI) : MRI(MRI), virtualVRegNumber(0) {}
Puyan Lotfid6f73132018-04-05 00:27:15 +0000487
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000488 void SkipVRegs() {
489 unsigned VRegGapIndex = 1;
Puyan Lotfi0d63cef2019-05-31 06:02:38 +0000490 if (!virtualVRegNumber) {
491 VRegGapIndex = 0;
492 virtualVRegNumber = MRI.createIncompleteVirtualRegister();
493 }
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000494 const unsigned VR_GAP = (++VRegGapIndex * 1000);
Puyan Lotfid6f73132018-04-05 00:27:15 +0000495
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000496 unsigned I = virtualVRegNumber;
497 const unsigned E = (((I + VR_GAP) / VR_GAP) + 1) * VR_GAP;
Puyan Lotfid6f73132018-04-05 00:27:15 +0000498
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000499 virtualVRegNumber = E;
500 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000501
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000502 unsigned getVirtualVReg() const { return virtualVRegNumber; }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000503
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000504 unsigned incrementVirtualVReg(unsigned incr = 1) {
505 virtualVRegNumber += incr;
506 return virtualVRegNumber;
507 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000508
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000509 unsigned createVirtualRegister(unsigned VReg) {
Puyan Lotfi0d63cef2019-05-31 06:02:38 +0000510 if (!virtualVRegNumber)
511 SkipVRegs();
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000512 std::string S;
513 raw_string_ostream OS(S);
514 OS << "namedVReg" << (virtualVRegNumber & ~0x80000000);
515 OS.flush();
516 virtualVRegNumber++;
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000517 if (auto RC = MRI.getRegClassOrNull(VReg))
518 return MRI.createVirtualRegister(RC, OS.str());
519 return MRI.createGenericVirtualRegister(MRI.getType(VReg), OS.str());
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000520 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000521};
Benjamin Kramer651d0bf2018-05-15 21:26:47 +0000522} // namespace
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000523
524static std::map<unsigned, unsigned>
525GetVRegRenameMap(const std::vector<TypedVReg> &VRegs,
526 const std::vector<unsigned> &renamedInOtherBB,
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000527 MachineRegisterInfo &MRI, NamedVRegCursor &NVC) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000528 std::map<unsigned, unsigned> VRegRenameMap;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000529 bool FirstCandidate = true;
530
531 for (auto &vreg : VRegs) {
532 if (vreg.isFrameIndex()) {
533 // We skip one vreg for any frame index because there is a good chance
534 // (especially when comparing SelectionDAG to GlobalISel generated MIR)
535 // that in the other file we are just getting an incoming vreg that comes
536 // from a copy from a frame index. So it's safe to skip by one.
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000537 unsigned LastRenameReg = NVC.incrementVirtualVReg();
538 (void)LastRenameReg;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000539 LLVM_DEBUG(dbgs() << "Skipping rename for FI " << LastRenameReg << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000540 continue;
541 } else if (vreg.isCandidate()) {
542
543 // After the first candidate, for every subsequent candidate, we skip mod
544 // 10 registers so that the candidates are more likely to start at the
545 // same vreg number making it more likely that the canonical walk from the
546 // candidate insruction. We don't need to skip from the first candidate of
547 // the BasicBlock because we already skip ahead several vregs for each BB.
Puyan Lotfid6f73132018-04-05 00:27:15 +0000548 unsigned LastRenameReg = NVC.getVirtualVReg();
549 if (FirstCandidate)
550 NVC.incrementVirtualVReg(LastRenameReg % 10);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000551 FirstCandidate = false;
552 continue;
553 } else if (!TargetRegisterInfo::isVirtualRegister(vreg.getReg())) {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000554 unsigned LastRenameReg = NVC.incrementVirtualVReg();
555 (void)LastRenameReg;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000556 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000557 dbgs() << "Skipping rename for Phys Reg " << LastRenameReg << "\n";
558 });
559 continue;
560 }
561
562 auto Reg = vreg.getReg();
563 if (llvm::find(renamedInOtherBB, Reg) != renamedInOtherBB.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000564 LLVM_DEBUG(dbgs() << "Vreg " << Reg
565 << " already renamed in other BB.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000566 continue;
567 }
568
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000569 auto Rename = NVC.createVirtualRegister(Reg);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000570
571 if (VRegRenameMap.find(Reg) == VRegRenameMap.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000572 LLVM_DEBUG(dbgs() << "Mapping vreg ";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000573 if (MRI.reg_begin(Reg) != MRI.reg_end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000574 LLVM_DEBUG(auto foo = &*MRI.reg_begin(Reg); foo->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000575 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000576 LLVM_DEBUG(dbgs() << Reg;);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000577 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000578 LLVM_DEBUG(dbgs() << " to ";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000579 if (MRI.reg_begin(Rename) != MRI.reg_end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000580 LLVM_DEBUG(auto foo = &*MRI.reg_begin(Rename); foo->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000581 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000582 LLVM_DEBUG(dbgs() << Rename;);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000583 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000584 LLVM_DEBUG(dbgs() << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000585
586 VRegRenameMap.insert(std::pair<unsigned, unsigned>(Reg, Rename));
587 }
588 }
589
590 return VRegRenameMap;
591}
592
593static bool doVRegRenaming(std::vector<unsigned> &RenamedInOtherBB,
594 const std::map<unsigned, unsigned> &VRegRenameMap,
595 MachineRegisterInfo &MRI) {
596 bool Changed = false;
597 for (auto I = VRegRenameMap.begin(), E = VRegRenameMap.end(); I != E; ++I) {
598
599 auto VReg = I->first;
600 auto Rename = I->second;
601
602 RenamedInOtherBB.push_back(Rename);
603
604 std::vector<MachineOperand *> RenameMOs;
605 for (auto &MO : MRI.reg_operands(VReg)) {
606 RenameMOs.push_back(&MO);
607 }
608
609 for (auto *MO : RenameMOs) {
610 Changed = true;
611 MO->setReg(Rename);
612
613 if (!MO->isDef())
614 MO->setIsKill(false);
615 }
616 }
617
618 return Changed;
619}
620
621static bool doDefKillClear(MachineBasicBlock *MBB) {
622 bool Changed = false;
623
624 for (auto &MI : *MBB) {
625 for (auto &MO : MI.operands()) {
626 if (!MO.isReg())
627 continue;
628 if (!MO.isDef() && MO.isKill()) {
629 Changed = true;
630 MO.setIsKill(false);
631 }
632
633 if (MO.isDef() && MO.isDead()) {
634 Changed = true;
635 MO.setIsDead(false);
636 }
637 }
638 }
639
640 return Changed;
641}
642
643static bool runOnBasicBlock(MachineBasicBlock *MBB,
644 std::vector<StringRef> &bbNames,
645 std::vector<unsigned> &renamedInOtherBB,
Puyan Lotfid6f73132018-04-05 00:27:15 +0000646 unsigned &basicBlockNum, unsigned &VRegGapIndex,
647 NamedVRegCursor &NVC) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000648
649 if (CanonicalizeBasicBlockNumber != ~0U) {
650 if (CanonicalizeBasicBlockNumber != basicBlockNum++)
651 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000652 LLVM_DEBUG(dbgs() << "\n Canonicalizing BasicBlock " << MBB->getName()
653 << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000654 }
655
656 if (llvm::find(bbNames, MBB->getName()) != bbNames.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000657 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000658 dbgs() << "Found potentially duplicate BasicBlocks: " << MBB->getName()
659 << "\n";
660 });
661 return false;
662 }
663
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000664 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000665 dbgs() << "\n\n NEW BASIC BLOCK: " << MBB->getName() << " \n\n";
666 dbgs() << "\n\n================================================\n\n";
667 });
668
669 bool Changed = false;
670 MachineFunction &MF = *MBB->getParent();
671 MachineRegisterInfo &MRI = MF.getRegInfo();
672
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000673 bbNames.push_back(MBB->getName());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000674 LLVM_DEBUG(dbgs() << "\n\n NEW BASIC BLOCK: " << MBB->getName() << "\n\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000675
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000676 LLVM_DEBUG(dbgs() << "MBB Before Canonical Copy Propagation:\n";
677 MBB->dump(););
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000678 Changed |= propagateLocalCopies(MBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000679 LLVM_DEBUG(dbgs() << "MBB After Canonical Copy Propagation:\n"; MBB->dump(););
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000680
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000681 LLVM_DEBUG(dbgs() << "MBB Before Scheduling:\n"; MBB->dump(););
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000682 unsigned IdempotentInstCount = 0;
683 Changed |= rescheduleCanonically(IdempotentInstCount, MBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000684 LLVM_DEBUG(dbgs() << "MBB After Scheduling:\n"; MBB->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000685
686 std::vector<MachineInstr *> Candidates = populateCandidates(MBB);
687 std::vector<MachineInstr *> VisitedMIs;
Fangrui Song75709322018-11-17 01:44:25 +0000688 llvm::copy(Candidates, std::back_inserter(VisitedMIs));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000689
690 std::vector<TypedVReg> VRegs;
691 for (auto candidate : Candidates) {
692 VRegs.push_back(TypedVReg(RSE_NewCandidate));
693
694 std::queue<TypedVReg> RegQueue;
695
696 // Here we walk the vreg operands of a non-root node along our walk.
697 // The root nodes are the original candidates (stores normally).
698 // These are normally not the root nodes (except for the case of copies to
699 // physical registers).
700 for (unsigned i = 1; i < candidate->getNumOperands(); i++) {
701 if (candidate->mayStore() || candidate->isBranch())
702 break;
703
704 MachineOperand &MO = candidate->getOperand(i);
705 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
706 continue;
707
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000708 LLVM_DEBUG(dbgs() << "Enqueue register"; MO.dump(); dbgs() << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000709 RegQueue.push(TypedVReg(MO.getReg()));
710 }
711
712 // Here we walk the root candidates. We start from the 0th operand because
713 // the root is normally a store to a vreg.
714 for (unsigned i = 0; i < candidate->getNumOperands(); i++) {
715
716 if (!candidate->mayStore() && !candidate->isBranch())
717 break;
718
719 MachineOperand &MO = candidate->getOperand(i);
720
721 // TODO: Do we want to only add vregs here?
722 if (!MO.isReg() && !MO.isFI())
723 continue;
724
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000725 LLVM_DEBUG(dbgs() << "Enqueue Reg/FI"; MO.dump(); dbgs() << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000726
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000727 RegQueue.push(MO.isReg() ? TypedVReg(MO.getReg())
728 : TypedVReg(RSE_FrameIndex));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000729 }
730
731 doCandidateWalk(VRegs, RegQueue, VisitedMIs, MBB);
732 }
733
734 // If we have populated no vregs to rename then bail.
735 // The rest of this function does the vreg remaping.
736 if (VRegs.size() == 0)
737 return Changed;
738
Puyan Lotfid6f73132018-04-05 00:27:15 +0000739 auto VRegRenameMap = GetVRegRenameMap(VRegs, renamedInOtherBB, MRI, NVC);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000740 Changed |= doVRegRenaming(renamedInOtherBB, VRegRenameMap, MRI);
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000741
742 // Here we renumber the def vregs for the idempotent instructions from the top
743 // of the MachineBasicBlock so that they are named in the order that we sorted
744 // them alphabetically. Eventually we wont need SkipVRegs because we will use
745 // named vregs instead.
Puyan Lotfid6f73132018-04-05 00:27:15 +0000746 NVC.SkipVRegs();
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000747
748 auto MII = MBB->begin();
749 for (unsigned i = 0; i < IdempotentInstCount && MII != MBB->end(); ++i) {
750 MachineInstr &MI = *MII++;
751 Changed = true;
752 unsigned vRegToRename = MI.getOperand(0).getReg();
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000753 auto Rename = NVC.createVirtualRegister(vRegToRename);
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000754
755 std::vector<MachineOperand *> RenameMOs;
756 for (auto &MO : MRI.reg_operands(vRegToRename)) {
757 RenameMOs.push_back(&MO);
758 }
759
760 for (auto *MO : RenameMOs) {
761 MO->setReg(Rename);
762 }
763 }
764
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000765 Changed |= doDefKillClear(MBB);
766
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000767 LLVM_DEBUG(dbgs() << "Updated MachineBasicBlock:\n"; MBB->dump();
768 dbgs() << "\n";);
769 LLVM_DEBUG(
770 dbgs() << "\n\n================================================\n\n");
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000771 return Changed;
772}
773
774bool MIRCanonicalizer::runOnMachineFunction(MachineFunction &MF) {
775
776 static unsigned functionNum = 0;
777 if (CanonicalizeFunctionNumber != ~0U) {
778 if (CanonicalizeFunctionNumber != functionNum++)
779 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000780 LLVM_DEBUG(dbgs() << "\n Canonicalizing Function " << MF.getName()
781 << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000782 }
783
784 // we need a valid vreg to create a vreg type for skipping all those
785 // stray vreg numbers so reach alignment/canonical vreg values.
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000786 std::vector<MachineBasicBlock *> RPOList = GetRPOList(MF);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000787
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000788 LLVM_DEBUG(
789 dbgs() << "\n\n NEW MACHINE FUNCTION: " << MF.getName() << " \n\n";
790 dbgs() << "\n\n================================================\n\n";
791 dbgs() << "Total Basic Blocks: " << RPOList.size() << "\n";
792 for (auto MBB
793 : RPOList) { dbgs() << MBB->getName() << "\n"; } dbgs()
794 << "\n\n================================================\n\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000795
796 std::vector<StringRef> BBNames;
797 std::vector<unsigned> RenamedInOtherBB;
798
799 unsigned GapIdx = 0;
800 unsigned BBNum = 0;
801
802 bool Changed = false;
803
Puyan Lotfid6f73132018-04-05 00:27:15 +0000804 MachineRegisterInfo &MRI = MF.getRegInfo();
805 NamedVRegCursor NVC(MRI);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000806 for (auto MBB : RPOList)
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000807 Changed |=
808 runOnBasicBlock(MBB, BBNames, RenamedInOtherBB, BBNum, GapIdx, NVC);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000809
810 return Changed;
811}