blob: e8a6e409fb51221d5db84078db0ff547926d900a [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) {
107 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
108 std::vector<MachineBasicBlock *> RPOList;
109 for (auto MBB : RPOT) {
110 RPOList.push_back(MBB);
111 }
112
113 return RPOList;
114}
115
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000116static bool
117rescheduleLexographically(std::vector<MachineInstr *> instructions,
118 MachineBasicBlock *MBB,
119 std::function<MachineBasicBlock::iterator()> getPos) {
120
121 bool Changed = false;
Puyan Lotfi380a6f52018-05-13 06:07:20 +0000122 using StringInstrPair = std::pair<std::string, MachineInstr *>;
123 std::vector<StringInstrPair> StringInstrMap;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000124
125 for (auto *II : instructions) {
126 std::string S;
127 raw_string_ostream OS(S);
128 II->print(OS);
129 OS.flush();
130
131 // Trim the assignment, or start from the begining in the case of a store.
132 const size_t i = S.find("=");
Puyan Lotfi380a6f52018-05-13 06:07:20 +0000133 StringInstrMap.push_back({(i == std::string::npos) ? S : S.substr(i), II});
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000134 }
135
Fangrui Song0cac7262018-09-27 02:13:45 +0000136 llvm::sort(StringInstrMap,
137 [](const StringInstrPair &a, const StringInstrPair &b) -> bool {
138 return (a.first < b.first);
139 });
Puyan Lotfi380a6f52018-05-13 06:07:20 +0000140
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000141 for (auto &II : StringInstrMap) {
142
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000143 LLVM_DEBUG({
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000144 dbgs() << "Splicing ";
145 II.second->dump();
146 dbgs() << " right before: ";
147 getPos()->dump();
148 });
149
150 Changed = true;
151 MBB->splice(getPos(), MBB, II.second);
152 }
153
154 return Changed;
155}
156
157static bool rescheduleCanonically(unsigned &PseudoIdempotentInstCount,
158 MachineBasicBlock *MBB) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000159
160 bool Changed = false;
161
162 // Calculates the distance of MI from the begining of its parent BB.
163 auto getInstrIdx = [](const MachineInstr &MI) {
164 unsigned i = 0;
165 for (auto &CurMI : *MI.getParent()) {
166 if (&CurMI == &MI)
167 return i;
168 i++;
169 }
170 return ~0U;
171 };
172
173 // Pre-Populate vector of instructions to reschedule so that we don't
174 // clobber the iterator.
175 std::vector<MachineInstr *> Instructions;
176 for (auto &MI : *MBB) {
177 Instructions.push_back(&MI);
178 }
179
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000180 std::map<MachineInstr *, std::vector<MachineInstr *>> MultiUsers;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000181 std::vector<MachineInstr *> PseudoIdempotentInstructions;
182 std::vector<unsigned> PhysRegDefs;
183 for (auto *II : Instructions) {
184 for (unsigned i = 1; i < II->getNumOperands(); i++) {
185 MachineOperand &MO = II->getOperand(i);
186 if (!MO.isReg())
187 continue;
188
189 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
190 continue;
191
192 if (!MO.isDef())
193 continue;
194
195 PhysRegDefs.push_back(MO.getReg());
196 }
197 }
198
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000199 for (auto *II : Instructions) {
200 if (II->getNumOperands() == 0)
201 continue;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000202 if (II->mayLoadOrStore())
203 continue;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000204
205 MachineOperand &MO = II->getOperand(0);
206 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
207 continue;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000208 if (!MO.isDef())
209 continue;
210
211 bool IsPseudoIdempotent = true;
212 for (unsigned i = 1; i < II->getNumOperands(); i++) {
213
214 if (II->getOperand(i).isImm()) {
215 continue;
216 }
217
218 if (II->getOperand(i).isReg()) {
219 if (!TargetRegisterInfo::isVirtualRegister(II->getOperand(i).getReg()))
220 if (llvm::find(PhysRegDefs, II->getOperand(i).getReg()) ==
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000221 PhysRegDefs.end()) {
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000222 continue;
223 }
224 }
225
226 IsPseudoIdempotent = false;
227 break;
228 }
229
230 if (IsPseudoIdempotent) {
231 PseudoIdempotentInstructions.push_back(II);
232 continue;
233 }
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000234
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000235 LLVM_DEBUG(dbgs() << "Operand " << 0 << " of "; II->dump(); MO.dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000236
237 MachineInstr *Def = II;
238 unsigned Distance = ~0U;
239 MachineInstr *UseToBringDefCloserTo = nullptr;
240 MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
241 for (auto &UO : MRI->use_nodbg_operands(MO.getReg())) {
242 MachineInstr *UseInst = UO.getParent();
243
244 const unsigned DefLoc = getInstrIdx(*Def);
245 const unsigned UseLoc = getInstrIdx(*UseInst);
246 const unsigned Delta = (UseLoc - DefLoc);
247
248 if (UseInst->getParent() != Def->getParent())
249 continue;
250 if (DefLoc >= UseLoc)
251 continue;
252
253 if (Delta < Distance) {
254 Distance = Delta;
255 UseToBringDefCloserTo = UseInst;
256 }
257 }
258
259 const auto BBE = MBB->instr_end();
260 MachineBasicBlock::iterator DefI = BBE;
261 MachineBasicBlock::iterator UseI = BBE;
262
263 for (auto BBI = MBB->instr_begin(); BBI != BBE; ++BBI) {
264
265 if (DefI != BBE && UseI != BBE)
266 break;
267
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000268 if (&*BBI == Def) {
269 DefI = BBI;
270 continue;
271 }
272
273 if (&*BBI == UseToBringDefCloserTo) {
274 UseI = BBI;
275 continue;
276 }
277 }
278
279 if (DefI == BBE || UseI == BBE)
280 continue;
281
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000282 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000283 dbgs() << "Splicing ";
284 DefI->dump();
285 dbgs() << " right before: ";
286 UseI->dump();
287 });
288
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000289 MultiUsers[UseToBringDefCloserTo].push_back(Def);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000290 Changed = true;
291 MBB->splice(UseI, MBB, DefI);
292 }
293
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000294 // Sort the defs for users of multiple defs lexographically.
295 for (const auto &E : MultiUsers) {
296
297 auto UseI =
298 std::find_if(MBB->instr_begin(), MBB->instr_end(),
299 [&](MachineInstr &MI) -> bool { return &MI == E.first; });
300
301 if (UseI == MBB->instr_end())
302 continue;
303
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000304 LLVM_DEBUG(
305 dbgs() << "Rescheduling Multi-Use Instructions Lexographically.";);
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000306 Changed |= rescheduleLexographically(
307 E.second, MBB, [&]() -> MachineBasicBlock::iterator { return UseI; });
308 }
309
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000310 PseudoIdempotentInstCount = PseudoIdempotentInstructions.size();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000311 LLVM_DEBUG(
312 dbgs() << "Rescheduling Idempotent Instructions Lexographically.";);
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000313 Changed |= rescheduleLexographically(
314 PseudoIdempotentInstructions, MBB,
315 [&]() -> MachineBasicBlock::iterator { return MBB->begin(); });
316
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000317 return Changed;
318}
319
Benjamin Kramer651d0bf2018-05-15 21:26:47 +0000320static bool propagateLocalCopies(MachineBasicBlock *MBB) {
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000321 bool Changed = false;
322 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
323
324 std::vector<MachineInstr *> Copies;
325 for (MachineInstr &MI : MBB->instrs()) {
326 if (MI.isCopy())
327 Copies.push_back(&MI);
328 }
329
330 for (MachineInstr *MI : Copies) {
331
332 if (!MI->getOperand(0).isReg())
333 continue;
334 if (!MI->getOperand(1).isReg())
335 continue;
336
337 const unsigned Dst = MI->getOperand(0).getReg();
338 const unsigned Src = MI->getOperand(1).getReg();
339
340 if (!TargetRegisterInfo::isVirtualRegister(Dst))
341 continue;
342 if (!TargetRegisterInfo::isVirtualRegister(Src))
343 continue;
344 if (MRI.getRegClass(Dst) != MRI.getRegClass(Src))
345 continue;
346
347 for (auto UI = MRI.use_begin(Dst); UI != MRI.use_end(); ++UI) {
348 MachineOperand *MO = &*UI;
349 MO->setReg(Src);
350 Changed = true;
351 }
352
353 MI->eraseFromParent();
354 }
355
356 return Changed;
357}
358
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000359/// Here we find our candidates. What makes an interesting candidate?
360/// An candidate for a canonicalization tree root is normally any kind of
361/// instruction that causes side effects such as a store to memory or a copy to
362/// a physical register or a return instruction. We use these as an expression
363/// tree root that we walk inorder to build a canonical walk which should result
364/// in canoncal vreg renaming.
365static std::vector<MachineInstr *> populateCandidates(MachineBasicBlock *MBB) {
366 std::vector<MachineInstr *> Candidates;
367 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
368
369 for (auto II = MBB->begin(), IE = MBB->end(); II != IE; ++II) {
370 MachineInstr *MI = &*II;
371
372 bool DoesMISideEffect = false;
373
374 if (MI->getNumOperands() > 0 && MI->getOperand(0).isReg()) {
375 const unsigned Dst = MI->getOperand(0).getReg();
376 DoesMISideEffect |= !TargetRegisterInfo::isVirtualRegister(Dst);
377
378 for (auto UI = MRI.use_begin(Dst); UI != MRI.use_end(); ++UI) {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000379 if (DoesMISideEffect)
380 break;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000381 DoesMISideEffect |= (UI->getParent()->getParent() != MI->getParent());
382 }
383 }
384
385 if (!MI->mayStore() && !MI->isBranch() && !DoesMISideEffect)
386 continue;
387
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000388 LLVM_DEBUG(dbgs() << "Found Candidate: "; MI->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000389 Candidates.push_back(MI);
390 }
391
392 return Candidates;
393}
394
Benjamin Kramer51ebcaa2017-11-24 14:55:41 +0000395static void doCandidateWalk(std::vector<TypedVReg> &VRegs,
396 std::queue<TypedVReg> &RegQueue,
397 std::vector<MachineInstr *> &VisitedMIs,
398 const MachineBasicBlock *MBB) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000399
400 const MachineFunction &MF = *MBB->getParent();
401 const MachineRegisterInfo &MRI = MF.getRegInfo();
402
403 while (!RegQueue.empty()) {
404
405 auto TReg = RegQueue.front();
406 RegQueue.pop();
407
408 if (TReg.isFrameIndex()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000409 LLVM_DEBUG(dbgs() << "Popping frame index.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000410 VRegs.push_back(TypedVReg(RSE_FrameIndex));
411 continue;
412 }
413
414 assert(TReg.isReg() && "Expected vreg or physreg.");
415 unsigned Reg = TReg.getReg();
416
417 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000418 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000419 dbgs() << "Popping vreg ";
420 MRI.def_begin(Reg)->dump();
421 dbgs() << "\n";
422 });
423
424 if (!llvm::any_of(VRegs, [&](const TypedVReg &TR) {
425 return TR.isReg() && TR.getReg() == Reg;
426 })) {
427 VRegs.push_back(TypedVReg(Reg));
428 }
429 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000430 LLVM_DEBUG(dbgs() << "Popping physreg.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000431 VRegs.push_back(TypedVReg(Reg));
432 continue;
433 }
434
435 for (auto RI = MRI.def_begin(Reg), RE = MRI.def_end(); RI != RE; ++RI) {
436 MachineInstr *Def = RI->getParent();
437
438 if (Def->getParent() != MBB)
439 continue;
440
441 if (llvm::any_of(VisitedMIs,
442 [&](const MachineInstr *VMI) { return Def == VMI; })) {
443 break;
444 }
445
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000446 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000447 dbgs() << "\n========================\n";
448 dbgs() << "Visited MI: ";
449 Def->dump();
450 dbgs() << "BB Name: " << Def->getParent()->getName() << "\n";
451 dbgs() << "\n========================\n";
452 });
453 VisitedMIs.push_back(Def);
454 for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
455
456 MachineOperand &MO = Def->getOperand(I);
457 if (MO.isFI()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000458 LLVM_DEBUG(dbgs() << "Pushing frame index.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000459 RegQueue.push(TypedVReg(RSE_FrameIndex));
460 }
461
462 if (!MO.isReg())
463 continue;
464 RegQueue.push(TypedVReg(MO.getReg()));
465 }
466 }
467 }
468}
469
Benjamin Kramer651d0bf2018-05-15 21:26:47 +0000470namespace {
Puyan Lotfid6f73132018-04-05 00:27:15 +0000471class NamedVRegCursor {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000472 MachineRegisterInfo &MRI;
473 unsigned virtualVRegNumber;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000474
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000475public:
476 NamedVRegCursor(MachineRegisterInfo &MRI) : MRI(MRI) {
477 unsigned VRegGapIndex = 0;
478 const unsigned VR_GAP = (++VRegGapIndex * 1000);
Puyan Lotfid6f73132018-04-05 00:27:15 +0000479
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000480 unsigned I = MRI.createIncompleteVirtualRegister();
481 const unsigned E = (((I + VR_GAP) / VR_GAP) + 1) * VR_GAP;
Puyan Lotfid6f73132018-04-05 00:27:15 +0000482
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000483 virtualVRegNumber = E;
484 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000485
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000486 void SkipVRegs() {
487 unsigned VRegGapIndex = 1;
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 = virtualVRegNumber;
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 unsigned getVirtualVReg() const { return virtualVRegNumber; }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000497
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000498 unsigned incrementVirtualVReg(unsigned incr = 1) {
499 virtualVRegNumber += incr;
500 return virtualVRegNumber;
501 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000502
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000503 unsigned createVirtualRegister(unsigned VReg) {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000504 std::string S;
505 raw_string_ostream OS(S);
506 OS << "namedVReg" << (virtualVRegNumber & ~0x80000000);
507 OS.flush();
508 virtualVRegNumber++;
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000509 if (auto RC = MRI.getRegClassOrNull(VReg))
510 return MRI.createVirtualRegister(RC, OS.str());
511 return MRI.createGenericVirtualRegister(MRI.getType(VReg), OS.str());
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000512 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000513};
Benjamin Kramer651d0bf2018-05-15 21:26:47 +0000514} // namespace
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000515
516static std::map<unsigned, unsigned>
517GetVRegRenameMap(const std::vector<TypedVReg> &VRegs,
518 const std::vector<unsigned> &renamedInOtherBB,
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000519 MachineRegisterInfo &MRI, NamedVRegCursor &NVC) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000520 std::map<unsigned, unsigned> VRegRenameMap;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000521 bool FirstCandidate = true;
522
523 for (auto &vreg : VRegs) {
524 if (vreg.isFrameIndex()) {
525 // We skip one vreg for any frame index because there is a good chance
526 // (especially when comparing SelectionDAG to GlobalISel generated MIR)
527 // that in the other file we are just getting an incoming vreg that comes
528 // from a copy from a frame index. So it's safe to skip by one.
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000529 unsigned LastRenameReg = NVC.incrementVirtualVReg();
530 (void)LastRenameReg;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000531 LLVM_DEBUG(dbgs() << "Skipping rename for FI " << LastRenameReg << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000532 continue;
533 } else if (vreg.isCandidate()) {
534
535 // After the first candidate, for every subsequent candidate, we skip mod
536 // 10 registers so that the candidates are more likely to start at the
537 // same vreg number making it more likely that the canonical walk from the
538 // candidate insruction. We don't need to skip from the first candidate of
539 // the BasicBlock because we already skip ahead several vregs for each BB.
Puyan Lotfid6f73132018-04-05 00:27:15 +0000540 unsigned LastRenameReg = NVC.getVirtualVReg();
541 if (FirstCandidate)
542 NVC.incrementVirtualVReg(LastRenameReg % 10);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000543 FirstCandidate = false;
544 continue;
545 } else if (!TargetRegisterInfo::isVirtualRegister(vreg.getReg())) {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000546 unsigned LastRenameReg = NVC.incrementVirtualVReg();
547 (void)LastRenameReg;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000548 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000549 dbgs() << "Skipping rename for Phys Reg " << LastRenameReg << "\n";
550 });
551 continue;
552 }
553
554 auto Reg = vreg.getReg();
555 if (llvm::find(renamedInOtherBB, Reg) != renamedInOtherBB.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000556 LLVM_DEBUG(dbgs() << "Vreg " << Reg
557 << " already renamed in other BB.\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000558 continue;
559 }
560
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000561 auto Rename = NVC.createVirtualRegister(Reg);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000562
563 if (VRegRenameMap.find(Reg) == VRegRenameMap.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000564 LLVM_DEBUG(dbgs() << "Mapping vreg ";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000565 if (MRI.reg_begin(Reg) != MRI.reg_end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000566 LLVM_DEBUG(auto foo = &*MRI.reg_begin(Reg); foo->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000567 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000568 LLVM_DEBUG(dbgs() << Reg;);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000569 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000570 LLVM_DEBUG(dbgs() << " to ";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000571 if (MRI.reg_begin(Rename) != MRI.reg_end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000572 LLVM_DEBUG(auto foo = &*MRI.reg_begin(Rename); foo->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000573 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000574 LLVM_DEBUG(dbgs() << Rename;);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000575 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000576 LLVM_DEBUG(dbgs() << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000577
578 VRegRenameMap.insert(std::pair<unsigned, unsigned>(Reg, Rename));
579 }
580 }
581
582 return VRegRenameMap;
583}
584
585static bool doVRegRenaming(std::vector<unsigned> &RenamedInOtherBB,
586 const std::map<unsigned, unsigned> &VRegRenameMap,
587 MachineRegisterInfo &MRI) {
588 bool Changed = false;
589 for (auto I = VRegRenameMap.begin(), E = VRegRenameMap.end(); I != E; ++I) {
590
591 auto VReg = I->first;
592 auto Rename = I->second;
593
594 RenamedInOtherBB.push_back(Rename);
595
596 std::vector<MachineOperand *> RenameMOs;
597 for (auto &MO : MRI.reg_operands(VReg)) {
598 RenameMOs.push_back(&MO);
599 }
600
601 for (auto *MO : RenameMOs) {
602 Changed = true;
603 MO->setReg(Rename);
604
605 if (!MO->isDef())
606 MO->setIsKill(false);
607 }
608 }
609
610 return Changed;
611}
612
613static bool doDefKillClear(MachineBasicBlock *MBB) {
614 bool Changed = false;
615
616 for (auto &MI : *MBB) {
617 for (auto &MO : MI.operands()) {
618 if (!MO.isReg())
619 continue;
620 if (!MO.isDef() && MO.isKill()) {
621 Changed = true;
622 MO.setIsKill(false);
623 }
624
625 if (MO.isDef() && MO.isDead()) {
626 Changed = true;
627 MO.setIsDead(false);
628 }
629 }
630 }
631
632 return Changed;
633}
634
635static bool runOnBasicBlock(MachineBasicBlock *MBB,
636 std::vector<StringRef> &bbNames,
637 std::vector<unsigned> &renamedInOtherBB,
Puyan Lotfid6f73132018-04-05 00:27:15 +0000638 unsigned &basicBlockNum, unsigned &VRegGapIndex,
639 NamedVRegCursor &NVC) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000640
641 if (CanonicalizeBasicBlockNumber != ~0U) {
642 if (CanonicalizeBasicBlockNumber != basicBlockNum++)
643 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000644 LLVM_DEBUG(dbgs() << "\n Canonicalizing BasicBlock " << MBB->getName()
645 << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000646 }
647
648 if (llvm::find(bbNames, MBB->getName()) != bbNames.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000649 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000650 dbgs() << "Found potentially duplicate BasicBlocks: " << MBB->getName()
651 << "\n";
652 });
653 return false;
654 }
655
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000656 LLVM_DEBUG({
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000657 dbgs() << "\n\n NEW BASIC BLOCK: " << MBB->getName() << " \n\n";
658 dbgs() << "\n\n================================================\n\n";
659 });
660
661 bool Changed = false;
662 MachineFunction &MF = *MBB->getParent();
663 MachineRegisterInfo &MRI = MF.getRegInfo();
664
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000665 bbNames.push_back(MBB->getName());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000666 LLVM_DEBUG(dbgs() << "\n\n NEW BASIC BLOCK: " << MBB->getName() << "\n\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000667
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000668 LLVM_DEBUG(dbgs() << "MBB Before Canonical Copy Propagation:\n";
669 MBB->dump(););
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000670 Changed |= propagateLocalCopies(MBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000671 LLVM_DEBUG(dbgs() << "MBB After Canonical Copy Propagation:\n"; MBB->dump(););
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000672
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000673 LLVM_DEBUG(dbgs() << "MBB Before Scheduling:\n"; MBB->dump(););
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000674 unsigned IdempotentInstCount = 0;
675 Changed |= rescheduleCanonically(IdempotentInstCount, MBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000676 LLVM_DEBUG(dbgs() << "MBB After Scheduling:\n"; MBB->dump(););
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000677
678 std::vector<MachineInstr *> Candidates = populateCandidates(MBB);
679 std::vector<MachineInstr *> VisitedMIs;
Fangrui Song75709322018-11-17 01:44:25 +0000680 llvm::copy(Candidates, std::back_inserter(VisitedMIs));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000681
682 std::vector<TypedVReg> VRegs;
683 for (auto candidate : Candidates) {
684 VRegs.push_back(TypedVReg(RSE_NewCandidate));
685
686 std::queue<TypedVReg> RegQueue;
687
688 // Here we walk the vreg operands of a non-root node along our walk.
689 // The root nodes are the original candidates (stores normally).
690 // These are normally not the root nodes (except for the case of copies to
691 // physical registers).
692 for (unsigned i = 1; i < candidate->getNumOperands(); i++) {
693 if (candidate->mayStore() || candidate->isBranch())
694 break;
695
696 MachineOperand &MO = candidate->getOperand(i);
697 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
698 continue;
699
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000700 LLVM_DEBUG(dbgs() << "Enqueue register"; MO.dump(); dbgs() << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000701 RegQueue.push(TypedVReg(MO.getReg()));
702 }
703
704 // Here we walk the root candidates. We start from the 0th operand because
705 // the root is normally a store to a vreg.
706 for (unsigned i = 0; i < candidate->getNumOperands(); i++) {
707
708 if (!candidate->mayStore() && !candidate->isBranch())
709 break;
710
711 MachineOperand &MO = candidate->getOperand(i);
712
713 // TODO: Do we want to only add vregs here?
714 if (!MO.isReg() && !MO.isFI())
715 continue;
716
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000717 LLVM_DEBUG(dbgs() << "Enqueue Reg/FI"; MO.dump(); dbgs() << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000718
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000719 RegQueue.push(MO.isReg() ? TypedVReg(MO.getReg())
720 : TypedVReg(RSE_FrameIndex));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000721 }
722
723 doCandidateWalk(VRegs, RegQueue, VisitedMIs, MBB);
724 }
725
726 // If we have populated no vregs to rename then bail.
727 // The rest of this function does the vreg remaping.
728 if (VRegs.size() == 0)
729 return Changed;
730
Puyan Lotfid6f73132018-04-05 00:27:15 +0000731 auto VRegRenameMap = GetVRegRenameMap(VRegs, renamedInOtherBB, MRI, NVC);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000732 Changed |= doVRegRenaming(renamedInOtherBB, VRegRenameMap, MRI);
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000733
734 // Here we renumber the def vregs for the idempotent instructions from the top
735 // of the MachineBasicBlock so that they are named in the order that we sorted
736 // them alphabetically. Eventually we wont need SkipVRegs because we will use
737 // named vregs instead.
Puyan Lotfid6f73132018-04-05 00:27:15 +0000738 NVC.SkipVRegs();
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000739
740 auto MII = MBB->begin();
741 for (unsigned i = 0; i < IdempotentInstCount && MII != MBB->end(); ++i) {
742 MachineInstr &MI = *MII++;
743 Changed = true;
744 unsigned vRegToRename = MI.getOperand(0).getReg();
Puyan Lotfi0f4446b2019-05-30 18:06:28 +0000745 auto Rename = NVC.createVirtualRegister(vRegToRename);
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000746
747 std::vector<MachineOperand *> RenameMOs;
748 for (auto &MO : MRI.reg_operands(vRegToRename)) {
749 RenameMOs.push_back(&MO);
750 }
751
752 for (auto *MO : RenameMOs) {
753 MO->setReg(Rename);
754 }
755 }
756
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000757 Changed |= doDefKillClear(MBB);
758
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000759 LLVM_DEBUG(dbgs() << "Updated MachineBasicBlock:\n"; MBB->dump();
760 dbgs() << "\n";);
761 LLVM_DEBUG(
762 dbgs() << "\n\n================================================\n\n");
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000763 return Changed;
764}
765
766bool MIRCanonicalizer::runOnMachineFunction(MachineFunction &MF) {
767
768 static unsigned functionNum = 0;
769 if (CanonicalizeFunctionNumber != ~0U) {
770 if (CanonicalizeFunctionNumber != functionNum++)
771 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000772 LLVM_DEBUG(dbgs() << "\n Canonicalizing Function " << MF.getName()
773 << "\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000774 }
775
776 // we need a valid vreg to create a vreg type for skipping all those
777 // stray vreg numbers so reach alignment/canonical vreg values.
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000778 std::vector<MachineBasicBlock *> RPOList = GetRPOList(MF);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000779
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000780 LLVM_DEBUG(
781 dbgs() << "\n\n NEW MACHINE FUNCTION: " << MF.getName() << " \n\n";
782 dbgs() << "\n\n================================================\n\n";
783 dbgs() << "Total Basic Blocks: " << RPOList.size() << "\n";
784 for (auto MBB
785 : RPOList) { dbgs() << MBB->getName() << "\n"; } dbgs()
786 << "\n\n================================================\n\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000787
788 std::vector<StringRef> BBNames;
789 std::vector<unsigned> RenamedInOtherBB;
790
791 unsigned GapIdx = 0;
792 unsigned BBNum = 0;
793
794 bool Changed = false;
795
Puyan Lotfid6f73132018-04-05 00:27:15 +0000796 MachineRegisterInfo &MRI = MF.getRegInfo();
797 NamedVRegCursor NVC(MRI);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000798 for (auto MBB : RPOList)
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000799 Changed |=
800 runOnBasicBlock(MBB, BBNames, RenamedInOtherBB, BBNum, GapIdx, NVC);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000801
802 return Changed;
803}