a7dc1b328c1b34257daffe5a93bb14b20ed023e0
[oota-llvm.git] / lib / CodeGen / MachineBasicBlock.cpp
1 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Collect the sequence of machine instructions for a basic block.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/MachineBasicBlock.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/LiveVariables.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SlotIndexes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/LeakDetector.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetSubtargetInfo.h"
36 #include <algorithm>
37 using namespace llvm;
38
39 #define DEBUG_TYPE "codegen"
40
41 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
42   : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
43     AddressTaken(false), CachedMCSymbol(nullptr) {
44   Insts.Parent = this;
45 }
46
47 MachineBasicBlock::~MachineBasicBlock() {
48   LeakDetector::removeGarbageObject(this);
49 }
50
51 /// getSymbol - Return the MCSymbol for this basic block.
52 ///
53 MCSymbol *MachineBasicBlock::getSymbol() const {
54   if (!CachedMCSymbol) {
55     const MachineFunction *MF = getParent();
56     MCContext &Ctx = MF->getContext();
57     const char *Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
58     CachedMCSymbol = Ctx.GetOrCreateSymbol(Twine(Prefix) + "BB" +
59                                            Twine(MF->getFunctionNumber()) +
60                                            "_" + Twine(getNumber()));
61   }
62
63   return CachedMCSymbol;
64 }
65
66
67 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
68   MBB.print(OS);
69   return OS;
70 }
71
72 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
73 /// parent pointer of the MBB, the MBB numbering, and any instructions in the
74 /// MBB to be on the right operand list for registers.
75 ///
76 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
77 /// gets the next available unique MBB number. If it is removed from a
78 /// MachineFunction, it goes back to being #-1.
79 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
80   MachineFunction &MF = *N->getParent();
81   N->Number = MF.addToMBBNumbering(N);
82
83   // Make sure the instructions have their operands in the reginfo lists.
84   MachineRegisterInfo &RegInfo = MF.getRegInfo();
85   for (MachineBasicBlock::instr_iterator
86          I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
87     I->AddRegOperandsToUseLists(RegInfo);
88
89   LeakDetector::removeGarbageObject(N);
90 }
91
92 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
93   N->getParent()->removeFromMBBNumbering(N->Number);
94   N->Number = -1;
95   LeakDetector::addGarbageObject(N);
96 }
97
98
99 /// addNodeToList (MI) - When we add an instruction to a basic block
100 /// list, we update its parent pointer and add its operands from reg use/def
101 /// lists if appropriate.
102 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
103   assert(!N->getParent() && "machine instruction already in a basic block");
104   N->setParent(Parent);
105
106   // Add the instruction's register operands to their corresponding
107   // use/def lists.
108   MachineFunction *MF = Parent->getParent();
109   N->AddRegOperandsToUseLists(MF->getRegInfo());
110 }
111
112 /// removeNodeFromList (MI) - When we remove an instruction from a basic block
113 /// list, we update its parent pointer and remove its operands from reg use/def
114 /// lists if appropriate.
115 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
116   assert(N->getParent() && "machine instruction not in a basic block");
117
118   // Remove from the use/def lists.
119   if (MachineFunction *MF = N->getParent()->getParent())
120     N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
121
122   N->setParent(nullptr);
123 }
124
125 /// transferNodesFromList (MI) - When moving a range of instructions from one
126 /// MBB list to another, we need to update the parent pointers and the use/def
127 /// lists.
128 void ilist_traits<MachineInstr>::
129 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
130                       ilist_iterator<MachineInstr> first,
131                       ilist_iterator<MachineInstr> last) {
132   assert(Parent->getParent() == fromList.Parent->getParent() &&
133         "MachineInstr parent mismatch!");
134
135   // Splice within the same MBB -> no change.
136   if (Parent == fromList.Parent) return;
137
138   // If splicing between two blocks within the same function, just update the
139   // parent pointers.
140   for (; first != last; ++first)
141     first->setParent(Parent);
142 }
143
144 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
145   assert(!MI->getParent() && "MI is still in a block!");
146   Parent->getParent()->DeleteMachineInstr(MI);
147 }
148
149 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
150   instr_iterator I = instr_begin(), E = instr_end();
151   while (I != E && I->isPHI())
152     ++I;
153   assert((I == E || !I->isInsideBundle()) &&
154          "First non-phi MI cannot be inside a bundle!");
155   return I;
156 }
157
158 MachineBasicBlock::iterator
159 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
160   iterator E = end();
161   while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue()))
162     ++I;
163   // FIXME: This needs to change if we wish to bundle labels / dbg_values
164   // inside the bundle.
165   assert((I == E || !I->isInsideBundle()) &&
166          "First non-phi / non-label instruction is inside a bundle!");
167   return I;
168 }
169
170 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
171   iterator B = begin(), E = end(), I = E;
172   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
173     ; /*noop */
174   while (I != E && !I->isTerminator())
175     ++I;
176   return I;
177 }
178
179 MachineBasicBlock::const_iterator
180 MachineBasicBlock::getFirstTerminator() const {
181   const_iterator B = begin(), E = end(), I = E;
182   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
183     ; /*noop */
184   while (I != E && !I->isTerminator())
185     ++I;
186   return I;
187 }
188
189 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
190   instr_iterator B = instr_begin(), E = instr_end(), I = E;
191   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
192     ; /*noop */
193   while (I != E && !I->isTerminator())
194     ++I;
195   return I;
196 }
197
198 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
199   // Skip over end-of-block dbg_value instructions.
200   instr_iterator B = instr_begin(), I = instr_end();
201   while (I != B) {
202     --I;
203     // Return instruction that starts a bundle.
204     if (I->isDebugValue() || I->isInsideBundle())
205       continue;
206     return I;
207   }
208   // The block is all debug values.
209   return end();
210 }
211
212 MachineBasicBlock::const_iterator
213 MachineBasicBlock::getLastNonDebugInstr() const {
214   // Skip over end-of-block dbg_value instructions.
215   const_instr_iterator B = instr_begin(), I = instr_end();
216   while (I != B) {
217     --I;
218     // Return instruction that starts a bundle.
219     if (I->isDebugValue() || I->isInsideBundle())
220       continue;
221     return I;
222   }
223   // The block is all debug values.
224   return end();
225 }
226
227 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
228   // A block with a landing pad successor only has one other successor.
229   if (succ_size() > 2)
230     return nullptr;
231   for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
232     if ((*I)->isLandingPad())
233       return *I;
234   return nullptr;
235 }
236
237 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
238 void MachineBasicBlock::dump() const {
239   print(dbgs());
240 }
241 #endif
242
243 StringRef MachineBasicBlock::getName() const {
244   if (const BasicBlock *LBB = getBasicBlock())
245     return LBB->getName();
246   else
247     return "(null)";
248 }
249
250 /// Return a hopefully unique identifier for this block.
251 std::string MachineBasicBlock::getFullName() const {
252   std::string Name;
253   if (getParent())
254     Name = (getParent()->getName() + ":").str();
255   if (getBasicBlock())
256     Name += getBasicBlock()->getName();
257   else
258     Name += (Twine("BB") + Twine(getNumber())).str();
259   return Name;
260 }
261
262 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
263   const MachineFunction *MF = getParent();
264   if (!MF) {
265     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
266        << " is null\n";
267     return;
268   }
269
270   if (Indexes)
271     OS << Indexes->getMBBStartIdx(this) << '\t';
272
273   OS << "BB#" << getNumber() << ": ";
274
275   const char *Comma = "";
276   if (const BasicBlock *LBB = getBasicBlock()) {
277     OS << Comma << "derived from LLVM BB ";
278     LBB->printAsOperand(OS, /*PrintType=*/false);
279     Comma = ", ";
280   }
281   if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
282   if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
283   if (Alignment)
284     OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
285        << " bytes)";
286
287   OS << '\n';
288
289   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
290   if (!livein_empty()) {
291     if (Indexes) OS << '\t';
292     OS << "    Live Ins:";
293     for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
294       OS << ' ' << PrintReg(*I, TRI);
295     OS << '\n';
296   }
297   // Print the preds of this block according to the CFG.
298   if (!pred_empty()) {
299     if (Indexes) OS << '\t';
300     OS << "    Predecessors according to CFG:";
301     for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
302       OS << " BB#" << (*PI)->getNumber();
303     OS << '\n';
304   }
305
306   for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
307     if (Indexes) {
308       if (Indexes->hasIndex(I))
309         OS << Indexes->getInstructionIndex(I);
310       OS << '\t';
311     }
312     OS << '\t';
313     if (I->isInsideBundle())
314       OS << "  * ";
315     I->print(OS, &getParent()->getTarget());
316   }
317
318   // Print the successors of this block according to the CFG.
319   if (!succ_empty()) {
320     if (Indexes) OS << '\t';
321     OS << "    Successors according to CFG:";
322     for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
323       OS << " BB#" << (*SI)->getNumber();
324       if (!Weights.empty())
325         OS << '(' << *getWeightIterator(SI) << ')';
326     }
327     OS << '\n';
328   }
329 }
330
331 void MachineBasicBlock::printAsOperand(raw_ostream &OS, bool /*PrintType*/) const {
332   OS << "BB#" << getNumber();
333 }
334
335 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
336   std::vector<unsigned>::iterator I =
337     std::find(LiveIns.begin(), LiveIns.end(), Reg);
338   if (I != LiveIns.end())
339     LiveIns.erase(I);
340 }
341
342 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
343   livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
344   return I != livein_end();
345 }
346
347 unsigned
348 MachineBasicBlock::addLiveIn(unsigned PhysReg, const TargetRegisterClass *RC) {
349   assert(getParent() && "MBB must be inserted in function");
350   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
351   assert(RC && "Register class is required");
352   assert((isLandingPad() || this == &getParent()->front()) &&
353          "Only the entry block and landing pads can have physreg live ins");
354
355   bool LiveIn = isLiveIn(PhysReg);
356   iterator I = SkipPHIsAndLabels(begin()), E = end();
357   MachineRegisterInfo &MRI = getParent()->getRegInfo();
358   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
359
360   // Look for an existing copy.
361   if (LiveIn)
362     for (;I != E && I->isCopy(); ++I)
363       if (I->getOperand(1).getReg() == PhysReg) {
364         unsigned VirtReg = I->getOperand(0).getReg();
365         if (!MRI.constrainRegClass(VirtReg, RC))
366           llvm_unreachable("Incompatible live-in register class.");
367         return VirtReg;
368       }
369
370   // No luck, create a virtual register.
371   unsigned VirtReg = MRI.createVirtualRegister(RC);
372   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
373     .addReg(PhysReg, RegState::Kill);
374   if (!LiveIn)
375     addLiveIn(PhysReg);
376   return VirtReg;
377 }
378
379 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
380   getParent()->splice(NewAfter, this);
381 }
382
383 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
384   MachineFunction::iterator BBI = NewBefore;
385   getParent()->splice(++BBI, this);
386 }
387
388 void MachineBasicBlock::updateTerminator() {
389   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
390   // A block with no successors has no concerns with fall-through edges.
391   if (this->succ_empty()) return;
392
393   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
394   SmallVector<MachineOperand, 4> Cond;
395   DebugLoc dl;  // FIXME: this is nowhere
396   bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
397   (void) B;
398   assert(!B && "UpdateTerminators requires analyzable predecessors!");
399   if (Cond.empty()) {
400     if (TBB) {
401       // The block has an unconditional branch. If its successor is now
402       // its layout successor, delete the branch.
403       if (isLayoutSuccessor(TBB))
404         TII->RemoveBranch(*this);
405     } else {
406       // The block has an unconditional fallthrough. If its successor is not
407       // its layout successor, insert a branch. First we have to locate the
408       // only non-landing-pad successor, as that is the fallthrough block.
409       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
410         if ((*SI)->isLandingPad())
411           continue;
412         assert(!TBB && "Found more than one non-landing-pad successor!");
413         TBB = *SI;
414       }
415
416       // If there is no non-landing-pad successor, the block has no
417       // fall-through edges to be concerned with.
418       if (!TBB)
419         return;
420
421       // Finally update the unconditional successor to be reached via a branch
422       // if it would not be reached by fallthrough.
423       if (!isLayoutSuccessor(TBB))
424         TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
425     }
426   } else {
427     if (FBB) {
428       // The block has a non-fallthrough conditional branch. If one of its
429       // successors is its layout successor, rewrite it to a fallthrough
430       // conditional branch.
431       if (isLayoutSuccessor(TBB)) {
432         if (TII->ReverseBranchCondition(Cond))
433           return;
434         TII->RemoveBranch(*this);
435         TII->InsertBranch(*this, FBB, nullptr, Cond, dl);
436       } else if (isLayoutSuccessor(FBB)) {
437         TII->RemoveBranch(*this);
438         TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
439       }
440     } else {
441       // Walk through the successors and find the successor which is not
442       // a landing pad and is not the conditional branch destination (in TBB)
443       // as the fallthrough successor.
444       MachineBasicBlock *FallthroughBB = nullptr;
445       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
446         if ((*SI)->isLandingPad() || *SI == TBB)
447           continue;
448         assert(!FallthroughBB && "Found more than one fallthrough successor.");
449         FallthroughBB = *SI;
450       }
451       if (!FallthroughBB && canFallThrough()) {
452         // We fallthrough to the same basic block as the conditional jump
453         // targets. Remove the conditional jump, leaving unconditional
454         // fallthrough.
455         // FIXME: This does not seem like a reasonable pattern to support, but it
456         // has been seen in the wild coming out of degenerate ARM test cases.
457         TII->RemoveBranch(*this);
458
459         // Finally update the unconditional successor to be reached via a branch
460         // if it would not be reached by fallthrough.
461         if (!isLayoutSuccessor(TBB))
462           TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
463         return;
464       }
465
466       // The block has a fallthrough conditional branch.
467       if (isLayoutSuccessor(TBB)) {
468         if (TII->ReverseBranchCondition(Cond)) {
469           // We can't reverse the condition, add an unconditional branch.
470           Cond.clear();
471           TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
472           return;
473         }
474         TII->RemoveBranch(*this);
475         TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
476       } else if (!isLayoutSuccessor(FallthroughBB)) {
477         TII->RemoveBranch(*this);
478         TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
479       }
480     }
481   }
482 }
483
484 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
485
486   // If we see non-zero value for the first time it means we actually use Weight
487   // list, so we fill all Weights with 0's.
488   if (weight != 0 && Weights.empty())
489     Weights.resize(Successors.size());
490
491   if (weight != 0 || !Weights.empty())
492     Weights.push_back(weight);
493
494    Successors.push_back(succ);
495    succ->addPredecessor(this);
496  }
497
498 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
499   succ->removePredecessor(this);
500   succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
501   assert(I != Successors.end() && "Not a current successor!");
502
503   // If Weight list is empty it means we don't use it (disabled optimization).
504   if (!Weights.empty()) {
505     weight_iterator WI = getWeightIterator(I);
506     Weights.erase(WI);
507   }
508
509   Successors.erase(I);
510 }
511
512 MachineBasicBlock::succ_iterator
513 MachineBasicBlock::removeSuccessor(succ_iterator I) {
514   assert(I != Successors.end() && "Not a current successor!");
515
516   // If Weight list is empty it means we don't use it (disabled optimization).
517   if (!Weights.empty()) {
518     weight_iterator WI = getWeightIterator(I);
519     Weights.erase(WI);
520   }
521
522   (*I)->removePredecessor(this);
523   return Successors.erase(I);
524 }
525
526 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
527                                          MachineBasicBlock *New) {
528   if (Old == New)
529     return;
530
531   succ_iterator E = succ_end();
532   succ_iterator NewI = E;
533   succ_iterator OldI = E;
534   for (succ_iterator I = succ_begin(); I != E; ++I) {
535     if (*I == Old) {
536       OldI = I;
537       if (NewI != E)
538         break;
539     }
540     if (*I == New) {
541       NewI = I;
542       if (OldI != E)
543         break;
544     }
545   }
546   assert(OldI != E && "Old is not a successor of this block");
547   Old->removePredecessor(this);
548
549   // If New isn't already a successor, let it take Old's place.
550   if (NewI == E) {
551     New->addPredecessor(this);
552     *OldI = New;
553     return;
554   }
555
556   // New is already a successor.
557   // Update its weight instead of adding a duplicate edge.
558   if (!Weights.empty()) {
559     weight_iterator OldWI = getWeightIterator(OldI);
560     *getWeightIterator(NewI) += *OldWI;
561     Weights.erase(OldWI);
562   }
563   Successors.erase(OldI);
564 }
565
566 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
567   Predecessors.push_back(pred);
568 }
569
570 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
571   pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
572   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
573   Predecessors.erase(I);
574 }
575
576 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
577   if (this == fromMBB)
578     return;
579
580   while (!fromMBB->succ_empty()) {
581     MachineBasicBlock *Succ = *fromMBB->succ_begin();
582     uint32_t Weight = 0;
583
584     // If Weight list is empty it means we don't use it (disabled optimization).
585     if (!fromMBB->Weights.empty())
586       Weight = *fromMBB->Weights.begin();
587
588     addSuccessor(Succ, Weight);
589     fromMBB->removeSuccessor(Succ);
590   }
591 }
592
593 void
594 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
595   if (this == fromMBB)
596     return;
597
598   while (!fromMBB->succ_empty()) {
599     MachineBasicBlock *Succ = *fromMBB->succ_begin();
600     uint32_t Weight = 0;
601     if (!fromMBB->Weights.empty())
602       Weight = *fromMBB->Weights.begin();
603     addSuccessor(Succ, Weight);
604     fromMBB->removeSuccessor(Succ);
605
606     // Fix up any PHI nodes in the successor.
607     for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
608            ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
609       for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
610         MachineOperand &MO = MI->getOperand(i);
611         if (MO.getMBB() == fromMBB)
612           MO.setMBB(this);
613       }
614   }
615 }
616
617 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
618   return std::find(pred_begin(), pred_end(), MBB) != pred_end();
619 }
620
621 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
622   return std::find(succ_begin(), succ_end(), MBB) != succ_end();
623 }
624
625 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
626   MachineFunction::const_iterator I(this);
627   return std::next(I) == MachineFunction::const_iterator(MBB);
628 }
629
630 bool MachineBasicBlock::canFallThrough() {
631   MachineFunction::iterator Fallthrough = this;
632   ++Fallthrough;
633   // If FallthroughBlock is off the end of the function, it can't fall through.
634   if (Fallthrough == getParent()->end())
635     return false;
636
637   // If FallthroughBlock isn't a successor, no fallthrough is possible.
638   if (!isSuccessor(Fallthrough))
639     return false;
640
641   // Analyze the branches, if any, at the end of the block.
642   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
643   SmallVector<MachineOperand, 4> Cond;
644   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
645   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
646     // If we couldn't analyze the branch, examine the last instruction.
647     // If the block doesn't end in a known control barrier, assume fallthrough
648     // is possible. The isPredicated check is needed because this code can be
649     // called during IfConversion, where an instruction which is normally a
650     // Barrier is predicated and thus no longer an actual control barrier.
651     return empty() || !back().isBarrier() || TII->isPredicated(&back());
652   }
653
654   // If there is no branch, control always falls through.
655   if (!TBB) return true;
656
657   // If there is some explicit branch to the fallthrough block, it can obviously
658   // reach, even though the branch should get folded to fall through implicitly.
659   if (MachineFunction::iterator(TBB) == Fallthrough ||
660       MachineFunction::iterator(FBB) == Fallthrough)
661     return true;
662
663   // If it's an unconditional branch to some block not the fall through, it
664   // doesn't fall through.
665   if (Cond.empty()) return false;
666
667   // Otherwise, if it is conditional and has no explicit false block, it falls
668   // through.
669   return FBB == nullptr;
670 }
671
672 MachineBasicBlock *
673 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
674   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
675   // it in this generic function.
676   if (Succ->isLandingPad())
677     return nullptr;
678
679   MachineFunction *MF = getParent();
680   DebugLoc dl;  // FIXME: this is nowhere
681
682   // Performance might be harmed on HW that implements branching using exec mask
683   // where both sides of the branches are always executed.
684   if (MF->getTarget().requiresStructuredCFG())
685     return nullptr;
686
687   // We may need to update this's terminator, but we can't do that if
688   // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
689   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
690   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
691   SmallVector<MachineOperand, 4> Cond;
692   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
693     return nullptr;
694
695   // Avoid bugpoint weirdness: A block may end with a conditional branch but
696   // jumps to the same MBB is either case. We have duplicate CFG edges in that
697   // case that we can't handle. Since this never happens in properly optimized
698   // code, just skip those edges.
699   if (TBB && TBB == FBB) {
700     DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
701                  << getNumber() << '\n');
702     return nullptr;
703   }
704
705   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
706   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
707   DEBUG(dbgs() << "Splitting critical edge:"
708         " BB#" << getNumber()
709         << " -- BB#" << NMBB->getNumber()
710         << " -- BB#" << Succ->getNumber() << '\n');
711
712   LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
713   SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
714   if (LIS)
715     LIS->insertMBBInMaps(NMBB);
716   else if (Indexes)
717     Indexes->insertMBBInMaps(NMBB);
718
719   // On some targets like Mips, branches may kill virtual registers. Make sure
720   // that LiveVariables is properly updated after updateTerminator replaces the
721   // terminators.
722   LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
723
724   // Collect a list of virtual registers killed by the terminators.
725   SmallVector<unsigned, 4> KilledRegs;
726   if (LV)
727     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
728          I != E; ++I) {
729       MachineInstr *MI = I;
730       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
731            OE = MI->operands_end(); OI != OE; ++OI) {
732         if (!OI->isReg() || OI->getReg() == 0 ||
733             !OI->isUse() || !OI->isKill() || OI->isUndef())
734           continue;
735         unsigned Reg = OI->getReg();
736         if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
737             LV->getVarInfo(Reg).removeKill(MI)) {
738           KilledRegs.push_back(Reg);
739           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
740           OI->setIsKill(false);
741         }
742       }
743     }
744
745   SmallVector<unsigned, 4> UsedRegs;
746   if (LIS) {
747     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
748          I != E; ++I) {
749       MachineInstr *MI = I;
750
751       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
752            OE = MI->operands_end(); OI != OE; ++OI) {
753         if (!OI->isReg() || OI->getReg() == 0)
754           continue;
755
756         unsigned Reg = OI->getReg();
757         if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
758           UsedRegs.push_back(Reg);
759       }
760     }
761   }
762
763   ReplaceUsesOfBlockWith(Succ, NMBB);
764
765   // If updateTerminator() removes instructions, we need to remove them from
766   // SlotIndexes.
767   SmallVector<MachineInstr*, 4> Terminators;
768   if (Indexes) {
769     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
770          I != E; ++I)
771       Terminators.push_back(I);
772   }
773
774   updateTerminator();
775
776   if (Indexes) {
777     SmallVector<MachineInstr*, 4> NewTerminators;
778     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
779          I != E; ++I)
780       NewTerminators.push_back(I);
781
782     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
783         E = Terminators.end(); I != E; ++I) {
784       if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
785           NewTerminators.end())
786        Indexes->removeMachineInstrFromMaps(*I);
787     }
788   }
789
790   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
791   NMBB->addSuccessor(Succ);
792   if (!NMBB->isLayoutSuccessor(Succ)) {
793     Cond.clear();
794     MF->getSubtarget().getInstrInfo()->InsertBranch(*NMBB, Succ, nullptr, Cond,
795                                                     dl);
796
797     if (Indexes) {
798       for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
799            I != E; ++I) {
800         // Some instructions may have been moved to NMBB by updateTerminator(),
801         // so we first remove any instruction that already has an index.
802         if (Indexes->hasIndex(I))
803           Indexes->removeMachineInstrFromMaps(I);
804         Indexes->insertMachineInstrInMaps(I);
805       }
806     }
807   }
808
809   // Fix PHI nodes in Succ so they refer to NMBB instead of this
810   for (MachineBasicBlock::instr_iterator
811          i = Succ->instr_begin(),e = Succ->instr_end();
812        i != e && i->isPHI(); ++i)
813     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
814       if (i->getOperand(ni+1).getMBB() == this)
815         i->getOperand(ni+1).setMBB(NMBB);
816
817   // Inherit live-ins from the successor
818   for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
819          E = Succ->livein_end(); I != E; ++I)
820     NMBB->addLiveIn(*I);
821
822   // Update LiveVariables.
823   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
824   if (LV) {
825     // Restore kills of virtual registers that were killed by the terminators.
826     while (!KilledRegs.empty()) {
827       unsigned Reg = KilledRegs.pop_back_val();
828       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
829         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
830           continue;
831         if (TargetRegisterInfo::isVirtualRegister(Reg))
832           LV->getVarInfo(Reg).Kills.push_back(I);
833         DEBUG(dbgs() << "Restored terminator kill: " << *I);
834         break;
835       }
836     }
837     // Update relevant live-through information.
838     LV->addNewBlock(NMBB, this, Succ);
839   }
840
841   if (LIS) {
842     // After splitting the edge and updating SlotIndexes, live intervals may be
843     // in one of two situations, depending on whether this block was the last in
844     // the function. If the original block was the last in the function, all live
845     // intervals will end prior to the beginning of the new split block. If the
846     // original block was not at the end of the function, all live intervals will
847     // extend to the end of the new split block.
848
849     bool isLastMBB =
850       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
851
852     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
853     SlotIndex PrevIndex = StartIndex.getPrevSlot();
854     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
855
856     // Find the registers used from NMBB in PHIs in Succ.
857     SmallSet<unsigned, 8> PHISrcRegs;
858     for (MachineBasicBlock::instr_iterator
859          I = Succ->instr_begin(), E = Succ->instr_end();
860          I != E && I->isPHI(); ++I) {
861       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
862         if (I->getOperand(ni+1).getMBB() == NMBB) {
863           MachineOperand &MO = I->getOperand(ni);
864           unsigned Reg = MO.getReg();
865           PHISrcRegs.insert(Reg);
866           if (MO.isUndef())
867             continue;
868
869           LiveInterval &LI = LIS->getInterval(Reg);
870           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
871           assert(VNI && "PHI sources should be live out of their predecessors.");
872           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
873         }
874       }
875     }
876
877     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
878     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
879       unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
880       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
881         continue;
882
883       LiveInterval &LI = LIS->getInterval(Reg);
884       if (!LI.liveAt(PrevIndex))
885         continue;
886
887       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
888       if (isLiveOut && isLastMBB) {
889         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
890         assert(VNI && "LiveInterval should have VNInfo where it is live.");
891         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
892       } else if (!isLiveOut && !isLastMBB) {
893         LI.removeSegment(StartIndex, EndIndex);
894       }
895     }
896
897     // Update all intervals for registers whose uses may have been modified by
898     // updateTerminator().
899     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
900   }
901
902   if (MachineDominatorTree *MDT =
903       P->getAnalysisIfAvailable<MachineDominatorTree>())
904     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
905
906   if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
907     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
908       // If one or the other blocks were not in a loop, the new block is not
909       // either, and thus LI doesn't need to be updated.
910       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
911         if (TIL == DestLoop) {
912           // Both in the same loop, the NMBB joins loop.
913           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
914         } else if (TIL->contains(DestLoop)) {
915           // Edge from an outer loop to an inner loop.  Add to the outer loop.
916           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
917         } else if (DestLoop->contains(TIL)) {
918           // Edge from an inner loop to an outer loop.  Add to the outer loop.
919           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
920         } else {
921           // Edge from two loops with no containment relation.  Because these
922           // are natural loops, we know that the destination block must be the
923           // header of its loop (adding a branch into a loop elsewhere would
924           // create an irreducible loop).
925           assert(DestLoop->getHeader() == Succ &&
926                  "Should not create irreducible loops!");
927           if (MachineLoop *P = DestLoop->getParentLoop())
928             P->addBasicBlockToLoop(NMBB, MLI->getBase());
929         }
930       }
931     }
932
933   return NMBB;
934 }
935
936 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
937 /// neighboring instructions so the bundle won't be broken by removing MI.
938 static void unbundleSingleMI(MachineInstr *MI) {
939   // Removing the first instruction in a bundle.
940   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
941     MI->unbundleFromSucc();
942   // Removing the last instruction in a bundle.
943   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
944     MI->unbundleFromPred();
945   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
946   // are already fine.
947 }
948
949 MachineBasicBlock::instr_iterator
950 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
951   unbundleSingleMI(I);
952   return Insts.erase(I);
953 }
954
955 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
956   unbundleSingleMI(MI);
957   MI->clearFlag(MachineInstr::BundledPred);
958   MI->clearFlag(MachineInstr::BundledSucc);
959   return Insts.remove(MI);
960 }
961
962 MachineBasicBlock::instr_iterator
963 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
964   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
965          "Cannot insert instruction with bundle flags");
966   // Set the bundle flags when inserting inside a bundle.
967   if (I != instr_end() && I->isBundledWithPred()) {
968     MI->setFlag(MachineInstr::BundledPred);
969     MI->setFlag(MachineInstr::BundledSucc);
970   }
971   return Insts.insert(I, MI);
972 }
973
974 /// removeFromParent - This method unlinks 'this' from the containing function,
975 /// and returns it, but does not delete it.
976 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
977   assert(getParent() && "Not embedded in a function!");
978   getParent()->remove(this);
979   return this;
980 }
981
982
983 /// eraseFromParent - This method unlinks 'this' from the containing function,
984 /// and deletes it.
985 void MachineBasicBlock::eraseFromParent() {
986   assert(getParent() && "Not embedded in a function!");
987   getParent()->erase(this);
988 }
989
990
991 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
992 /// 'Old', change the code and CFG so that it branches to 'New' instead.
993 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
994                                                MachineBasicBlock *New) {
995   assert(Old != New && "Cannot replace self with self!");
996
997   MachineBasicBlock::instr_iterator I = instr_end();
998   while (I != instr_begin()) {
999     --I;
1000     if (!I->isTerminator()) break;
1001
1002     // Scan the operands of this machine instruction, replacing any uses of Old
1003     // with New.
1004     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1005       if (I->getOperand(i).isMBB() &&
1006           I->getOperand(i).getMBB() == Old)
1007         I->getOperand(i).setMBB(New);
1008   }
1009
1010   // Update the successor information.
1011   replaceSuccessor(Old, New);
1012 }
1013
1014 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
1015 /// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
1016 /// DestB, remove any other MBB successors from the CFG.  DestA and DestB can be
1017 /// null.
1018 ///
1019 /// Besides DestA and DestB, retain other edges leading to LandingPads
1020 /// (currently there can be only one; we don't check or require that here).
1021 /// Note it is possible that DestA and/or DestB are LandingPads.
1022 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1023                                              MachineBasicBlock *DestB,
1024                                              bool isCond) {
1025   // The values of DestA and DestB frequently come from a call to the
1026   // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1027   // values from there.
1028   //
1029   // 1. If both DestA and DestB are null, then the block ends with no branches
1030   //    (it falls through to its successor).
1031   // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
1032   //    with only an unconditional branch.
1033   // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
1034   //    with a conditional branch that falls through to a successor (DestB).
1035   // 4. If DestA and DestB is set and isCond is true, then the block ends with a
1036   //    conditional branch followed by an unconditional branch. DestA is the
1037   //    'true' destination and DestB is the 'false' destination.
1038
1039   bool Changed = false;
1040
1041   MachineFunction::iterator FallThru =
1042     std::next(MachineFunction::iterator(this));
1043
1044   if (!DestA && !DestB) {
1045     // Block falls through to successor.
1046     DestA = FallThru;
1047     DestB = FallThru;
1048   } else if (DestA && !DestB) {
1049     if (isCond)
1050       // Block ends in conditional jump that falls through to successor.
1051       DestB = FallThru;
1052   } else {
1053     assert(DestA && DestB && isCond &&
1054            "CFG in a bad state. Cannot correct CFG edges");
1055   }
1056
1057   // Remove superfluous edges. I.e., those which aren't destinations of this
1058   // basic block, duplicate edges, or landing pads.
1059   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1060   MachineBasicBlock::succ_iterator SI = succ_begin();
1061   while (SI != succ_end()) {
1062     const MachineBasicBlock *MBB = *SI;
1063     if (!SeenMBBs.insert(MBB).second ||
1064         (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
1065       // This is a superfluous edge, remove it.
1066       SI = removeSuccessor(SI);
1067       Changed = true;
1068     } else {
1069       ++SI;
1070     }
1071   }
1072
1073   return Changed;
1074 }
1075
1076 /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
1077 /// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
1078 DebugLoc
1079 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1080   DebugLoc DL;
1081   instr_iterator E = instr_end();
1082   if (MBBI == E)
1083     return DL;
1084
1085   // Skip debug declarations, we don't want a DebugLoc from them.
1086   while (MBBI != E && MBBI->isDebugValue())
1087     MBBI++;
1088   if (MBBI != E)
1089     DL = MBBI->getDebugLoc();
1090   return DL;
1091 }
1092
1093 /// getSuccWeight - Return weight of the edge from this block to MBB.
1094 ///
1095 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
1096   if (Weights.empty())
1097     return 0;
1098
1099   return *getWeightIterator(Succ);
1100 }
1101
1102 /// Set successor weight of a given iterator.
1103 void MachineBasicBlock::setSuccWeight(succ_iterator I, uint32_t weight) {
1104   if (Weights.empty())
1105     return;
1106   *getWeightIterator(I) = weight;
1107 }
1108
1109 /// getWeightIterator - Return wight iterator corresonding to the I successor
1110 /// iterator
1111 MachineBasicBlock::weight_iterator MachineBasicBlock::
1112 getWeightIterator(MachineBasicBlock::succ_iterator I) {
1113   assert(Weights.size() == Successors.size() && "Async weight list!");
1114   size_t index = std::distance(Successors.begin(), I);
1115   assert(index < Weights.size() && "Not a current successor!");
1116   return Weights.begin() + index;
1117 }
1118
1119 /// getWeightIterator - Return wight iterator corresonding to the I successor
1120 /// iterator
1121 MachineBasicBlock::const_weight_iterator MachineBasicBlock::
1122 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
1123   assert(Weights.size() == Successors.size() && "Async weight list!");
1124   const size_t index = std::distance(Successors.begin(), I);
1125   assert(index < Weights.size() && "Not a current successor!");
1126   return Weights.begin() + index;
1127 }
1128
1129 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1130 /// as of just before "MI".
1131 /// 
1132 /// Search is localised to a neighborhood of
1133 /// Neighborhood instructions before (searching for defs or kills) and N
1134 /// instructions after (searching just for defs) MI.
1135 MachineBasicBlock::LivenessQueryResult
1136 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1137                                            unsigned Reg, MachineInstr *MI,
1138                                            unsigned Neighborhood) {
1139   unsigned N = Neighborhood;
1140   MachineBasicBlock *MBB = MI->getParent();
1141
1142   // Start by searching backwards from MI, looking for kills, reads or defs.
1143
1144   MachineBasicBlock::iterator I(MI);
1145   // If this is the first insn in the block, don't search backwards.
1146   if (I != MBB->begin()) {
1147     do {
1148       --I;
1149
1150       MachineOperandIteratorBase::PhysRegInfo Analysis =
1151         MIOperands(I).analyzePhysReg(Reg, TRI);
1152
1153       if (Analysis.Defines)
1154         // Outputs happen after inputs so they take precedence if both are
1155         // present.
1156         return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
1157
1158       if (Analysis.Kills || Analysis.Clobbers)
1159         // Register killed, so isn't live.
1160         return LQR_Dead;
1161
1162       else if (Analysis.ReadsOverlap)
1163         // Defined or read without a previous kill - live.
1164         return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
1165
1166     } while (I != MBB->begin() && --N > 0);
1167   }
1168
1169   // Did we get to the start of the block?
1170   if (I == MBB->begin()) {
1171     // If so, the register's state is definitely defined by the live-in state.
1172     for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
1173          RAI.isValid(); ++RAI) {
1174       if (MBB->isLiveIn(*RAI))
1175         return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
1176     }
1177
1178     return LQR_Dead;
1179   }
1180
1181   N = Neighborhood;
1182
1183   // Try searching forwards from MI, looking for reads or defs.
1184   I = MachineBasicBlock::iterator(MI);
1185   // If this is the last insn in the block, don't search forwards.
1186   if (I != MBB->end()) {
1187     for (++I; I != MBB->end() && N > 0; ++I, --N) {
1188       MachineOperandIteratorBase::PhysRegInfo Analysis =
1189         MIOperands(I).analyzePhysReg(Reg, TRI);
1190
1191       if (Analysis.ReadsOverlap)
1192         // Used, therefore must have been live.
1193         return (Analysis.Reads) ?
1194           LQR_Live : LQR_OverlappingLive;
1195
1196       else if (Analysis.Clobbers || Analysis.Defines)
1197         // Defined (but not read) therefore cannot have been live.
1198         return LQR_Dead;
1199     }
1200   }
1201
1202   // At this point we have no idea of the liveness of the register.
1203   return LQR_Unknown;
1204 }