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