blob: d36c0c89ba0b13169f945c353c36e9ab6fb014fa [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:
486 NamedVRegCursor(MachineRegisterInfo &MRI) : MRI(MRI) {
487 unsigned VRegGapIndex = 0;
488 const unsigned VR_GAP = (++VRegGapIndex * 1000);
Puyan Lotfid6f73132018-04-05 00:27:15 +0000489
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000490 unsigned I = MRI.createIncompleteVirtualRegister();
491 const unsigned E = (((I + VR_GAP) / VR_GAP) + 1) * VR_GAP;
Puyan Lotfid6f73132018-04-05 00:27:15 +0000492
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000493 virtualVRegNumber = E;
494 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000495
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000496 void SkipVRegs() {
497 unsigned VRegGapIndex = 1;
498 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 Lotfi6ea89b42018-04-16 08:12:15 +0000514 std::string S;
515 raw_string_ostream OS(S);
516 OS << "namedVReg" << (virtualVRegNumber & ~0x80000000);
517 OS.flush();
518 virtualVRegNumber++;
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000519 if (auto RC = MRI.getRegClassOrNull(VReg))
520 return MRI.createVirtualRegister(RC, OS.str());
521 return MRI.createGenericVirtualRegister(MRI.getType(VReg), OS.str());
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000522 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000523};
Benjamin Kramer651d0bf2018-05-15 21:26:47 +0000524} // namespace
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000525
526static std::map<unsigned, unsigned>
527GetVRegRenameMap(const std::vector<TypedVReg> &VRegs,
528 const std::vector<unsigned> &renamedInOtherBB,
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000529 MachineRegisterInfo &MRI, NamedVRegCursor &NVC) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000530 std::map<unsigned, unsigned> VRegRenameMap;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000531 bool FirstCandidate = true;
532
533 for (auto &vreg : VRegs) {
534 if (vreg.isFrameIndex()) {
535 // We skip one vreg for any frame index because there is a good chance
536 // (especially when comparing SelectionDAG to GlobalISel generated MIR)
537 // that in the other file we are just getting an incoming vreg that comes
538 // from a copy from a frame index. So it's safe to skip by one.
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000539 unsigned LastRenameReg = NVC.incrementVirtualVReg();
540 (void)LastRenameReg;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000541 LLVM_DEBUG(dbgs() << "Skipping rename for FI " << LastRenameReg << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000542 continue;
543 } else if (vreg.isCandidate()) {
544
545 // After the first candidate, for every subsequent candidate, we skip mod
546 // 10 registers so that the candidates are more likely to start at the
547 // same vreg number making it more likely that the canonical walk from the
548 // candidate insruction. We don't need to skip from the first candidate of
549 // the BasicBlock because we already skip ahead several vregs for each BB.
Puyan Lotfid6f73132018-04-05 00:27:15 +0000550 unsigned LastRenameReg = NVC.getVirtualVReg();
551 if (FirstCandidate)
552 NVC.incrementVirtualVReg(LastRenameReg % 10);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000553 FirstCandidate = false;
554 continue;
555 } else if (!TargetRegisterInfo::isVirtualRegister(vreg.getReg())) {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000556 unsigned LastRenameReg = NVC.incrementVirtualVReg();
557 (void)LastRenameReg;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000558 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000559 dbgs() << "Skipping rename for Phys Reg " << LastRenameReg << "\n";
560 });
561 continue;
562 }
563
564 auto Reg = vreg.getReg();
565 if (llvm::find(renamedInOtherBB, Reg) != renamedInOtherBB.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000566 LLVM_DEBUG(dbgs() << "Vreg " << Reg
567 << " already renamed in other BB.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000568 continue;
569 }
570
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000571 auto Rename = NVC.createVirtualRegister(Reg);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000572
573 if (VRegRenameMap.find(Reg) == VRegRenameMap.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000574 LLVM_DEBUG(dbgs() << "Mapping vreg ";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000575 if (MRI.reg_begin(Reg) != MRI.reg_end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000576 LLVM_DEBUG(auto foo = &*MRI.reg_begin(Reg); foo->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000577 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000578 LLVM_DEBUG(dbgs() << Reg;);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000579 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000580 LLVM_DEBUG(dbgs() << " to ";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000581 if (MRI.reg_begin(Rename) != MRI.reg_end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000582 LLVM_DEBUG(auto foo = &*MRI.reg_begin(Rename); foo->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000583 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000584 LLVM_DEBUG(dbgs() << Rename;);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000585 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000586 LLVM_DEBUG(dbgs() << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000587
588 VRegRenameMap.insert(std::pair<unsigned, unsigned>(Reg, Rename));
589 }
590 }
591
592 return VRegRenameMap;
593}
594
595static bool doVRegRenaming(std::vector<unsigned> &RenamedInOtherBB,
596 const std::map<unsigned, unsigned> &VRegRenameMap,
597 MachineRegisterInfo &MRI) {
598 bool Changed = false;
599 for (auto I = VRegRenameMap.begin(), E = VRegRenameMap.end(); I != E; ++I) {
600
601 auto VReg = I->first;
602 auto Rename = I->second;
603
604 RenamedInOtherBB.push_back(Rename);
605
606 std::vector<MachineOperand *> RenameMOs;
607 for (auto &MO : MRI.reg_operands(VReg)) {
608 RenameMOs.push_back(&MO);
609 }
610
611 for (auto *MO : RenameMOs) {
612 Changed = true;
613 MO->setReg(Rename);
614
615 if (!MO->isDef())
616 MO->setIsKill(false);
617 }
618 }
619
620 return Changed;
621}
622
623static bool doDefKillClear(MachineBasicBlock *MBB) {
624 bool Changed = false;
625
626 for (auto &MI : *MBB) {
627 for (auto &MO : MI.operands()) {
628 if (!MO.isReg())
629 continue;
630 if (!MO.isDef() && MO.isKill()) {
631 Changed = true;
632 MO.setIsKill(false);
633 }
634
635 if (MO.isDef() && MO.isDead()) {
636 Changed = true;
637 MO.setIsDead(false);
638 }
639 }
640 }
641
642 return Changed;
643}
644
645static bool runOnBasicBlock(MachineBasicBlock *MBB,
646 std::vector<StringRef> &bbNames,
647 std::vector<unsigned> &renamedInOtherBB,
Puyan Lotfid6f73132018-04-05 00:27:15 +0000648 unsigned &basicBlockNum, unsigned &VRegGapIndex,
649 NamedVRegCursor &NVC) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000650
651 if (CanonicalizeBasicBlockNumber != ~0U) {
652 if (CanonicalizeBasicBlockNumber != basicBlockNum++)
653 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000654 LLVM_DEBUG(dbgs() << "\n Canonicalizing BasicBlock " << MBB->getName()
655 << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000656 }
657
658 if (llvm::find(bbNames, MBB->getName()) != bbNames.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000659 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000660 dbgs() << "Found potentially duplicate BasicBlocks: " << MBB->getName()
661 << "\n";
662 });
663 return false;
664 }
665
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000666 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000667 dbgs() << "\n\n NEW BASIC BLOCK: " << MBB->getName() << " \n\n";
668 dbgs() << "\n\n================================================\n\n";
669 });
670
671 bool Changed = false;
672 MachineFunction &MF = *MBB->getParent();
673 MachineRegisterInfo &MRI = MF.getRegInfo();
674
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000675 bbNames.push_back(MBB->getName());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000676 LLVM_DEBUG(dbgs() << "\n\n NEW BASIC BLOCK: " << MBB->getName() << "\n\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000677
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000678 LLVM_DEBUG(dbgs() << "MBB Before Canonical Copy Propagation:\n";
679 MBB->dump(););
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000680 Changed |= propagateLocalCopies(MBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000681 LLVM_DEBUG(dbgs() << "MBB After Canonical Copy Propagation:\n"; MBB->dump(););
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000682
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000683 LLVM_DEBUG(dbgs() << "MBB Before Scheduling:\n"; MBB->dump(););
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000684 unsigned IdempotentInstCount = 0;
685 Changed |= rescheduleCanonically(IdempotentInstCount, MBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000686 LLVM_DEBUG(dbgs() << "MBB After Scheduling:\n"; MBB->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000687
688 std::vector<MachineInstr *> Candidates = populateCandidates(MBB);
689 std::vector<MachineInstr *> VisitedMIs;
Fangrui Song75709322018-11-17 01:44:25 +0000690 llvm::copy(Candidates, std::back_inserter(VisitedMIs));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000691
692 std::vector<TypedVReg> VRegs;
693 for (auto candidate : Candidates) {
694 VRegs.push_back(TypedVReg(RSE_NewCandidate));
695
696 std::queue<TypedVReg> RegQueue;
697
698 // Here we walk the vreg operands of a non-root node along our walk.
699 // The root nodes are the original candidates (stores normally).
700 // These are normally not the root nodes (except for the case of copies to
701 // physical registers).
702 for (unsigned i = 1; i < candidate->getNumOperands(); i++) {
703 if (candidate->mayStore() || candidate->isBranch())
704 break;
705
706 MachineOperand &MO = candidate->getOperand(i);
707 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
708 continue;
709
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000710 LLVM_DEBUG(dbgs() << "Enqueue register"; MO.dump(); dbgs() << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000711 RegQueue.push(TypedVReg(MO.getReg()));
712 }
713
714 // Here we walk the root candidates. We start from the 0th operand because
715 // the root is normally a store to a vreg.
716 for (unsigned i = 0; i < candidate->getNumOperands(); i++) {
717
718 if (!candidate->mayStore() && !candidate->isBranch())
719 break;
720
721 MachineOperand &MO = candidate->getOperand(i);
722
723 // TODO: Do we want to only add vregs here?
724 if (!MO.isReg() && !MO.isFI())
725 continue;
726
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000727 LLVM_DEBUG(dbgs() << "Enqueue Reg/FI"; MO.dump(); dbgs() << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000728
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000729 RegQueue.push(MO.isReg() ? TypedVReg(MO.getReg())
730 : TypedVReg(RSE_FrameIndex));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000731 }
732
733 doCandidateWalk(VRegs, RegQueue, VisitedMIs, MBB);
734 }
735
736 // If we have populated no vregs to rename then bail.
737 // The rest of this function does the vreg remaping.
738 if (VRegs.size() == 0)
739 return Changed;
740
Puyan Lotfid6f73132018-04-05 00:27:15 +0000741 auto VRegRenameMap = GetVRegRenameMap(VRegs, renamedInOtherBB, MRI, NVC);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000742 Changed |= doVRegRenaming(renamedInOtherBB, VRegRenameMap, MRI);
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000743
744 // Here we renumber the def vregs for the idempotent instructions from the top
745 // of the MachineBasicBlock so that they are named in the order that we sorted
746 // them alphabetically. Eventually we wont need SkipVRegs because we will use
747 // named vregs instead.
Puyan Lotfid6f73132018-04-05 00:27:15 +0000748 NVC.SkipVRegs();
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000749
750 auto MII = MBB->begin();
751 for (unsigned i = 0; i < IdempotentInstCount && MII != MBB->end(); ++i) {
752 MachineInstr &MI = *MII++;
753 Changed = true;
754 unsigned vRegToRename = MI.getOperand(0).getReg();
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000755 auto Rename = NVC.createVirtualRegister(vRegToRename);
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000756
757 std::vector<MachineOperand *> RenameMOs;
758 for (auto &MO : MRI.reg_operands(vRegToRename)) {
759 RenameMOs.push_back(&MO);
760 }
761
762 for (auto *MO : RenameMOs) {
763 MO->setReg(Rename);
764 }
765 }
766
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000767 Changed |= doDefKillClear(MBB);
768
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000769 LLVM_DEBUG(dbgs() << "Updated MachineBasicBlock:\n"; MBB->dump();
770 dbgs() << "\n";);
771 LLVM_DEBUG(
772 dbgs() << "\n\n================================================\n\n");
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000773 return Changed;
774}
775
776bool MIRCanonicalizer::runOnMachineFunction(MachineFunction &MF) {
777
778 static unsigned functionNum = 0;
779 if (CanonicalizeFunctionNumber != ~0U) {
780 if (CanonicalizeFunctionNumber != functionNum++)
781 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000782 LLVM_DEBUG(dbgs() << "\n Canonicalizing Function " << MF.getName()
783 << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000784 }
785
786 // we need a valid vreg to create a vreg type for skipping all those
787 // stray vreg numbers so reach alignment/canonical vreg values.
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000788 std::vector<MachineBasicBlock *> RPOList = GetRPOList(MF);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000789
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000790 LLVM_DEBUG(
791 dbgs() << "\n\n NEW MACHINE FUNCTION: " << MF.getName() << " \n\n";
792 dbgs() << "\n\n================================================\n\n";
793 dbgs() << "Total Basic Blocks: " << RPOList.size() << "\n";
794 for (auto MBB
795 : RPOList) { dbgs() << MBB->getName() << "\n"; } dbgs()
796 << "\n\n================================================\n\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000797
798 std::vector<StringRef> BBNames;
799 std::vector<unsigned> RenamedInOtherBB;
800
801 unsigned GapIdx = 0;
802 unsigned BBNum = 0;
803
804 bool Changed = false;
805
Puyan Lotfid6f73132018-04-05 00:27:15 +0000806 MachineRegisterInfo &MRI = MF.getRegInfo();
807 NamedVRegCursor NVC(MRI);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000808 for (auto MBB : RPOList)
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000809 Changed |=
810 runOnBasicBlock(MBB, BBNames, RenamedInOtherBB, BBNum, GapIdx, NVC);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000811
812 return Changed;
813}