xref: /llvm-project/llvm/lib/CodeGen/ReachingDefAnalysis.cpp (revision 1e3ed09165cf89b7f87318b4a5f7cab484661d49)
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 
24 static bool isValidReg(const MachineOperand &MO) {
25   return MO.isReg() && MO.getReg();
26 }
27 
28 static bool isValidRegUse(const MachineOperand &MO) {
29   return isValidReg(MO) && MO.isUse();
30 }
31 
32 static bool isValidRegUseOf(const MachineOperand &MO, MCRegister PhysReg) {
33   return isValidRegUse(MO) && MO.getReg() == PhysReg;
34 }
35 
36 static bool isValidRegDef(const MachineOperand &MO) {
37   return isValidReg(MO) && MO.isDef();
38 }
39 
40 static bool isValidRegDefOf(const MachineOperand &MO, MCRegister PhysReg) {
41   return isValidRegDef(MO) && MO.getReg() == PhysReg;
42 }
43 
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 
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 
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 
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 
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 
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 
215 void ReachingDefAnalysis::releaseMemory() {
216   // Clear the internal vectors.
217   MBBOutRegsInfos.clear();
218   MBBReachingDefs.clear();
219   InstIds.clear();
220   LiveRegs.clear();
221 }
222 
223 void ReachingDefAnalysis::reset() {
224   releaseMemory();
225   init();
226   traverse();
227 }
228 
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 
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 
256 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 *
277 ReachingDefAnalysis::getReachingLocalMIDef(MachineInstr *MI,
278                                            MCRegister PhysReg) const {
279   return hasLocalDefBefore(MI, PhysReg)
280     ? getInstFromId(MI->getParent(), getReachingDef(MI, PhysReg))
281     : nullptr;
282 }
283 
284 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 
294 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 
313 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 
319 bool ReachingDefAnalysis::hasLocalDefBefore(MachineInstr *MI,
320                                             MCRegister PhysReg) const {
321   return getReachingDef(MI, PhysReg) >= 0;
322 }
323 
324 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 
349 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 
368 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         llvm::append_range(ToVisit, MBB->successors());
391       Visited.insert(MBB);
392     }
393   }
394 }
395 
396 void ReachingDefAnalysis::getGlobalReachingDefs(MachineInstr *MI,
397                                                 MCRegister PhysReg,
398                                                 InstSet &Defs) const {
399   if (auto *Def = getUniqueReachingMIDef(MI, PhysReg)) {
400     Defs.insert(Def);
401     return;
402   }
403 
404   for (auto *MBB : MI->getParent()->predecessors())
405     getLiveOuts(MBB, PhysReg, Defs);
406 }
407 
408 void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock *MBB,
409                                       MCRegister PhysReg, InstSet &Defs) const {
410   SmallPtrSet<MachineBasicBlock*, 2> VisitedBBs;
411   getLiveOuts(MBB, PhysReg, Defs, VisitedBBs);
412 }
413 
414 void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock *MBB,
415                                       MCRegister PhysReg, InstSet &Defs,
416                                       BlockSet &VisitedBBs) const {
417   if (VisitedBBs.count(MBB))
418     return;
419 
420   VisitedBBs.insert(MBB);
421   LivePhysRegs LiveRegs(*TRI);
422   LiveRegs.addLiveOuts(*MBB);
423   if (!LiveRegs.contains(PhysReg))
424     return;
425 
426   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
427     Defs.insert(Def);
428   else
429     for (auto *Pred : MBB->predecessors())
430       getLiveOuts(Pred, PhysReg, Defs, VisitedBBs);
431 }
432 
433 MachineInstr *
434 ReachingDefAnalysis::getUniqueReachingMIDef(MachineInstr *MI,
435                                             MCRegister PhysReg) const {
436   // If there's a local def before MI, return it.
437   MachineInstr *LocalDef = getReachingLocalMIDef(MI, PhysReg);
438   if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
439     return LocalDef;
440 
441   SmallPtrSet<MachineInstr*, 2> Incoming;
442   MachineBasicBlock *Parent = MI->getParent();
443   for (auto *Pred : Parent->predecessors())
444     getLiveOuts(Pred, PhysReg, Incoming);
445 
446   // Check that we have a single incoming value and that it does not
447   // come from the same block as MI - since it would mean that the def
448   // is executed after MI.
449   if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
450     return *Incoming.begin();
451   return nullptr;
452 }
453 
454 MachineInstr *ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
455                                                 unsigned Idx) const {
456   assert(MI->getOperand(Idx).isReg() && "Expected register operand");
457   return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
458 }
459 
460 MachineInstr *ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
461                                                 MachineOperand &MO) const {
462   assert(MO.isReg() && "Expected register operand");
463   return getUniqueReachingMIDef(MI, MO.getReg());
464 }
465 
466 bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
467                                          MCRegister PhysReg) const {
468   MachineBasicBlock *MBB = MI->getParent();
469   LivePhysRegs LiveRegs(*TRI);
470   LiveRegs.addLiveOuts(*MBB);
471 
472   // Yes if the register is live out of the basic block.
473   if (LiveRegs.contains(PhysReg))
474     return true;
475 
476   // Walk backwards through the block to see if the register is live at some
477   // point.
478   for (MachineInstr &Last :
479        instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
480     LiveRegs.stepBackward(Last);
481     if (LiveRegs.contains(PhysReg))
482       return InstIds.lookup(&Last) > InstIds.lookup(MI);
483   }
484   return false;
485 }
486 
487 bool ReachingDefAnalysis::isRegDefinedAfter(MachineInstr *MI,
488                                             MCRegister PhysReg) const {
489   MachineBasicBlock *MBB = MI->getParent();
490   auto Last = MBB->getLastNonDebugInstr();
491   if (Last != MBB->end() &&
492       getReachingDef(MI, PhysReg) != getReachingDef(&*Last, PhysReg))
493     return true;
494 
495   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
496     return Def == getReachingLocalMIDef(MI, PhysReg);
497 
498   return false;
499 }
500 
501 bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr *MI,
502                                                MCRegister PhysReg) const {
503   MachineBasicBlock *MBB = MI->getParent();
504   LivePhysRegs LiveRegs(*TRI);
505   LiveRegs.addLiveOuts(*MBB);
506   if (!LiveRegs.contains(PhysReg))
507     return false;
508 
509   auto Last = MBB->getLastNonDebugInstr();
510   int Def = getReachingDef(MI, PhysReg);
511   if (Last != MBB->end() && getReachingDef(&*Last, PhysReg) != Def)
512     return false;
513 
514   // Finally check that the last instruction doesn't redefine the register.
515   for (auto &MO : Last->operands())
516     if (isValidRegDefOf(MO, PhysReg))
517       return false;
518 
519   return true;
520 }
521 
522 MachineInstr *
523 ReachingDefAnalysis::getLocalLiveOutMIDef(MachineBasicBlock *MBB,
524                                           MCRegister PhysReg) const {
525   LivePhysRegs LiveRegs(*TRI);
526   LiveRegs.addLiveOuts(*MBB);
527   if (!LiveRegs.contains(PhysReg))
528     return nullptr;
529 
530   auto Last = MBB->getLastNonDebugInstr();
531   if (Last == MBB->end())
532     return nullptr;
533 
534   int Def = getReachingDef(&*Last, PhysReg);
535   for (auto &MO : Last->operands())
536     if (isValidRegDefOf(MO, PhysReg))
537       return &*Last;
538 
539   return Def < 0 ? nullptr : getInstFromId(MBB, Def);
540 }
541 
542 static bool mayHaveSideEffects(MachineInstr &MI) {
543   return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
544          MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
545          MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
546 }
547 
548 // Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
549 // not define a register that is used by any instructions, after and including,
550 // 'To'. These instructions also must not redefine any of Froms operands.
551 template<typename Iterator>
552 bool ReachingDefAnalysis::isSafeToMove(MachineInstr *From,
553                                        MachineInstr *To) const {
554   if (From->getParent() != To->getParent() || From == To)
555     return false;
556 
557   SmallSet<int, 2> Defs;
558   // First check that From would compute the same value if moved.
559   for (auto &MO : From->operands()) {
560     if (!isValidReg(MO))
561       continue;
562     if (MO.isDef())
563       Defs.insert(MO.getReg());
564     else if (!hasSameReachingDef(From, To, MO.getReg()))
565       return false;
566   }
567 
568   // Now walk checking that the rest of the instructions will compute the same
569   // value and that we're not overwriting anything. Don't move the instruction
570   // past any memory, control-flow or other ambiguous instructions.
571   for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
572     if (mayHaveSideEffects(*I))
573       return false;
574     for (auto &MO : I->operands())
575       if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
576         return false;
577   }
578   return true;
579 }
580 
581 bool ReachingDefAnalysis::isSafeToMoveForwards(MachineInstr *From,
582                                                MachineInstr *To) const {
583   using Iterator = MachineBasicBlock::iterator;
584   // Walk forwards until we find the instruction.
585   for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
586     if (&*I == To)
587       return isSafeToMove<Iterator>(From, To);
588   return false;
589 }
590 
591 bool ReachingDefAnalysis::isSafeToMoveBackwards(MachineInstr *From,
592                                                 MachineInstr *To) const {
593   using Iterator = MachineBasicBlock::reverse_iterator;
594   // Walk backwards until we find the instruction.
595   for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
596     if (&*I == To)
597       return isSafeToMove<Iterator>(From, To);
598   return false;
599 }
600 
601 bool ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI,
602                                          InstSet &ToRemove) const {
603   SmallPtrSet<MachineInstr*, 1> Ignore;
604   SmallPtrSet<MachineInstr*, 2> Visited;
605   return isSafeToRemove(MI, Visited, ToRemove, Ignore);
606 }
607 
608 bool
609 ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &ToRemove,
610                                     InstSet &Ignore) const {
611   SmallPtrSet<MachineInstr*, 2> Visited;
612   return isSafeToRemove(MI, Visited, ToRemove, Ignore);
613 }
614 
615 bool
616 ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
617                                     InstSet &ToRemove, InstSet &Ignore) const {
618   if (Visited.count(MI) || Ignore.count(MI))
619     return true;
620   else if (mayHaveSideEffects(*MI)) {
621     // Unless told to ignore the instruction, don't remove anything which has
622     // side effects.
623     return false;
624   }
625 
626   Visited.insert(MI);
627   for (auto &MO : MI->operands()) {
628     if (!isValidRegDef(MO))
629       continue;
630 
631     SmallPtrSet<MachineInstr*, 4> Uses;
632     getGlobalUses(MI, MO.getReg(), Uses);
633 
634     for (auto I : Uses) {
635       if (Ignore.count(I) || ToRemove.count(I))
636         continue;
637       if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
638         return false;
639     }
640   }
641   ToRemove.insert(MI);
642   return true;
643 }
644 
645 void ReachingDefAnalysis::collectKilledOperands(MachineInstr *MI,
646                                                 InstSet &Dead) const {
647   Dead.insert(MI);
648   auto IsDead = [this, &Dead](MachineInstr *Def, MCRegister PhysReg) {
649     if (mayHaveSideEffects(*Def))
650       return false;
651 
652     unsigned LiveDefs = 0;
653     for (auto &MO : Def->operands()) {
654       if (!isValidRegDef(MO))
655         continue;
656       if (!MO.isDead())
657         ++LiveDefs;
658     }
659 
660     if (LiveDefs > 1)
661       return false;
662 
663     SmallPtrSet<MachineInstr*, 4> Uses;
664     getGlobalUses(Def, PhysReg, Uses);
665     for (auto *Use : Uses)
666       if (!Dead.count(Use))
667         return false;
668     return true;
669   };
670 
671   for (auto &MO : MI->operands()) {
672     if (!isValidRegUse(MO))
673       continue;
674     if (MachineInstr *Def = getMIOperand(MI, MO))
675       if (IsDead(Def, MO.getReg()))
676         collectKilledOperands(Def, Dead);
677   }
678 }
679 
680 bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI,
681                                            MCRegister PhysReg) const {
682   SmallPtrSet<MachineInstr*, 1> Ignore;
683   return isSafeToDefRegAt(MI, PhysReg, Ignore);
684 }
685 
686 bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI, MCRegister PhysReg,
687                                            InstSet &Ignore) const {
688   // Check for any uses of the register after MI.
689   if (isRegUsedAfter(MI, PhysReg)) {
690     if (auto *Def = getReachingLocalMIDef(MI, PhysReg)) {
691       SmallPtrSet<MachineInstr*, 2> Uses;
692       getGlobalUses(Def, PhysReg, Uses);
693       for (auto *Use : Uses)
694         if (!Ignore.count(Use))
695           return false;
696     } else
697       return false;
698   }
699 
700   MachineBasicBlock *MBB = MI->getParent();
701   // Check for any defs after MI.
702   if (isRegDefinedAfter(MI, PhysReg)) {
703     auto I = MachineBasicBlock::iterator(MI);
704     for (auto E = MBB->end(); I != E; ++I) {
705       if (Ignore.count(&*I))
706         continue;
707       for (auto &MO : I->operands())
708         if (isValidRegDefOf(MO, PhysReg))
709           return false;
710     }
711   }
712   return true;
713 }
714