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