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