xref: /llvm-project/llvm/lib/CodeGen/MachineBasicBlock.cpp (revision 0d955d0bf5cbbd50061309ad2c08c0dcf8f62039)
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) {
474     if (canFallThrough()) {
475       // We fallthrough to the same basic block as the conditional jump targets.
476       // Remove the conditional jump, leaving unconditional fallthrough.
477       // FIXME: This does not seem like a reasonable pattern to support, but it
478       // has been seen in the wild coming out of degenerate ARM test cases.
479       TII->RemoveBranch(*this);
480 
481       // Finally update the unconditional successor to be reached via a branch if
482       // it would not be reached by fallthrough.
483       if (!isLayoutSuccessor(TBB))
484         TII->InsertBranch(*this, TBB, nullptr, Cond, DL);
485       return;
486     }
487 
488     // We enter here iff exactly one successor is TBB which cannot fallthrough
489     // and the rest successors if any are EHPads.  In this case, we need to
490     // change the conditional branch into unconditional branch.
491     TII->RemoveBranch(*this);
492     Cond.clear();
493     TII->InsertBranch(*this, TBB, nullptr, Cond, DL);
494     return;
495   }
496 
497   // The block has a fallthrough conditional branch.
498   if (isLayoutSuccessor(TBB)) {
499     if (TII->ReverseBranchCondition(Cond)) {
500       // We can't reverse the condition, add an unconditional branch.
501       Cond.clear();
502       TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, DL);
503       return;
504     }
505     TII->RemoveBranch(*this);
506     TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, DL);
507   } else if (!isLayoutSuccessor(FallthroughBB)) {
508     TII->RemoveBranch(*this);
509     TII->InsertBranch(*this, TBB, FallthroughBB, Cond, DL);
510   }
511 }
512 
513 void MachineBasicBlock::validateSuccProbs() const {
514 #ifndef NDEBUG
515   int64_t Sum = 0;
516   for (auto Prob : Probs)
517     Sum += Prob.getNumerator();
518   // Due to precision issue, we assume that the sum of probabilities is one if
519   // the difference between the sum of their numerators and the denominator is
520   // no greater than the number of successors.
521   assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
522              Probs.size() &&
523          "The sum of successors's probabilities exceeds one.");
524 #endif // NDEBUG
525 }
526 
527 void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
528                                      BranchProbability Prob) {
529   // Probability list is either empty (if successor list isn't empty, this means
530   // disabled optimization) or has the same size as successor list.
531   if (!(Probs.empty() && !Successors.empty()))
532     Probs.push_back(Prob);
533   Successors.push_back(Succ);
534   Succ->addPredecessor(this);
535 }
536 
537 void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
538   // We need to make sure probability list is either empty or has the same size
539   // of successor list. When this function is called, we can safely delete all
540   // probability in the list.
541   Probs.clear();
542   Successors.push_back(Succ);
543   Succ->addPredecessor(this);
544 }
545 
546 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
547                                         bool NormalizeSuccProbs) {
548   succ_iterator I = find(Successors, Succ);
549   removeSuccessor(I, NormalizeSuccProbs);
550 }
551 
552 MachineBasicBlock::succ_iterator
553 MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
554   assert(I != Successors.end() && "Not a current successor!");
555 
556   // If probability list is empty it means we don't use it (disabled
557   // optimization).
558   if (!Probs.empty()) {
559     probability_iterator WI = getProbabilityIterator(I);
560     Probs.erase(WI);
561     if (NormalizeSuccProbs)
562       normalizeSuccProbs();
563   }
564 
565   (*I)->removePredecessor(this);
566   return Successors.erase(I);
567 }
568 
569 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
570                                          MachineBasicBlock *New) {
571   if (Old == New)
572     return;
573 
574   succ_iterator E = succ_end();
575   succ_iterator NewI = E;
576   succ_iterator OldI = E;
577   for (succ_iterator I = succ_begin(); I != E; ++I) {
578     if (*I == Old) {
579       OldI = I;
580       if (NewI != E)
581         break;
582     }
583     if (*I == New) {
584       NewI = I;
585       if (OldI != E)
586         break;
587     }
588   }
589   assert(OldI != E && "Old is not a successor of this block");
590 
591   // If New isn't already a successor, let it take Old's place.
592   if (NewI == E) {
593     Old->removePredecessor(this);
594     New->addPredecessor(this);
595     *OldI = New;
596     return;
597   }
598 
599   // New is already a successor.
600   // Update its probability instead of adding a duplicate edge.
601   if (!Probs.empty()) {
602     auto ProbIter = getProbabilityIterator(NewI);
603     if (!ProbIter->isUnknown())
604       *ProbIter += *getProbabilityIterator(OldI);
605   }
606   removeSuccessor(OldI);
607 }
608 
609 void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
610   Predecessors.push_back(Pred);
611 }
612 
613 void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
614   pred_iterator I = find(Predecessors, Pred);
615   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
616   Predecessors.erase(I);
617 }
618 
619 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
620   if (this == FromMBB)
621     return;
622 
623   while (!FromMBB->succ_empty()) {
624     MachineBasicBlock *Succ = *FromMBB->succ_begin();
625 
626     // If probability list is empty it means we don't use it (disabled optimization).
627     if (!FromMBB->Probs.empty()) {
628       auto Prob = *FromMBB->Probs.begin();
629       addSuccessor(Succ, Prob);
630     } else
631       addSuccessorWithoutProb(Succ);
632 
633     FromMBB->removeSuccessor(Succ);
634   }
635 }
636 
637 void
638 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
639   if (this == FromMBB)
640     return;
641 
642   while (!FromMBB->succ_empty()) {
643     MachineBasicBlock *Succ = *FromMBB->succ_begin();
644     if (!FromMBB->Probs.empty()) {
645       auto Prob = *FromMBB->Probs.begin();
646       addSuccessor(Succ, Prob);
647     } else
648       addSuccessorWithoutProb(Succ);
649     FromMBB->removeSuccessor(Succ);
650 
651     // Fix up any PHI nodes in the successor.
652     for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
653            ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
654       for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
655         MachineOperand &MO = MI->getOperand(i);
656         if (MO.getMBB() == FromMBB)
657           MO.setMBB(this);
658       }
659   }
660   normalizeSuccProbs();
661 }
662 
663 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
664   return std::find(pred_begin(), pred_end(), MBB) != pred_end();
665 }
666 
667 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
668   return std::find(succ_begin(), succ_end(), MBB) != succ_end();
669 }
670 
671 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
672   MachineFunction::const_iterator I(this);
673   return std::next(I) == MachineFunction::const_iterator(MBB);
674 }
675 
676 bool MachineBasicBlock::canFallThrough() {
677   MachineFunction::iterator Fallthrough = getIterator();
678   ++Fallthrough;
679   // If FallthroughBlock is off the end of the function, it can't fall through.
680   if (Fallthrough == getParent()->end())
681     return false;
682 
683   // If FallthroughBlock isn't a successor, no fallthrough is possible.
684   if (!isSuccessor(&*Fallthrough))
685     return false;
686 
687   // Analyze the branches, if any, at the end of the block.
688   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
689   SmallVector<MachineOperand, 4> Cond;
690   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
691   if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
692     // If we couldn't analyze the branch, examine the last instruction.
693     // If the block doesn't end in a known control barrier, assume fallthrough
694     // is possible. The isPredicated check is needed because this code can be
695     // called during IfConversion, where an instruction which is normally a
696     // Barrier is predicated and thus no longer an actual control barrier.
697     return empty() || !back().isBarrier() || TII->isPredicated(back());
698   }
699 
700   // If there is no branch, control always falls through.
701   if (!TBB) return true;
702 
703   // If there is some explicit branch to the fallthrough block, it can obviously
704   // reach, even though the branch should get folded to fall through implicitly.
705   if (MachineFunction::iterator(TBB) == Fallthrough ||
706       MachineFunction::iterator(FBB) == Fallthrough)
707     return true;
708 
709   // If it's an unconditional branch to some block not the fall through, it
710   // doesn't fall through.
711   if (Cond.empty()) return false;
712 
713   // Otherwise, if it is conditional and has no explicit false block, it falls
714   // through.
715   return FBB == nullptr;
716 }
717 
718 MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ,
719                                                         Pass &P) {
720   if (!canSplitCriticalEdge(Succ))
721     return nullptr;
722 
723   MachineFunction *MF = getParent();
724   DebugLoc DL;  // FIXME: this is nowhere
725 
726   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
727   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
728   DEBUG(dbgs() << "Splitting critical edge:"
729         " BB#" << getNumber()
730         << " -- BB#" << NMBB->getNumber()
731         << " -- BB#" << Succ->getNumber() << '\n');
732 
733   LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
734   SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
735   if (LIS)
736     LIS->insertMBBInMaps(NMBB);
737   else if (Indexes)
738     Indexes->insertMBBInMaps(NMBB);
739 
740   // On some targets like Mips, branches may kill virtual registers. Make sure
741   // that LiveVariables is properly updated after updateTerminator replaces the
742   // terminators.
743   LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
744 
745   // Collect a list of virtual registers killed by the terminators.
746   SmallVector<unsigned, 4> KilledRegs;
747   if (LV)
748     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
749          I != E; ++I) {
750       MachineInstr *MI = &*I;
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             !OI->isUse() || !OI->isKill() || OI->isUndef())
755           continue;
756         unsigned Reg = OI->getReg();
757         if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
758             LV->getVarInfo(Reg).removeKill(*MI)) {
759           KilledRegs.push_back(Reg);
760           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
761           OI->setIsKill(false);
762         }
763       }
764     }
765 
766   SmallVector<unsigned, 4> UsedRegs;
767   if (LIS) {
768     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
769          I != E; ++I) {
770       MachineInstr *MI = &*I;
771 
772       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
773            OE = MI->operands_end(); OI != OE; ++OI) {
774         if (!OI->isReg() || OI->getReg() == 0)
775           continue;
776 
777         unsigned Reg = OI->getReg();
778         if (!is_contained(UsedRegs, Reg))
779           UsedRegs.push_back(Reg);
780       }
781     }
782   }
783 
784   ReplaceUsesOfBlockWith(Succ, NMBB);
785 
786   // If updateTerminator() removes instructions, we need to remove them from
787   // SlotIndexes.
788   SmallVector<MachineInstr*, 4> Terminators;
789   if (Indexes) {
790     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
791          I != E; ++I)
792       Terminators.push_back(&*I);
793   }
794 
795   updateTerminator();
796 
797   if (Indexes) {
798     SmallVector<MachineInstr*, 4> NewTerminators;
799     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
800          I != E; ++I)
801       NewTerminators.push_back(&*I);
802 
803     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
804         E = Terminators.end(); I != E; ++I) {
805       if (!is_contained(NewTerminators, *I))
806         Indexes->removeMachineInstrFromMaps(**I);
807     }
808   }
809 
810   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
811   NMBB->addSuccessor(Succ);
812   if (!NMBB->isLayoutSuccessor(Succ)) {
813     SmallVector<MachineOperand, 4> Cond;
814     const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
815     TII->InsertBranch(*NMBB, Succ, nullptr, Cond, DL);
816 
817     if (Indexes) {
818       for (MachineInstr &MI : NMBB->instrs()) {
819         // Some instructions may have been moved to NMBB by updateTerminator(),
820         // so we first remove any instruction that already has an index.
821         if (Indexes->hasIndex(MI))
822           Indexes->removeMachineInstrFromMaps(MI);
823         Indexes->insertMachineInstrInMaps(MI);
824       }
825     }
826   }
827 
828   // Fix PHI nodes in Succ so they refer to NMBB instead of this
829   for (MachineBasicBlock::instr_iterator
830          i = Succ->instr_begin(),e = Succ->instr_end();
831        i != e && i->isPHI(); ++i)
832     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
833       if (i->getOperand(ni+1).getMBB() == this)
834         i->getOperand(ni+1).setMBB(NMBB);
835 
836   // Inherit live-ins from the successor
837   for (const auto &LI : Succ->liveins())
838     NMBB->addLiveIn(LI);
839 
840   // Update LiveVariables.
841   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
842   if (LV) {
843     // Restore kills of virtual registers that were killed by the terminators.
844     while (!KilledRegs.empty()) {
845       unsigned Reg = KilledRegs.pop_back_val();
846       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
847         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
848           continue;
849         if (TargetRegisterInfo::isVirtualRegister(Reg))
850           LV->getVarInfo(Reg).Kills.push_back(&*I);
851         DEBUG(dbgs() << "Restored terminator kill: " << *I);
852         break;
853       }
854     }
855     // Update relevant live-through information.
856     LV->addNewBlock(NMBB, this, Succ);
857   }
858 
859   if (LIS) {
860     // After splitting the edge and updating SlotIndexes, live intervals may be
861     // in one of two situations, depending on whether this block was the last in
862     // the function. If the original block was the last in the function, all
863     // live intervals will end prior to the beginning of the new split block. If
864     // the original block was not at the end of the function, all live intervals
865     // will extend to the end of the new split block.
866 
867     bool isLastMBB =
868       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
869 
870     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
871     SlotIndex PrevIndex = StartIndex.getPrevSlot();
872     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
873 
874     // Find the registers used from NMBB in PHIs in Succ.
875     SmallSet<unsigned, 8> PHISrcRegs;
876     for (MachineBasicBlock::instr_iterator
877          I = Succ->instr_begin(), E = Succ->instr_end();
878          I != E && I->isPHI(); ++I) {
879       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
880         if (I->getOperand(ni+1).getMBB() == NMBB) {
881           MachineOperand &MO = I->getOperand(ni);
882           unsigned Reg = MO.getReg();
883           PHISrcRegs.insert(Reg);
884           if (MO.isUndef())
885             continue;
886 
887           LiveInterval &LI = LIS->getInterval(Reg);
888           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
889           assert(VNI &&
890                  "PHI sources should be live out of their predecessors.");
891           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
892         }
893       }
894     }
895 
896     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
897     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
898       unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
899       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
900         continue;
901 
902       LiveInterval &LI = LIS->getInterval(Reg);
903       if (!LI.liveAt(PrevIndex))
904         continue;
905 
906       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
907       if (isLiveOut && isLastMBB) {
908         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
909         assert(VNI && "LiveInterval should have VNInfo where it is live.");
910         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
911       } else if (!isLiveOut && !isLastMBB) {
912         LI.removeSegment(StartIndex, EndIndex);
913       }
914     }
915 
916     // Update all intervals for registers whose uses may have been modified by
917     // updateTerminator().
918     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
919   }
920 
921   if (MachineDominatorTree *MDT =
922           P.getAnalysisIfAvailable<MachineDominatorTree>())
923     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
924 
925   if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
926     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
927       // If one or the other blocks were not in a loop, the new block is not
928       // either, and thus LI doesn't need to be updated.
929       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
930         if (TIL == DestLoop) {
931           // Both in the same loop, the NMBB joins loop.
932           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
933         } else if (TIL->contains(DestLoop)) {
934           // Edge from an outer loop to an inner loop.  Add to the outer loop.
935           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
936         } else if (DestLoop->contains(TIL)) {
937           // Edge from an inner loop to an outer loop.  Add to the outer loop.
938           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
939         } else {
940           // Edge from two loops with no containment relation.  Because these
941           // are natural loops, we know that the destination block must be the
942           // header of its loop (adding a branch into a loop elsewhere would
943           // create an irreducible loop).
944           assert(DestLoop->getHeader() == Succ &&
945                  "Should not create irreducible loops!");
946           if (MachineLoop *P = DestLoop->getParentLoop())
947             P->addBasicBlockToLoop(NMBB, MLI->getBase());
948         }
949       }
950     }
951 
952   return NMBB;
953 }
954 
955 bool MachineBasicBlock::canSplitCriticalEdge(
956     const MachineBasicBlock *Succ) const {
957   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
958   // it in this generic function.
959   if (Succ->isEHPad())
960     return false;
961 
962   const MachineFunction *MF = getParent();
963 
964   // Performance might be harmed on HW that implements branching using exec mask
965   // where both sides of the branches are always executed.
966   if (MF->getTarget().requiresStructuredCFG())
967     return false;
968 
969   // We may need to update this's terminator, but we can't do that if
970   // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
971   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
972   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
973   SmallVector<MachineOperand, 4> Cond;
974   // AnalyzeBanch should modify this, since we did not allow modification.
975   if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
976                          /*AllowModify*/ false))
977     return false;
978 
979   // Avoid bugpoint weirdness: A block may end with a conditional branch but
980   // jumps to the same MBB is either case. We have duplicate CFG edges in that
981   // case that we can't handle. Since this never happens in properly optimized
982   // code, just skip those edges.
983   if (TBB && TBB == FBB) {
984     DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
985                  << getNumber() << '\n');
986     return false;
987   }
988   return true;
989 }
990 
991 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
992 /// neighboring instructions so the bundle won't be broken by removing MI.
993 static void unbundleSingleMI(MachineInstr *MI) {
994   // Removing the first instruction in a bundle.
995   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
996     MI->unbundleFromSucc();
997   // Removing the last instruction in a bundle.
998   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
999     MI->unbundleFromPred();
1000   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1001   // are already fine.
1002 }
1003 
1004 MachineBasicBlock::instr_iterator
1005 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
1006   unbundleSingleMI(&*I);
1007   return Insts.erase(I);
1008 }
1009 
1010 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
1011   unbundleSingleMI(MI);
1012   MI->clearFlag(MachineInstr::BundledPred);
1013   MI->clearFlag(MachineInstr::BundledSucc);
1014   return Insts.remove(MI);
1015 }
1016 
1017 MachineBasicBlock::instr_iterator
1018 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1019   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1020          "Cannot insert instruction with bundle flags");
1021   // Set the bundle flags when inserting inside a bundle.
1022   if (I != instr_end() && I->isBundledWithPred()) {
1023     MI->setFlag(MachineInstr::BundledPred);
1024     MI->setFlag(MachineInstr::BundledSucc);
1025   }
1026   return Insts.insert(I, MI);
1027 }
1028 
1029 /// This method unlinks 'this' from the containing function, and returns it, but
1030 /// does not delete it.
1031 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1032   assert(getParent() && "Not embedded in a function!");
1033   getParent()->remove(this);
1034   return this;
1035 }
1036 
1037 /// This method unlinks 'this' from the containing function, and deletes it.
1038 void MachineBasicBlock::eraseFromParent() {
1039   assert(getParent() && "Not embedded in a function!");
1040   getParent()->erase(this);
1041 }
1042 
1043 /// Given a machine basic block that branched to 'Old', change the code and CFG
1044 /// so that it branches to 'New' instead.
1045 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1046                                                MachineBasicBlock *New) {
1047   assert(Old != New && "Cannot replace self with self!");
1048 
1049   MachineBasicBlock::instr_iterator I = instr_end();
1050   while (I != instr_begin()) {
1051     --I;
1052     if (!I->isTerminator()) break;
1053 
1054     // Scan the operands of this machine instruction, replacing any uses of Old
1055     // with New.
1056     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1057       if (I->getOperand(i).isMBB() &&
1058           I->getOperand(i).getMBB() == Old)
1059         I->getOperand(i).setMBB(New);
1060   }
1061 
1062   // Update the successor information.
1063   replaceSuccessor(Old, New);
1064 }
1065 
1066 /// Various pieces of code can cause excess edges in the CFG to be inserted.  If
1067 /// we have proven that MBB can only branch to DestA and DestB, remove any other
1068 /// MBB successors from the CFG.  DestA and DestB can be null.
1069 ///
1070 /// Besides DestA and DestB, retain other edges leading to LandingPads
1071 /// (currently there can be only one; we don't check or require that here).
1072 /// Note it is possible that DestA and/or DestB are LandingPads.
1073 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1074                                              MachineBasicBlock *DestB,
1075                                              bool IsCond) {
1076   // The values of DestA and DestB frequently come from a call to the
1077   // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1078   // values from there.
1079   //
1080   // 1. If both DestA and DestB are null, then the block ends with no branches
1081   //    (it falls through to its successor).
1082   // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends
1083   //    with only an unconditional branch.
1084   // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends
1085   //    with a conditional branch that falls through to a successor (DestB).
1086   // 4. If DestA and DestB is set and IsCond is true, then the block ends with a
1087   //    conditional branch followed by an unconditional branch. DestA is the
1088   //    'true' destination and DestB is the 'false' destination.
1089 
1090   bool Changed = false;
1091 
1092   MachineFunction::iterator FallThru = std::next(getIterator());
1093 
1094   if (!DestA && !DestB) {
1095     // Block falls through to successor.
1096     DestA = &*FallThru;
1097     DestB = &*FallThru;
1098   } else if (DestA && !DestB) {
1099     if (IsCond)
1100       // Block ends in conditional jump that falls through to successor.
1101       DestB = &*FallThru;
1102   } else {
1103     assert(DestA && DestB && IsCond &&
1104            "CFG in a bad state. Cannot correct CFG edges");
1105   }
1106 
1107   // Remove superfluous edges. I.e., those which aren't destinations of this
1108   // basic block, duplicate edges, or landing pads.
1109   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1110   MachineBasicBlock::succ_iterator SI = succ_begin();
1111   while (SI != succ_end()) {
1112     const MachineBasicBlock *MBB = *SI;
1113     if (!SeenMBBs.insert(MBB).second ||
1114         (MBB != DestA && MBB != DestB && !MBB->isEHPad())) {
1115       // This is a superfluous edge, remove it.
1116       SI = removeSuccessor(SI);
1117       Changed = true;
1118     } else {
1119       ++SI;
1120     }
1121   }
1122 
1123   if (Changed)
1124     normalizeSuccProbs();
1125   return Changed;
1126 }
1127 
1128 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
1129 /// instructions.  Return UnknownLoc if there is none.
1130 DebugLoc
1131 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1132   DebugLoc DL;
1133   instr_iterator E = instr_end();
1134   if (MBBI == E)
1135     return DL;
1136 
1137   // Skip debug declarations, we don't want a DebugLoc from them.
1138   while (MBBI != E && MBBI->isDebugValue())
1139     MBBI++;
1140   if (MBBI != E)
1141     DL = MBBI->getDebugLoc();
1142   return DL;
1143 }
1144 
1145 /// Return probability of the edge from this block to MBB.
1146 BranchProbability
1147 MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
1148   if (Probs.empty())
1149     return BranchProbability(1, succ_size());
1150 
1151   const auto &Prob = *getProbabilityIterator(Succ);
1152   if (Prob.isUnknown()) {
1153     // For unknown probabilities, collect the sum of all known ones, and evenly
1154     // ditribute the complemental of the sum to each unknown probability.
1155     unsigned KnownProbNum = 0;
1156     auto Sum = BranchProbability::getZero();
1157     for (auto &P : Probs) {
1158       if (!P.isUnknown()) {
1159         Sum += P;
1160         KnownProbNum++;
1161       }
1162     }
1163     return Sum.getCompl() / (Probs.size() - KnownProbNum);
1164   } else
1165     return Prob;
1166 }
1167 
1168 /// Set successor probability of a given iterator.
1169 void MachineBasicBlock::setSuccProbability(succ_iterator I,
1170                                            BranchProbability Prob) {
1171   assert(!Prob.isUnknown());
1172   if (Probs.empty())
1173     return;
1174   *getProbabilityIterator(I) = Prob;
1175 }
1176 
1177 /// Return probability iterator corresonding to the I successor iterator
1178 MachineBasicBlock::const_probability_iterator
1179 MachineBasicBlock::getProbabilityIterator(
1180     MachineBasicBlock::const_succ_iterator I) const {
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 probability iterator corresonding to the I successor iterator.
1188 MachineBasicBlock::probability_iterator
1189 MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1190   assert(Probs.size() == Successors.size() && "Async probability list!");
1191   const size_t index = std::distance(Successors.begin(), I);
1192   assert(index < Probs.size() && "Not a current successor!");
1193   return Probs.begin() + index;
1194 }
1195 
1196 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1197 /// as of just before "MI".
1198 ///
1199 /// Search is localised to a neighborhood of
1200 /// Neighborhood instructions before (searching for defs or kills) and N
1201 /// instructions after (searching just for defs) MI.
1202 MachineBasicBlock::LivenessQueryResult
1203 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1204                                            unsigned Reg, const_iterator Before,
1205                                            unsigned Neighborhood) const {
1206   unsigned N = Neighborhood;
1207 
1208   // Start by searching backwards from Before, looking for kills, reads or defs.
1209   const_iterator I(Before);
1210   // If this is the first insn in the block, don't search backwards.
1211   if (I != begin()) {
1212     do {
1213       --I;
1214 
1215       MachineOperandIteratorBase::PhysRegInfo Info =
1216           ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
1217 
1218       // Defs happen after uses so they take precedence if both are present.
1219 
1220       // Register is dead after a dead def of the full register.
1221       if (Info.DeadDef)
1222         return LQR_Dead;
1223       // Register is (at least partially) live after a def.
1224       if (Info.Defined) {
1225         if (!Info.PartialDeadDef)
1226           return LQR_Live;
1227         // As soon as we saw a partial definition (dead or not),
1228         // we cannot tell if the value is partial live without
1229         // tracking the lanemasks. We are not going to do this,
1230         // so fall back on the remaining of the analysis.
1231         break;
1232       }
1233       // Register is dead after a full kill or clobber and no def.
1234       if (Info.Killed || Info.Clobbered)
1235         return LQR_Dead;
1236       // Register must be live if we read it.
1237       if (Info.Read)
1238         return LQR_Live;
1239     } while (I != begin() && --N > 0);
1240   }
1241 
1242   // Did we get to the start of the block?
1243   if (I == begin()) {
1244     // If so, the register's state is definitely defined by the live-in state.
1245     for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true); RAI.isValid();
1246          ++RAI)
1247       if (isLiveIn(*RAI))
1248         return LQR_Live;
1249 
1250     return LQR_Dead;
1251   }
1252 
1253   N = Neighborhood;
1254 
1255   // Try searching forwards from Before, looking for reads or defs.
1256   I = const_iterator(Before);
1257   // If this is the last insn in the block, don't search forwards.
1258   if (I != end()) {
1259     for (++I; I != end() && N > 0; ++I, --N) {
1260       MachineOperandIteratorBase::PhysRegInfo Info =
1261           ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
1262 
1263       // Register is live when we read it here.
1264       if (Info.Read)
1265         return LQR_Live;
1266       // Register is dead if we can fully overwrite or clobber it here.
1267       if (Info.FullyDefined || Info.Clobbered)
1268         return LQR_Dead;
1269     }
1270   }
1271 
1272   // At this point we have no idea of the liveness of the register.
1273   return LQR_Unknown;
1274 }
1275 
1276 const uint32_t *
1277 MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
1278   // EH funclet entry does not preserve any registers.
1279   return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1280 }
1281 
1282 const uint32_t *
1283 MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
1284   // If we see a return block with successors, this must be a funclet return,
1285   // which does not preserve any registers. If there are no successors, we don't
1286   // care what kind of return it is, putting a mask after it is a no-op.
1287   return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1288 }
1289