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