xref: /llvm-project/llvm/lib/CodeGen/ReachingDefAnalysis.cpp (revision 64f2bff12b8ac40c79004ffacf46a5294600d219)
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-deps-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, MCRegister PhysReg,
34                             const TargetRegisterInfo *TRI) {
35   if (!isValidRegUse(MO))
36     return false;
37   return TRI->regsOverlap(MO.getReg(), PhysReg);
38 }
39 
40 static bool isValidRegDef(const MachineOperand &MO) {
41   return isValidReg(MO) && MO.isDef();
42 }
43 
44 static bool isValidRegDefOf(const MachineOperand &MO, MCRegister PhysReg,
45                             const TargetRegisterInfo *TRI) {
46   if (!isValidRegDef(MO))
47     return false;
48   return TRI->regsOverlap(MO.getReg(), PhysReg);
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,
264                                         MCRegister PhysReg) const {
265   assert(InstIds.count(MI) && "Unexpected machine instuction.");
266   int InstId = InstIds.lookup(MI);
267   int DefRes = ReachingDefDefaultVal;
268   unsigned MBBNumber = MI->getParent()->getNumber();
269   assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
270          "Unexpected basic block number.");
271   int LatestDef = ReachingDefDefaultVal;
272   for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
273     for (int Def : MBBReachingDefs.defs(MBBNumber, Unit)) {
274       if (Def >= InstId)
275         break;
276       DefRes = Def;
277     }
278     LatestDef = std::max(LatestDef, DefRes);
279   }
280   return LatestDef;
281 }
282 
283 MachineInstr *
284 ReachingDefAnalysis::getReachingLocalMIDef(MachineInstr *MI,
285                                            MCRegister PhysReg) const {
286   return hasLocalDefBefore(MI, PhysReg)
287     ? getInstFromId(MI->getParent(), getReachingDef(MI, PhysReg))
288     : nullptr;
289 }
290 
291 bool ReachingDefAnalysis::hasSameReachingDef(MachineInstr *A, MachineInstr *B,
292                                              MCRegister PhysReg) const {
293   MachineBasicBlock *ParentA = A->getParent();
294   MachineBasicBlock *ParentB = B->getParent();
295   if (ParentA != ParentB)
296     return false;
297 
298   return getReachingDef(A, PhysReg) == getReachingDef(B, PhysReg);
299 }
300 
301 MachineInstr *ReachingDefAnalysis::getInstFromId(MachineBasicBlock *MBB,
302                                                  int InstId) const {
303   assert(static_cast<size_t>(MBB->getNumber()) <
304              MBBReachingDefs.numBlockIDs() &&
305          "Unexpected basic block number.");
306   assert(InstId < static_cast<int>(MBB->size()) &&
307          "Unexpected instruction id.");
308 
309   if (InstId < 0)
310     return nullptr;
311 
312   for (auto &MI : *MBB) {
313     auto F = InstIds.find(&MI);
314     if (F != InstIds.end() && F->second == InstId)
315       return &MI;
316   }
317 
318   return nullptr;
319 }
320 
321 int ReachingDefAnalysis::getClearance(MachineInstr *MI,
322                                       MCRegister PhysReg) const {
323   assert(InstIds.count(MI) && "Unexpected machine instuction.");
324   return InstIds.lookup(MI) - getReachingDef(MI, PhysReg);
325 }
326 
327 bool ReachingDefAnalysis::hasLocalDefBefore(MachineInstr *MI,
328                                             MCRegister PhysReg) const {
329   return getReachingDef(MI, PhysReg) >= 0;
330 }
331 
332 void ReachingDefAnalysis::getReachingLocalUses(MachineInstr *Def,
333                                                MCRegister PhysReg,
334                                                InstSet &Uses) const {
335   MachineBasicBlock *MBB = Def->getParent();
336   MachineBasicBlock::iterator MI = MachineBasicBlock::iterator(Def);
337   while (++MI != MBB->end()) {
338     if (MI->isDebugInstr())
339       continue;
340 
341     // If/when we find a new reaching def, we know that there's no more uses
342     // of 'Def'.
343     if (getReachingLocalMIDef(&*MI, PhysReg) != Def)
344       return;
345 
346     for (auto &MO : MI->operands()) {
347       if (!isValidRegUseOf(MO, PhysReg, TRI))
348         continue;
349 
350       Uses.insert(&*MI);
351       if (MO.isKill())
352         return;
353     }
354   }
355 }
356 
357 bool ReachingDefAnalysis::getLiveInUses(MachineBasicBlock *MBB,
358                                         MCRegister PhysReg,
359                                         InstSet &Uses) const {
360   for (MachineInstr &MI :
361        instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end())) {
362     for (auto &MO : MI.operands()) {
363       if (!isValidRegUseOf(MO, PhysReg, TRI))
364         continue;
365       if (getReachingDef(&MI, PhysReg) >= 0)
366         return false;
367       Uses.insert(&MI);
368     }
369   }
370   auto Last = MBB->getLastNonDebugInstr();
371   if (Last == MBB->end())
372     return true;
373   return isReachingDefLiveOut(&*Last, PhysReg);
374 }
375 
376 void ReachingDefAnalysis::getGlobalUses(MachineInstr *MI, MCRegister PhysReg,
377                                         InstSet &Uses) const {
378   MachineBasicBlock *MBB = MI->getParent();
379 
380   // Collect the uses that each def touches within the block.
381   getReachingLocalUses(MI, PhysReg, Uses);
382 
383   // Handle live-out values.
384   if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), PhysReg)) {
385     if (LiveOut != MI)
386       return;
387 
388     SmallVector<MachineBasicBlock *, 4> ToVisit(MBB->successors());
389     SmallPtrSet<MachineBasicBlock*, 4>Visited;
390     while (!ToVisit.empty()) {
391       MachineBasicBlock *MBB = ToVisit.pop_back_val();
392       if (Visited.count(MBB) || !MBB->isLiveIn(PhysReg))
393         continue;
394       if (getLiveInUses(MBB, PhysReg, Uses))
395         llvm::append_range(ToVisit, MBB->successors());
396       Visited.insert(MBB);
397     }
398   }
399 }
400 
401 void ReachingDefAnalysis::getGlobalReachingDefs(MachineInstr *MI,
402                                                 MCRegister PhysReg,
403                                                 InstSet &Defs) const {
404   if (auto *Def = getUniqueReachingMIDef(MI, PhysReg)) {
405     Defs.insert(Def);
406     return;
407   }
408 
409   for (auto *MBB : MI->getParent()->predecessors())
410     getLiveOuts(MBB, PhysReg, Defs);
411 }
412 
413 void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock *MBB,
414                                       MCRegister PhysReg, InstSet &Defs) const {
415   SmallPtrSet<MachineBasicBlock*, 2> VisitedBBs;
416   getLiveOuts(MBB, PhysReg, Defs, VisitedBBs);
417 }
418 
419 void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock *MBB,
420                                       MCRegister PhysReg, InstSet &Defs,
421                                       BlockSet &VisitedBBs) const {
422   if (VisitedBBs.count(MBB))
423     return;
424 
425   VisitedBBs.insert(MBB);
426   LiveRegUnits LiveRegs(*TRI);
427   LiveRegs.addLiveOuts(*MBB);
428   if (LiveRegs.available(PhysReg))
429     return;
430 
431   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
432     Defs.insert(Def);
433   else
434     for (auto *Pred : MBB->predecessors())
435       getLiveOuts(Pred, PhysReg, Defs, VisitedBBs);
436 }
437 
438 MachineInstr *
439 ReachingDefAnalysis::getUniqueReachingMIDef(MachineInstr *MI,
440                                             MCRegister PhysReg) const {
441   // If there's a local def before MI, return it.
442   MachineInstr *LocalDef = getReachingLocalMIDef(MI, PhysReg);
443   if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
444     return LocalDef;
445 
446   SmallPtrSet<MachineInstr*, 2> Incoming;
447   MachineBasicBlock *Parent = MI->getParent();
448   for (auto *Pred : Parent->predecessors())
449     getLiveOuts(Pred, PhysReg, Incoming);
450 
451   // Check that we have a single incoming value and that it does not
452   // come from the same block as MI - since it would mean that the def
453   // is executed after MI.
454   if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
455     return *Incoming.begin();
456   return nullptr;
457 }
458 
459 MachineInstr *ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
460                                                 unsigned Idx) const {
461   assert(MI->getOperand(Idx).isReg() && "Expected register operand");
462   return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
463 }
464 
465 MachineInstr *ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
466                                                 MachineOperand &MO) const {
467   assert(MO.isReg() && "Expected register operand");
468   return getUniqueReachingMIDef(MI, MO.getReg());
469 }
470 
471 bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
472                                          MCRegister PhysReg) const {
473   MachineBasicBlock *MBB = MI->getParent();
474   LiveRegUnits LiveRegs(*TRI);
475   LiveRegs.addLiveOuts(*MBB);
476 
477   // Yes if the register is live out of the basic block.
478   if (!LiveRegs.available(PhysReg))
479     return true;
480 
481   // Walk backwards through the block to see if the register is live at some
482   // point.
483   for (MachineInstr &Last :
484        instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
485     LiveRegs.stepBackward(Last);
486     if (!LiveRegs.available(PhysReg))
487       return InstIds.lookup(&Last) > InstIds.lookup(MI);
488   }
489   return false;
490 }
491 
492 bool ReachingDefAnalysis::isRegDefinedAfter(MachineInstr *MI,
493                                             MCRegister PhysReg) const {
494   MachineBasicBlock *MBB = MI->getParent();
495   auto Last = MBB->getLastNonDebugInstr();
496   if (Last != MBB->end() &&
497       getReachingDef(MI, PhysReg) != getReachingDef(&*Last, PhysReg))
498     return true;
499 
500   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
501     return Def == getReachingLocalMIDef(MI, PhysReg);
502 
503   return false;
504 }
505 
506 bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr *MI,
507                                                MCRegister PhysReg) const {
508   MachineBasicBlock *MBB = MI->getParent();
509   LiveRegUnits LiveRegs(*TRI);
510   LiveRegs.addLiveOuts(*MBB);
511   if (LiveRegs.available(PhysReg))
512     return false;
513 
514   auto Last = MBB->getLastNonDebugInstr();
515   int Def = getReachingDef(MI, PhysReg);
516   if (Last != MBB->end() && getReachingDef(&*Last, PhysReg) != Def)
517     return false;
518 
519   // Finally check that the last instruction doesn't redefine the register.
520   for (auto &MO : Last->operands())
521     if (isValidRegDefOf(MO, PhysReg, TRI))
522       return false;
523 
524   return true;
525 }
526 
527 MachineInstr *
528 ReachingDefAnalysis::getLocalLiveOutMIDef(MachineBasicBlock *MBB,
529                                           MCRegister PhysReg) const {
530   LiveRegUnits LiveRegs(*TRI);
531   LiveRegs.addLiveOuts(*MBB);
532   if (LiveRegs.available(PhysReg))
533     return nullptr;
534 
535   auto Last = MBB->getLastNonDebugInstr();
536   if (Last == MBB->end())
537     return nullptr;
538 
539   int Def = getReachingDef(&*Last, PhysReg);
540   for (auto &MO : Last->operands())
541     if (isValidRegDefOf(MO, PhysReg, TRI))
542       return &*Last;
543 
544   return Def < 0 ? nullptr : getInstFromId(MBB, Def);
545 }
546 
547 static bool mayHaveSideEffects(MachineInstr &MI) {
548   return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
549          MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
550          MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
551 }
552 
553 // Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
554 // not define a register that is used by any instructions, after and including,
555 // 'To'. These instructions also must not redefine any of Froms operands.
556 template<typename Iterator>
557 bool ReachingDefAnalysis::isSafeToMove(MachineInstr *From,
558                                        MachineInstr *To) const {
559   if (From->getParent() != To->getParent() || From == To)
560     return false;
561 
562   SmallSet<int, 2> Defs;
563   // First check that From would compute the same value if moved.
564   for (auto &MO : From->operands()) {
565     if (!isValidReg(MO))
566       continue;
567     if (MO.isDef())
568       Defs.insert(MO.getReg());
569     else if (!hasSameReachingDef(From, To, MO.getReg()))
570       return false;
571   }
572 
573   // Now walk checking that the rest of the instructions will compute the same
574   // value and that we're not overwriting anything. Don't move the instruction
575   // past any memory, control-flow or other ambiguous instructions.
576   for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
577     if (mayHaveSideEffects(*I))
578       return false;
579     for (auto &MO : I->operands())
580       if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
581         return false;
582   }
583   return true;
584 }
585 
586 bool ReachingDefAnalysis::isSafeToMoveForwards(MachineInstr *From,
587                                                MachineInstr *To) const {
588   using Iterator = MachineBasicBlock::iterator;
589   // Walk forwards until we find the instruction.
590   for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
591     if (&*I == To)
592       return isSafeToMove<Iterator>(From, To);
593   return false;
594 }
595 
596 bool ReachingDefAnalysis::isSafeToMoveBackwards(MachineInstr *From,
597                                                 MachineInstr *To) const {
598   using Iterator = MachineBasicBlock::reverse_iterator;
599   // Walk backwards until we find the instruction.
600   for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
601     if (&*I == To)
602       return isSafeToMove<Iterator>(From, To);
603   return false;
604 }
605 
606 bool ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI,
607                                          InstSet &ToRemove) const {
608   SmallPtrSet<MachineInstr*, 1> Ignore;
609   SmallPtrSet<MachineInstr*, 2> Visited;
610   return isSafeToRemove(MI, Visited, ToRemove, Ignore);
611 }
612 
613 bool
614 ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &ToRemove,
615                                     InstSet &Ignore) const {
616   SmallPtrSet<MachineInstr*, 2> Visited;
617   return isSafeToRemove(MI, Visited, ToRemove, Ignore);
618 }
619 
620 bool
621 ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
622                                     InstSet &ToRemove, InstSet &Ignore) const {
623   if (Visited.count(MI) || Ignore.count(MI))
624     return true;
625   else if (mayHaveSideEffects(*MI)) {
626     // Unless told to ignore the instruction, don't remove anything which has
627     // side effects.
628     return false;
629   }
630 
631   Visited.insert(MI);
632   for (auto &MO : MI->operands()) {
633     if (!isValidRegDef(MO))
634       continue;
635 
636     SmallPtrSet<MachineInstr*, 4> Uses;
637     getGlobalUses(MI, MO.getReg(), Uses);
638 
639     for (auto *I : Uses) {
640       if (Ignore.count(I) || ToRemove.count(I))
641         continue;
642       if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
643         return false;
644     }
645   }
646   ToRemove.insert(MI);
647   return true;
648 }
649 
650 void ReachingDefAnalysis::collectKilledOperands(MachineInstr *MI,
651                                                 InstSet &Dead) const {
652   Dead.insert(MI);
653   auto IsDead = [this, &Dead](MachineInstr *Def, MCRegister PhysReg) {
654     if (mayHaveSideEffects(*Def))
655       return false;
656 
657     unsigned LiveDefs = 0;
658     for (auto &MO : Def->operands()) {
659       if (!isValidRegDef(MO))
660         continue;
661       if (!MO.isDead())
662         ++LiveDefs;
663     }
664 
665     if (LiveDefs > 1)
666       return false;
667 
668     SmallPtrSet<MachineInstr*, 4> Uses;
669     getGlobalUses(Def, PhysReg, Uses);
670     return llvm::set_is_subset(Uses, Dead);
671   };
672 
673   for (auto &MO : MI->operands()) {
674     if (!isValidRegUse(MO))
675       continue;
676     if (MachineInstr *Def = getMIOperand(MI, MO))
677       if (IsDead(Def, MO.getReg()))
678         collectKilledOperands(Def, Dead);
679   }
680 }
681 
682 bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI,
683                                            MCRegister PhysReg) const {
684   SmallPtrSet<MachineInstr*, 1> Ignore;
685   return isSafeToDefRegAt(MI, PhysReg, Ignore);
686 }
687 
688 bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI, MCRegister PhysReg,
689                                            InstSet &Ignore) const {
690   // Check for any uses of the register after MI.
691   if (isRegUsedAfter(MI, PhysReg)) {
692     if (auto *Def = getReachingLocalMIDef(MI, PhysReg)) {
693       SmallPtrSet<MachineInstr*, 2> Uses;
694       getGlobalUses(Def, PhysReg, Uses);
695       if (!llvm::set_is_subset(Uses, Ignore))
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, TRI))
710           return false;
711     }
712   }
713   return true;
714 }
715