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