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