• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===---- ReachingDefAnalysis.cpp - Reaching Def Analysis ---*- C++ -*-----===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/ADT/SmallSet.h"
10 #include "llvm/CodeGen/LivePhysRegs.h"
11 #include "llvm/CodeGen/ReachingDefAnalysis.h"
12 #include "llvm/CodeGen/TargetRegisterInfo.h"
13 #include "llvm/CodeGen/TargetSubtargetInfo.h"
14 #include "llvm/Support/Debug.h"
15 
16 using namespace llvm;
17 
18 #define DEBUG_TYPE "reaching-deps-analysis"
19 
20 char ReachingDefAnalysis::ID = 0;
21 INITIALIZE_PASS(ReachingDefAnalysis, DEBUG_TYPE, "ReachingDefAnalysis", false,
22                 true)
23 
isValidReg(const MachineOperand & MO)24 static bool isValidReg(const MachineOperand &MO) {
25   return MO.isReg() && MO.getReg();
26 }
27 
isValidRegUse(const MachineOperand & MO)28 static bool isValidRegUse(const MachineOperand &MO) {
29   return isValidReg(MO) && MO.isUse();
30 }
31 
isValidRegUseOf(const MachineOperand & MO,MCRegister PhysReg)32 static bool isValidRegUseOf(const MachineOperand &MO, MCRegister PhysReg) {
33   return isValidRegUse(MO) && MO.getReg() == PhysReg;
34 }
35 
isValidRegDef(const MachineOperand & MO)36 static bool isValidRegDef(const MachineOperand &MO) {
37   return isValidReg(MO) && MO.isDef();
38 }
39 
isValidRegDefOf(const MachineOperand & MO,MCRegister PhysReg)40 static bool isValidRegDefOf(const MachineOperand &MO, MCRegister PhysReg) {
41   return isValidRegDef(MO) && MO.getReg() == PhysReg;
42 }
43 
enterBasicBlock(MachineBasicBlock * MBB)44 void ReachingDefAnalysis::enterBasicBlock(MachineBasicBlock *MBB) {
45   unsigned MBBNumber = MBB->getNumber();
46   assert(MBBNumber < MBBReachingDefs.size() &&
47          "Unexpected basic block number.");
48   MBBReachingDefs[MBBNumber].resize(NumRegUnits);
49 
50   // Reset instruction counter in each basic block.
51   CurInstr = 0;
52 
53   // Set up LiveRegs to represent registers entering MBB.
54   // Default values are 'nothing happened a long time ago'.
55   if (LiveRegs.empty())
56     LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
57 
58   // This is the entry block.
59   if (MBB->pred_empty()) {
60     for (const auto &LI : MBB->liveins()) {
61       for (MCRegUnitIterator Unit(LI.PhysReg, TRI); Unit.isValid(); ++Unit) {
62         // Treat function live-ins as if they were defined just before the first
63         // instruction.  Usually, function arguments are set up immediately
64         // before the call.
65         if (LiveRegs[*Unit] != -1) {
66           LiveRegs[*Unit] = -1;
67           MBBReachingDefs[MBBNumber][*Unit].push_back(-1);
68         }
69       }
70     }
71     LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": entry\n");
72     return;
73   }
74 
75   // Try to coalesce live-out registers from predecessors.
76   for (MachineBasicBlock *pred : MBB->predecessors()) {
77     assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
78            "Should have pre-allocated MBBInfos for all MBBs");
79     const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
80     // Incoming is null if this is a backedge from a BB
81     // we haven't processed yet
82     if (Incoming.empty())
83       continue;
84 
85     // Find the most recent reaching definition from a predecessor.
86     for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
87       LiveRegs[Unit] = std::max(LiveRegs[Unit], Incoming[Unit]);
88   }
89 
90   // Insert the most recent reaching definition we found.
91   for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
92     if (LiveRegs[Unit] != ReachingDefDefaultVal)
93       MBBReachingDefs[MBBNumber][Unit].push_back(LiveRegs[Unit]);
94 }
95 
leaveBasicBlock(MachineBasicBlock * MBB)96 void ReachingDefAnalysis::leaveBasicBlock(MachineBasicBlock *MBB) {
97   assert(!LiveRegs.empty() && "Must enter basic block first.");
98   unsigned MBBNumber = MBB->getNumber();
99   assert(MBBNumber < MBBOutRegsInfos.size() &&
100          "Unexpected basic block number.");
101   // Save register clearances at end of MBB - used by enterBasicBlock().
102   MBBOutRegsInfos[MBBNumber] = LiveRegs;
103 
104   // While processing the basic block, we kept `Def` relative to the start
105   // of the basic block for convenience. However, future use of this information
106   // only cares about the clearance from the end of the block, so adjust
107   // everything to be relative to the end of the basic block.
108   for (int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
109     if (OutLiveReg != ReachingDefDefaultVal)
110       OutLiveReg -= CurInstr;
111   LiveRegs.clear();
112 }
113 
processDefs(MachineInstr * MI)114 void ReachingDefAnalysis::processDefs(MachineInstr *MI) {
115   assert(!MI->isDebugInstr() && "Won't process debug instructions");
116 
117   unsigned MBBNumber = MI->getParent()->getNumber();
118   assert(MBBNumber < MBBReachingDefs.size() &&
119          "Unexpected basic block number.");
120 
121   for (auto &MO : MI->operands()) {
122     if (!isValidRegDef(MO))
123       continue;
124     for (MCRegUnitIterator Unit(MO.getReg().asMCReg(), TRI); Unit.isValid();
125          ++Unit) {
126       // This instruction explicitly defines the current reg unit.
127       LLVM_DEBUG(dbgs() << printReg(*Unit, TRI) << ":\t" << CurInstr
128                         << '\t' << *MI);
129 
130       // How many instructions since this reg unit was last written?
131       if (LiveRegs[*Unit] != CurInstr) {
132         LiveRegs[*Unit] = CurInstr;
133         MBBReachingDefs[MBBNumber][*Unit].push_back(CurInstr);
134       }
135     }
136   }
137   InstIds[MI] = CurInstr;
138   ++CurInstr;
139 }
140 
reprocessBasicBlock(MachineBasicBlock * MBB)141 void ReachingDefAnalysis::reprocessBasicBlock(MachineBasicBlock *MBB) {
142   unsigned MBBNumber = MBB->getNumber();
143   assert(MBBNumber < MBBReachingDefs.size() &&
144          "Unexpected basic block number.");
145 
146   // Count number of non-debug instructions for end of block adjustment.
147   auto NonDbgInsts =
148     instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end());
149   int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
150 
151   // When reprocessing a block, the only thing we need to do is check whether
152   // there is now a more recent incoming reaching definition from a predecessor.
153   for (MachineBasicBlock *pred : MBB->predecessors()) {
154     assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
155            "Should have pre-allocated MBBInfos for all MBBs");
156     const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
157     // Incoming may be empty for dead predecessors.
158     if (Incoming.empty())
159       continue;
160 
161     for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
162       int Def = Incoming[Unit];
163       if (Def == ReachingDefDefaultVal)
164         continue;
165 
166       auto Start = MBBReachingDefs[MBBNumber][Unit].begin();
167       if (Start != MBBReachingDefs[MBBNumber][Unit].end() && *Start < 0) {
168         if (*Start >= Def)
169           continue;
170 
171         // Update existing reaching def from predecessor to a more recent one.
172         *Start = Def;
173       } else {
174         // Insert new reaching def from predecessor.
175         MBBReachingDefs[MBBNumber][Unit].insert(Start, Def);
176       }
177 
178       // Update reaching def at end of of BB. Keep in mind that these are
179       // adjusted relative to the end of the basic block.
180       if (MBBOutRegsInfos[MBBNumber][Unit] < Def - NumInsts)
181         MBBOutRegsInfos[MBBNumber][Unit] = Def - NumInsts;
182     }
183   }
184 }
185 
processBasicBlock(const LoopTraversal::TraversedMBBInfo & TraversedMBB)186 void ReachingDefAnalysis::processBasicBlock(
187     const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
188   MachineBasicBlock *MBB = TraversedMBB.MBB;
189   LLVM_DEBUG(dbgs() << printMBBReference(*MBB)
190                     << (!TraversedMBB.IsDone ? ": incomplete\n"
191                                              : ": all preds known\n"));
192 
193   if (!TraversedMBB.PrimaryPass) {
194     // Reprocess MBB that is part of a loop.
195     reprocessBasicBlock(MBB);
196     return;
197   }
198 
199   enterBasicBlock(MBB);
200   for (MachineInstr &MI :
201        instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end()))
202     processDefs(&MI);
203   leaveBasicBlock(MBB);
204 }
205 
runOnMachineFunction(MachineFunction & mf)206 bool ReachingDefAnalysis::runOnMachineFunction(MachineFunction &mf) {
207   MF = &mf;
208   TRI = MF->getSubtarget().getRegisterInfo();
209   LLVM_DEBUG(dbgs() << "********** REACHING DEFINITION ANALYSIS **********\n");
210   init();
211   traverse();
212   return false;
213 }
214 
releaseMemory()215 void ReachingDefAnalysis::releaseMemory() {
216   // Clear the internal vectors.
217   MBBOutRegsInfos.clear();
218   MBBReachingDefs.clear();
219   InstIds.clear();
220   LiveRegs.clear();
221 }
222 
reset()223 void ReachingDefAnalysis::reset() {
224   releaseMemory();
225   init();
226   traverse();
227 }
228 
init()229 void ReachingDefAnalysis::init() {
230   NumRegUnits = TRI->getNumRegUnits();
231   MBBReachingDefs.resize(MF->getNumBlockIDs());
232   // Initialize the MBBOutRegsInfos
233   MBBOutRegsInfos.resize(MF->getNumBlockIDs());
234   LoopTraversal Traversal;
235   TraversedMBBOrder = Traversal.traverse(*MF);
236 }
237 
traverse()238 void ReachingDefAnalysis::traverse() {
239   // Traverse the basic blocks.
240   for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder)
241     processBasicBlock(TraversedMBB);
242 #ifndef NDEBUG
243   // Make sure reaching defs are sorted and unique.
244   for (MBBDefsInfo &MBBDefs : MBBReachingDefs) {
245     for (MBBRegUnitDefs &RegUnitDefs : MBBDefs) {
246       int LastDef = ReachingDefDefaultVal;
247       for (int Def : RegUnitDefs) {
248         assert(Def > LastDef && "Defs must be sorted and unique");
249         LastDef = Def;
250       }
251     }
252   }
253 #endif
254 }
255 
getReachingDef(MachineInstr * MI,MCRegister PhysReg) const256 int ReachingDefAnalysis::getReachingDef(MachineInstr *MI,
257                                         MCRegister PhysReg) const {
258   assert(InstIds.count(MI) && "Unexpected machine instuction.");
259   int InstId = InstIds.lookup(MI);
260   int DefRes = ReachingDefDefaultVal;
261   unsigned MBBNumber = MI->getParent()->getNumber();
262   assert(MBBNumber < MBBReachingDefs.size() &&
263          "Unexpected basic block number.");
264   int LatestDef = ReachingDefDefaultVal;
265   for (MCRegUnitIterator Unit(PhysReg, TRI); Unit.isValid(); ++Unit) {
266     for (int Def : MBBReachingDefs[MBBNumber][*Unit]) {
267       if (Def >= InstId)
268         break;
269       DefRes = Def;
270     }
271     LatestDef = std::max(LatestDef, DefRes);
272   }
273   return LatestDef;
274 }
275 
276 MachineInstr *
getReachingLocalMIDef(MachineInstr * MI,MCRegister PhysReg) const277 ReachingDefAnalysis::getReachingLocalMIDef(MachineInstr *MI,
278                                            MCRegister PhysReg) const {
279   return hasLocalDefBefore(MI, PhysReg)
280     ? getInstFromId(MI->getParent(), getReachingDef(MI, PhysReg))
281     : nullptr;
282 }
283 
hasSameReachingDef(MachineInstr * A,MachineInstr * B,MCRegister PhysReg) const284 bool ReachingDefAnalysis::hasSameReachingDef(MachineInstr *A, MachineInstr *B,
285                                              MCRegister PhysReg) const {
286   MachineBasicBlock *ParentA = A->getParent();
287   MachineBasicBlock *ParentB = B->getParent();
288   if (ParentA != ParentB)
289     return false;
290 
291   return getReachingDef(A, PhysReg) == getReachingDef(B, PhysReg);
292 }
293 
getInstFromId(MachineBasicBlock * MBB,int InstId) const294 MachineInstr *ReachingDefAnalysis::getInstFromId(MachineBasicBlock *MBB,
295                                                  int InstId) const {
296   assert(static_cast<size_t>(MBB->getNumber()) < MBBReachingDefs.size() &&
297          "Unexpected basic block number.");
298   assert(InstId < static_cast<int>(MBB->size()) &&
299          "Unexpected instruction id.");
300 
301   if (InstId < 0)
302     return nullptr;
303 
304   for (auto &MI : *MBB) {
305     auto F = InstIds.find(&MI);
306     if (F != InstIds.end() && F->second == InstId)
307       return &MI;
308   }
309 
310   return nullptr;
311 }
312 
getClearance(MachineInstr * MI,MCRegister PhysReg) const313 int ReachingDefAnalysis::getClearance(MachineInstr *MI,
314                                       MCRegister PhysReg) const {
315   assert(InstIds.count(MI) && "Unexpected machine instuction.");
316   return InstIds.lookup(MI) - getReachingDef(MI, PhysReg);
317 }
318 
hasLocalDefBefore(MachineInstr * MI,MCRegister PhysReg) const319 bool ReachingDefAnalysis::hasLocalDefBefore(MachineInstr *MI,
320                                             MCRegister PhysReg) const {
321   return getReachingDef(MI, PhysReg) >= 0;
322 }
323 
getReachingLocalUses(MachineInstr * Def,MCRegister PhysReg,InstSet & Uses) const324 void ReachingDefAnalysis::getReachingLocalUses(MachineInstr *Def,
325                                                MCRegister PhysReg,
326                                                InstSet &Uses) const {
327   MachineBasicBlock *MBB = Def->getParent();
328   MachineBasicBlock::iterator MI = MachineBasicBlock::iterator(Def);
329   while (++MI != MBB->end()) {
330     if (MI->isDebugInstr())
331       continue;
332 
333     // If/when we find a new reaching def, we know that there's no more uses
334     // of 'Def'.
335     if (getReachingLocalMIDef(&*MI, PhysReg) != Def)
336       return;
337 
338     for (auto &MO : MI->operands()) {
339       if (!isValidRegUseOf(MO, PhysReg))
340         continue;
341 
342       Uses.insert(&*MI);
343       if (MO.isKill())
344         return;
345     }
346   }
347 }
348 
getLiveInUses(MachineBasicBlock * MBB,MCRegister PhysReg,InstSet & Uses) const349 bool ReachingDefAnalysis::getLiveInUses(MachineBasicBlock *MBB,
350                                         MCRegister PhysReg,
351                                         InstSet &Uses) const {
352   for (MachineInstr &MI :
353        instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end())) {
354     for (auto &MO : MI.operands()) {
355       if (!isValidRegUseOf(MO, PhysReg))
356         continue;
357       if (getReachingDef(&MI, PhysReg) >= 0)
358         return false;
359       Uses.insert(&MI);
360     }
361   }
362   auto Last = MBB->getLastNonDebugInstr();
363   if (Last == MBB->end())
364     return true;
365   return isReachingDefLiveOut(&*Last, PhysReg);
366 }
367 
getGlobalUses(MachineInstr * MI,MCRegister PhysReg,InstSet & Uses) const368 void ReachingDefAnalysis::getGlobalUses(MachineInstr *MI, MCRegister PhysReg,
369                                         InstSet &Uses) const {
370   MachineBasicBlock *MBB = MI->getParent();
371 
372   // Collect the uses that each def touches within the block.
373   getReachingLocalUses(MI, PhysReg, Uses);
374 
375   // Handle live-out values.
376   if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), PhysReg)) {
377     if (LiveOut != MI)
378       return;
379 
380     SmallVector<MachineBasicBlock*, 4> ToVisit;
381     ToVisit.insert(ToVisit.begin(), MBB->successors().begin(),
382                    MBB->successors().end());
383     SmallPtrSet<MachineBasicBlock*, 4>Visited;
384     while (!ToVisit.empty()) {
385       MachineBasicBlock *MBB = ToVisit.back();
386       ToVisit.pop_back();
387       if (Visited.count(MBB) || !MBB->isLiveIn(PhysReg))
388         continue;
389       if (getLiveInUses(MBB, PhysReg, Uses))
390         ToVisit.insert(ToVisit.end(), MBB->successors().begin(),
391                        MBB->successors().end());
392       Visited.insert(MBB);
393     }
394   }
395 }
396 
getGlobalReachingDefs(MachineInstr * MI,MCRegister PhysReg,InstSet & Defs) const397 void ReachingDefAnalysis::getGlobalReachingDefs(MachineInstr *MI,
398                                                 MCRegister PhysReg,
399                                                 InstSet &Defs) const {
400   if (auto *Def = getUniqueReachingMIDef(MI, PhysReg)) {
401     Defs.insert(Def);
402     return;
403   }
404 
405   for (auto *MBB : MI->getParent()->predecessors())
406     getLiveOuts(MBB, PhysReg, Defs);
407 }
408 
getLiveOuts(MachineBasicBlock * MBB,MCRegister PhysReg,InstSet & Defs) const409 void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock *MBB,
410                                       MCRegister PhysReg, InstSet &Defs) const {
411   SmallPtrSet<MachineBasicBlock*, 2> VisitedBBs;
412   getLiveOuts(MBB, PhysReg, Defs, VisitedBBs);
413 }
414 
getLiveOuts(MachineBasicBlock * MBB,MCRegister PhysReg,InstSet & Defs,BlockSet & VisitedBBs) const415 void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock *MBB,
416                                       MCRegister PhysReg, InstSet &Defs,
417                                       BlockSet &VisitedBBs) const {
418   if (VisitedBBs.count(MBB))
419     return;
420 
421   VisitedBBs.insert(MBB);
422   LivePhysRegs LiveRegs(*TRI);
423   LiveRegs.addLiveOuts(*MBB);
424   if (!LiveRegs.contains(PhysReg))
425     return;
426 
427   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
428     Defs.insert(Def);
429   else
430     for (auto *Pred : MBB->predecessors())
431       getLiveOuts(Pred, PhysReg, Defs, VisitedBBs);
432 }
433 
434 MachineInstr *
getUniqueReachingMIDef(MachineInstr * MI,MCRegister PhysReg) const435 ReachingDefAnalysis::getUniqueReachingMIDef(MachineInstr *MI,
436                                             MCRegister PhysReg) const {
437   // If there's a local def before MI, return it.
438   MachineInstr *LocalDef = getReachingLocalMIDef(MI, PhysReg);
439   if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
440     return LocalDef;
441 
442   SmallPtrSet<MachineInstr*, 2> Incoming;
443   MachineBasicBlock *Parent = MI->getParent();
444   for (auto *Pred : Parent->predecessors())
445     getLiveOuts(Pred, PhysReg, Incoming);
446 
447   // Check that we have a single incoming value and that it does not
448   // come from the same block as MI - since it would mean that the def
449   // is executed after MI.
450   if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
451     return *Incoming.begin();
452   return nullptr;
453 }
454 
getMIOperand(MachineInstr * MI,unsigned Idx) const455 MachineInstr *ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
456                                                 unsigned Idx) const {
457   assert(MI->getOperand(Idx).isReg() && "Expected register operand");
458   return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
459 }
460 
getMIOperand(MachineInstr * MI,MachineOperand & MO) const461 MachineInstr *ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
462                                                 MachineOperand &MO) const {
463   assert(MO.isReg() && "Expected register operand");
464   return getUniqueReachingMIDef(MI, MO.getReg());
465 }
466 
isRegUsedAfter(MachineInstr * MI,MCRegister PhysReg) const467 bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
468                                          MCRegister PhysReg) const {
469   MachineBasicBlock *MBB = MI->getParent();
470   LivePhysRegs LiveRegs(*TRI);
471   LiveRegs.addLiveOuts(*MBB);
472 
473   // Yes if the register is live out of the basic block.
474   if (LiveRegs.contains(PhysReg))
475     return true;
476 
477   // Walk backwards through the block to see if the register is live at some
478   // point.
479   for (MachineInstr &Last :
480        instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
481     LiveRegs.stepBackward(Last);
482     if (LiveRegs.contains(PhysReg))
483       return InstIds.lookup(&Last) > InstIds.lookup(MI);
484   }
485   return false;
486 }
487 
isRegDefinedAfter(MachineInstr * MI,MCRegister PhysReg) const488 bool ReachingDefAnalysis::isRegDefinedAfter(MachineInstr *MI,
489                                             MCRegister PhysReg) const {
490   MachineBasicBlock *MBB = MI->getParent();
491   auto Last = MBB->getLastNonDebugInstr();
492   if (Last != MBB->end() &&
493       getReachingDef(MI, PhysReg) != getReachingDef(&*Last, PhysReg))
494     return true;
495 
496   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
497     return Def == getReachingLocalMIDef(MI, PhysReg);
498 
499   return false;
500 }
501 
isReachingDefLiveOut(MachineInstr * MI,MCRegister PhysReg) const502 bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr *MI,
503                                                MCRegister PhysReg) const {
504   MachineBasicBlock *MBB = MI->getParent();
505   LivePhysRegs LiveRegs(*TRI);
506   LiveRegs.addLiveOuts(*MBB);
507   if (!LiveRegs.contains(PhysReg))
508     return false;
509 
510   auto Last = MBB->getLastNonDebugInstr();
511   int Def = getReachingDef(MI, PhysReg);
512   if (Last != MBB->end() && getReachingDef(&*Last, PhysReg) != Def)
513     return false;
514 
515   // Finally check that the last instruction doesn't redefine the register.
516   for (auto &MO : Last->operands())
517     if (isValidRegDefOf(MO, PhysReg))
518       return false;
519 
520   return true;
521 }
522 
523 MachineInstr *
getLocalLiveOutMIDef(MachineBasicBlock * MBB,MCRegister PhysReg) const524 ReachingDefAnalysis::getLocalLiveOutMIDef(MachineBasicBlock *MBB,
525                                           MCRegister PhysReg) const {
526   LivePhysRegs LiveRegs(*TRI);
527   LiveRegs.addLiveOuts(*MBB);
528   if (!LiveRegs.contains(PhysReg))
529     return nullptr;
530 
531   auto Last = MBB->getLastNonDebugInstr();
532   if (Last == MBB->end())
533     return nullptr;
534 
535   int Def = getReachingDef(&*Last, PhysReg);
536   for (auto &MO : Last->operands())
537     if (isValidRegDefOf(MO, PhysReg))
538       return &*Last;
539 
540   return Def < 0 ? nullptr : getInstFromId(MBB, Def);
541 }
542 
mayHaveSideEffects(MachineInstr & MI)543 static bool mayHaveSideEffects(MachineInstr &MI) {
544   return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
545          MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
546          MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
547 }
548 
549 // Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
550 // not define a register that is used by any instructions, after and including,
551 // 'To'. These instructions also must not redefine any of Froms operands.
552 template<typename Iterator>
isSafeToMove(MachineInstr * From,MachineInstr * To) const553 bool ReachingDefAnalysis::isSafeToMove(MachineInstr *From,
554                                        MachineInstr *To) const {
555   if (From->getParent() != To->getParent() || From == To)
556     return false;
557 
558   SmallSet<int, 2> Defs;
559   // First check that From would compute the same value if moved.
560   for (auto &MO : From->operands()) {
561     if (!isValidReg(MO))
562       continue;
563     if (MO.isDef())
564       Defs.insert(MO.getReg());
565     else if (!hasSameReachingDef(From, To, MO.getReg()))
566       return false;
567   }
568 
569   // Now walk checking that the rest of the instructions will compute the same
570   // value and that we're not overwriting anything. Don't move the instruction
571   // past any memory, control-flow or other ambiguous instructions.
572   for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
573     if (mayHaveSideEffects(*I))
574       return false;
575     for (auto &MO : I->operands())
576       if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
577         return false;
578   }
579   return true;
580 }
581 
isSafeToMoveForwards(MachineInstr * From,MachineInstr * To) const582 bool ReachingDefAnalysis::isSafeToMoveForwards(MachineInstr *From,
583                                                MachineInstr *To) const {
584   using Iterator = MachineBasicBlock::iterator;
585   // Walk forwards until we find the instruction.
586   for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
587     if (&*I == To)
588       return isSafeToMove<Iterator>(From, To);
589   return false;
590 }
591 
isSafeToMoveBackwards(MachineInstr * From,MachineInstr * To) const592 bool ReachingDefAnalysis::isSafeToMoveBackwards(MachineInstr *From,
593                                                 MachineInstr *To) const {
594   using Iterator = MachineBasicBlock::reverse_iterator;
595   // Walk backwards until we find the instruction.
596   for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
597     if (&*I == To)
598       return isSafeToMove<Iterator>(From, To);
599   return false;
600 }
601 
isSafeToRemove(MachineInstr * MI,InstSet & ToRemove) const602 bool ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI,
603                                          InstSet &ToRemove) const {
604   SmallPtrSet<MachineInstr*, 1> Ignore;
605   SmallPtrSet<MachineInstr*, 2> Visited;
606   return isSafeToRemove(MI, Visited, ToRemove, Ignore);
607 }
608 
609 bool
isSafeToRemove(MachineInstr * MI,InstSet & ToRemove,InstSet & Ignore) const610 ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &ToRemove,
611                                     InstSet &Ignore) const {
612   SmallPtrSet<MachineInstr*, 2> Visited;
613   return isSafeToRemove(MI, Visited, ToRemove, Ignore);
614 }
615 
616 bool
isSafeToRemove(MachineInstr * MI,InstSet & Visited,InstSet & ToRemove,InstSet & Ignore) const617 ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
618                                     InstSet &ToRemove, InstSet &Ignore) const {
619   if (Visited.count(MI) || Ignore.count(MI))
620     return true;
621   else if (mayHaveSideEffects(*MI)) {
622     // Unless told to ignore the instruction, don't remove anything which has
623     // side effects.
624     return false;
625   }
626 
627   Visited.insert(MI);
628   for (auto &MO : MI->operands()) {
629     if (!isValidRegDef(MO))
630       continue;
631 
632     SmallPtrSet<MachineInstr*, 4> Uses;
633     getGlobalUses(MI, MO.getReg(), Uses);
634 
635     for (auto I : Uses) {
636       if (Ignore.count(I) || ToRemove.count(I))
637         continue;
638       if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
639         return false;
640     }
641   }
642   ToRemove.insert(MI);
643   return true;
644 }
645 
collectKilledOperands(MachineInstr * MI,InstSet & Dead) const646 void ReachingDefAnalysis::collectKilledOperands(MachineInstr *MI,
647                                                 InstSet &Dead) const {
648   Dead.insert(MI);
649   auto IsDead = [this, &Dead](MachineInstr *Def, MCRegister PhysReg) {
650     if (mayHaveSideEffects(*Def))
651       return false;
652 
653     unsigned LiveDefs = 0;
654     for (auto &MO : Def->operands()) {
655       if (!isValidRegDef(MO))
656         continue;
657       if (!MO.isDead())
658         ++LiveDefs;
659     }
660 
661     if (LiveDefs > 1)
662       return false;
663 
664     SmallPtrSet<MachineInstr*, 4> Uses;
665     getGlobalUses(Def, PhysReg, Uses);
666     for (auto *Use : Uses)
667       if (!Dead.count(Use))
668         return false;
669     return true;
670   };
671 
672   for (auto &MO : MI->operands()) {
673     if (!isValidRegUse(MO))
674       continue;
675     if (MachineInstr *Def = getMIOperand(MI, MO))
676       if (IsDead(Def, MO.getReg()))
677         collectKilledOperands(Def, Dead);
678   }
679 }
680 
isSafeToDefRegAt(MachineInstr * MI,MCRegister PhysReg) const681 bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI,
682                                            MCRegister PhysReg) const {
683   SmallPtrSet<MachineInstr*, 1> Ignore;
684   return isSafeToDefRegAt(MI, PhysReg, Ignore);
685 }
686 
isSafeToDefRegAt(MachineInstr * MI,MCRegister PhysReg,InstSet & Ignore) const687 bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI, MCRegister PhysReg,
688                                            InstSet &Ignore) const {
689   // Check for any uses of the register after MI.
690   if (isRegUsedAfter(MI, PhysReg)) {
691     if (auto *Def = getReachingLocalMIDef(MI, PhysReg)) {
692       SmallPtrSet<MachineInstr*, 2> Uses;
693       getGlobalUses(Def, PhysReg, Uses);
694       for (auto *Use : Uses)
695         if (!Ignore.count(Use))
696           return false;
697     } else
698       return false;
699   }
700 
701   MachineBasicBlock *MBB = MI->getParent();
702   // Check for any defs after MI.
703   if (isRegDefinedAfter(MI, PhysReg)) {
704     auto I = MachineBasicBlock::iterator(MI);
705     for (auto E = MBB->end(); I != E; ++I) {
706       if (Ignore.count(&*I))
707         continue;
708       for (auto &MO : I->operands())
709         if (isValidRegDefOf(MO, PhysReg))
710           return false;
711     }
712   }
713   return true;
714 }
715