xref: /llvm-project/llvm/lib/CodeGen/MachineBasicBlock.cpp (revision 4a486e773e0ef1add4515ee47b038c274ced2e76)
1 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Collect the sequence of machine instructions for a basic block.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/MachineBasicBlock.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/CodeGen/LiveIntervals.h"
17 #include "llvm/CodeGen/LivePhysRegs.h"
18 #include "llvm/CodeGen/LiveVariables.h"
19 #include "llvm/CodeGen/MachineDomTreeUpdater.h"
20 #include "llvm/CodeGen/MachineDominators.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachinePostDominators.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/SlotIndexes.h"
28 #include "llvm/CodeGen/TargetInstrInfo.h"
29 #include "llvm/CodeGen/TargetLowering.h"
30 #include "llvm/CodeGen/TargetRegisterInfo.h"
31 #include "llvm/CodeGen/TargetSubtargetInfo.h"
32 #include "llvm/Config/llvm-config.h"
33 #include "llvm/IR/BasicBlock.h"
34 #include "llvm/IR/DebugInfoMetadata.h"
35 #include "llvm/IR/ModuleSlotTracker.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include <algorithm>
42 #include <cmath>
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "codegen"
46 
47 static cl::opt<bool> PrintSlotIndexes(
48     "print-slotindexes",
49     cl::desc("When printing machine IR, annotate instructions and blocks with "
50              "SlotIndexes when available"),
51     cl::init(true), cl::Hidden);
52 
53 MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
54     : BB(B), Number(-1), xParent(&MF) {
55   Insts.Parent = this;
56   if (B)
57     IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight();
58 }
59 
60 MachineBasicBlock::~MachineBasicBlock() = default;
61 
62 /// Return the MCSymbol for this basic block.
63 MCSymbol *MachineBasicBlock::getSymbol() const {
64   if (!CachedMCSymbol) {
65     const MachineFunction *MF = getParent();
66     MCContext &Ctx = MF->getContext();
67 
68     // We emit a non-temporary symbol -- with a descriptive name -- if it begins
69     // a section (with basic block sections). Otherwise we fall back to use temp
70     // label.
71     if (MF->hasBBSections() && isBeginSection()) {
72       SmallString<5> Suffix;
73       if (SectionID == MBBSectionID::ColdSectionID) {
74         Suffix += ".cold";
75       } else if (SectionID == MBBSectionID::ExceptionSectionID) {
76         Suffix += ".eh";
77       } else {
78         // For symbols that represent basic block sections, we add ".__part." to
79         // allow tools like symbolizers to know that this represents a part of
80         // the original function.
81         Suffix = (Suffix + Twine(".__part.") + Twine(SectionID.Number)).str();
82       }
83       CachedMCSymbol = Ctx.getOrCreateSymbol(MF->getName() + Suffix);
84     } else {
85       // If the block occurs as label in inline assembly, parsing the assembly
86       // needs an actual label name => set AlwaysEmit in these cases.
87       CachedMCSymbol = Ctx.createBlockSymbol(
88           "BB" + Twine(MF->getFunctionNumber()) + "_" + Twine(getNumber()),
89           /*AlwaysEmit=*/hasLabelMustBeEmitted());
90     }
91   }
92   return CachedMCSymbol;
93 }
94 
95 MCSymbol *MachineBasicBlock::getEHCatchretSymbol() const {
96   if (!CachedEHCatchretMCSymbol) {
97     const MachineFunction *MF = getParent();
98     SmallString<128> SymbolName;
99     raw_svector_ostream(SymbolName)
100         << "$ehgcr_" << MF->getFunctionNumber() << '_' << getNumber();
101     CachedEHCatchretMCSymbol = MF->getContext().getOrCreateSymbol(SymbolName);
102   }
103   return CachedEHCatchretMCSymbol;
104 }
105 
106 MCSymbol *MachineBasicBlock::getEndSymbol() const {
107   if (!CachedEndMCSymbol) {
108     const MachineFunction *MF = getParent();
109     MCContext &Ctx = MF->getContext();
110     CachedEndMCSymbol = Ctx.createBlockSymbol(
111         "BB_END" + Twine(MF->getFunctionNumber()) + "_" + Twine(getNumber()),
112         /*AlwaysEmit=*/false);
113   }
114   return CachedEndMCSymbol;
115 }
116 
117 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
118   MBB.print(OS);
119   return OS;
120 }
121 
122 Printable llvm::printMBBReference(const MachineBasicBlock &MBB) {
123   return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); });
124 }
125 
126 /// When an MBB is added to an MF, we need to update the parent pointer of the
127 /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
128 /// operand list for registers.
129 ///
130 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
131 /// gets the next available unique MBB number. If it is removed from a
132 /// MachineFunction, it goes back to being #-1.
133 void ilist_callback_traits<MachineBasicBlock>::addNodeToList(
134     MachineBasicBlock *N) {
135   MachineFunction &MF = *N->getParent();
136   N->Number = MF.addToMBBNumbering(N);
137 
138   // Make sure the instructions have their operands in the reginfo lists.
139   MachineRegisterInfo &RegInfo = MF.getRegInfo();
140   for (MachineInstr &MI : N->instrs())
141     MI.addRegOperandsToUseLists(RegInfo);
142 }
143 
144 void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList(
145     MachineBasicBlock *N) {
146   N->getParent()->removeFromMBBNumbering(N->Number);
147   N->Number = -1;
148 }
149 
150 /// When we add an instruction to a basic block list, we update its parent
151 /// pointer and add its operands from reg use/def lists if appropriate.
152 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
153   assert(!N->getParent() && "machine instruction already in a basic block");
154   N->setParent(Parent);
155 
156   // Add the instruction's register operands to their corresponding
157   // use/def lists.
158   MachineFunction *MF = Parent->getParent();
159   N->addRegOperandsToUseLists(MF->getRegInfo());
160   MF->handleInsertion(*N);
161 }
162 
163 /// When we remove an instruction from a basic block list, we update its parent
164 /// pointer and remove its operands from reg use/def lists if appropriate.
165 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
166   assert(N->getParent() && "machine instruction not in a basic block");
167 
168   // Remove from the use/def lists.
169   if (MachineFunction *MF = N->getMF()) {
170     MF->handleRemoval(*N);
171     N->removeRegOperandsFromUseLists(MF->getRegInfo());
172   }
173 
174   N->setParent(nullptr);
175 }
176 
177 /// When moving a range of instructions from one MBB list to another, we need to
178 /// update the parent pointers and the use/def lists.
179 void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList,
180                                                        instr_iterator First,
181                                                        instr_iterator Last) {
182   assert(Parent->getParent() == FromList.Parent->getParent() &&
183          "cannot transfer MachineInstrs between MachineFunctions");
184 
185   // If it's within the same BB, there's nothing to do.
186   if (this == &FromList)
187     return;
188 
189   assert(Parent != FromList.Parent && "Two lists have the same parent?");
190 
191   // If splicing between two blocks within the same function, just update the
192   // parent pointers.
193   for (; First != Last; ++First)
194     First->setParent(Parent);
195 }
196 
197 void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
198   assert(!MI->getParent() && "MI is still in a block!");
199   Parent->getParent()->deleteMachineInstr(MI);
200 }
201 
202 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
203   instr_iterator I = instr_begin(), E = instr_end();
204   while (I != E && I->isPHI())
205     ++I;
206   assert((I == E || !I->isInsideBundle()) &&
207          "First non-phi MI cannot be inside a bundle!");
208   return I;
209 }
210 
211 MachineBasicBlock::iterator
212 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
213   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
214 
215   iterator E = end();
216   while (I != E && (I->isPHI() || I->isPosition() ||
217                     TII->isBasicBlockPrologue(*I)))
218     ++I;
219   // FIXME: This needs to change if we wish to bundle labels
220   // inside the bundle.
221   assert((I == E || !I->isInsideBundle()) &&
222          "First non-phi / non-label instruction is inside a bundle!");
223   return I;
224 }
225 
226 MachineBasicBlock::iterator
227 MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I,
228                                           Register Reg, bool SkipPseudoOp) {
229   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
230 
231   iterator E = end();
232   while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() ||
233                     (SkipPseudoOp && I->isPseudoProbe()) ||
234                     TII->isBasicBlockPrologue(*I, Reg)))
235     ++I;
236   // FIXME: This needs to change if we wish to bundle labels / dbg_values
237   // inside the bundle.
238   assert((I == E || !I->isInsideBundle()) &&
239          "First non-phi / non-label / non-debug "
240          "instruction is inside a bundle!");
241   return I;
242 }
243 
244 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
245   iterator B = begin(), E = end(), I = E;
246   while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
247     ; /*noop */
248   while (I != E && !I->isTerminator())
249     ++I;
250   return I;
251 }
252 
253 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
254   instr_iterator B = instr_begin(), E = instr_end(), I = E;
255   while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
256     ; /*noop */
257   while (I != E && !I->isTerminator())
258     ++I;
259   return I;
260 }
261 
262 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminatorForward() {
263   return find_if(instrs(), [](auto &II) { return II.isTerminator(); });
264 }
265 
266 MachineBasicBlock::iterator
267 MachineBasicBlock::getFirstNonDebugInstr(bool SkipPseudoOp) {
268   // Skip over begin-of-block dbg_value instructions.
269   return skipDebugInstructionsForward(begin(), end(), SkipPseudoOp);
270 }
271 
272 MachineBasicBlock::iterator
273 MachineBasicBlock::getLastNonDebugInstr(bool SkipPseudoOp) {
274   // Skip over end-of-block dbg_value instructions.
275   instr_iterator B = instr_begin(), I = instr_end();
276   while (I != B) {
277     --I;
278     // Return instruction that starts a bundle.
279     if (I->isDebugInstr() || I->isInsideBundle())
280       continue;
281     if (SkipPseudoOp && I->isPseudoProbe())
282       continue;
283     return I;
284   }
285   // The block is all debug values.
286   return end();
287 }
288 
289 bool MachineBasicBlock::hasEHPadSuccessor() const {
290   for (const MachineBasicBlock *Succ : successors())
291     if (Succ->isEHPad())
292       return true;
293   return false;
294 }
295 
296 bool MachineBasicBlock::isEntryBlock() const {
297   return getParent()->begin() == getIterator();
298 }
299 
300 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
301 LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
302   print(dbgs());
303 }
304 #endif
305 
306 bool MachineBasicBlock::mayHaveInlineAsmBr() const {
307   for (const MachineBasicBlock *Succ : successors()) {
308     if (Succ->isInlineAsmBrIndirectTarget())
309       return true;
310   }
311   return false;
312 }
313 
314 bool MachineBasicBlock::isLegalToHoistInto() const {
315   if (isReturnBlock() || hasEHPadSuccessor() || mayHaveInlineAsmBr())
316     return false;
317   return true;
318 }
319 
320 bool MachineBasicBlock::hasName() const {
321   if (const BasicBlock *LBB = getBasicBlock())
322     return LBB->hasName();
323   return false;
324 }
325 
326 StringRef MachineBasicBlock::getName() const {
327   if (const BasicBlock *LBB = getBasicBlock())
328     return LBB->getName();
329   else
330     return StringRef("", 0);
331 }
332 
333 /// Return a hopefully unique identifier for this block.
334 std::string MachineBasicBlock::getFullName() const {
335   std::string Name;
336   if (getParent())
337     Name = (getParent()->getName() + ":").str();
338   if (getBasicBlock())
339     Name += getBasicBlock()->getName();
340   else
341     Name += ("BB" + Twine(getNumber())).str();
342   return Name;
343 }
344 
345 void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes,
346                               bool IsStandalone) const {
347   const MachineFunction *MF = getParent();
348   if (!MF) {
349     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
350        << " is null\n";
351     return;
352   }
353   const Function &F = MF->getFunction();
354   const Module *M = F.getParent();
355   ModuleSlotTracker MST(M);
356   MST.incorporateFunction(F);
357   print(OS, MST, Indexes, IsStandalone);
358 }
359 
360 void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
361                               const SlotIndexes *Indexes,
362                               bool IsStandalone) const {
363   const MachineFunction *MF = getParent();
364   if (!MF) {
365     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
366        << " is null\n";
367     return;
368   }
369 
370   if (Indexes && PrintSlotIndexes)
371     OS << Indexes->getMBBStartIdx(this) << '\t';
372 
373   printName(OS, PrintNameIr | PrintNameAttributes, &MST);
374   OS << ":\n";
375 
376   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
377   const MachineRegisterInfo &MRI = MF->getRegInfo();
378   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
379   bool HasLineAttributes = false;
380 
381   // Print the preds of this block according to the CFG.
382   if (!pred_empty() && IsStandalone) {
383     if (Indexes) OS << '\t';
384     // Don't indent(2), align with previous line attributes.
385     OS << "; predecessors: ";
386     ListSeparator LS;
387     for (auto *Pred : predecessors())
388       OS << LS << printMBBReference(*Pred);
389     OS << '\n';
390     HasLineAttributes = true;
391   }
392 
393   if (!succ_empty()) {
394     if (Indexes) OS << '\t';
395     // Print the successors
396     OS.indent(2) << "successors: ";
397     ListSeparator LS;
398     for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
399       OS << LS << printMBBReference(**I);
400       if (!Probs.empty())
401         OS << '('
402            << format("0x%08" PRIx32, getSuccProbability(I).getNumerator())
403            << ')';
404     }
405     if (!Probs.empty() && IsStandalone) {
406       // Print human readable probabilities as comments.
407       OS << "; ";
408       ListSeparator LS;
409       for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
410         const BranchProbability &BP = getSuccProbability(I);
411         OS << LS << printMBBReference(**I) << '('
412            << format("%.2f%%",
413                      rint(((double)BP.getNumerator() / BP.getDenominator()) *
414                           100.0 * 100.0) /
415                          100.0)
416            << ')';
417       }
418     }
419 
420     OS << '\n';
421     HasLineAttributes = true;
422   }
423 
424   if (!livein_empty() && MRI.tracksLiveness()) {
425     if (Indexes) OS << '\t';
426     OS.indent(2) << "liveins: ";
427 
428     ListSeparator LS;
429     for (const auto &LI : liveins()) {
430       OS << LS << printReg(LI.PhysReg, TRI);
431       if (!LI.LaneMask.all())
432         OS << ":0x" << PrintLaneMask(LI.LaneMask);
433     }
434     HasLineAttributes = true;
435   }
436 
437   if (HasLineAttributes)
438     OS << '\n';
439 
440   bool IsInBundle = false;
441   for (const MachineInstr &MI : instrs()) {
442     if (Indexes && PrintSlotIndexes) {
443       if (Indexes->hasIndex(MI))
444         OS << Indexes->getInstructionIndex(MI);
445       OS << '\t';
446     }
447 
448     if (IsInBundle && !MI.isInsideBundle()) {
449       OS.indent(2) << "}\n";
450       IsInBundle = false;
451     }
452 
453     OS.indent(IsInBundle ? 4 : 2);
454     MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
455              /*AddNewLine=*/false, &TII);
456 
457     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
458       OS << " {";
459       IsInBundle = true;
460     }
461     OS << '\n';
462   }
463 
464   if (IsInBundle)
465     OS.indent(2) << "}\n";
466 
467   if (IrrLoopHeaderWeight && IsStandalone) {
468     if (Indexes) OS << '\t';
469     OS.indent(2) << "; Irreducible loop header weight: " << *IrrLoopHeaderWeight
470                  << '\n';
471   }
472 }
473 
474 /// Print the basic block's name as:
475 ///
476 ///    bb.{number}[.{ir-name}] [(attributes...)]
477 ///
478 /// The {ir-name} is only printed when the \ref PrintNameIr flag is passed
479 /// (which is the default). If the IR block has no name, it is identified
480 /// numerically using the attribute syntax as "(%ir-block.{ir-slot})".
481 ///
482 /// When the \ref PrintNameAttributes flag is passed, additional attributes
483 /// of the block are printed when set.
484 ///
485 /// \param printNameFlags Combination of \ref PrintNameFlag flags indicating
486 ///                       the parts to print.
487 /// \param moduleSlotTracker Optional ModuleSlotTracker. This method will
488 ///                          incorporate its own tracker when necessary to
489 ///                          determine the block's IR name.
490 void MachineBasicBlock::printName(raw_ostream &os, unsigned printNameFlags,
491                                   ModuleSlotTracker *moduleSlotTracker) const {
492   os << "bb." << getNumber();
493   bool hasAttributes = false;
494 
495   auto PrintBBRef = [&](const BasicBlock *bb) {
496     os << "%ir-block.";
497     if (bb->hasName()) {
498       os << bb->getName();
499     } else {
500       int slot = -1;
501 
502       if (moduleSlotTracker) {
503         slot = moduleSlotTracker->getLocalSlot(bb);
504       } else if (bb->getParent()) {
505         ModuleSlotTracker tmpTracker(bb->getModule(), false);
506         tmpTracker.incorporateFunction(*bb->getParent());
507         slot = tmpTracker.getLocalSlot(bb);
508       }
509 
510       if (slot == -1)
511         os << "<ir-block badref>";
512       else
513         os << slot;
514     }
515   };
516 
517   if (printNameFlags & PrintNameIr) {
518     if (const auto *bb = getBasicBlock()) {
519       if (bb->hasName()) {
520         os << '.' << bb->getName();
521       } else {
522         hasAttributes = true;
523         os << " (";
524         PrintBBRef(bb);
525       }
526     }
527   }
528 
529   if (printNameFlags & PrintNameAttributes) {
530     if (isMachineBlockAddressTaken()) {
531       os << (hasAttributes ? ", " : " (");
532       os << "machine-block-address-taken";
533       hasAttributes = true;
534     }
535     if (isIRBlockAddressTaken()) {
536       os << (hasAttributes ? ", " : " (");
537       os << "ir-block-address-taken ";
538       PrintBBRef(getAddressTakenIRBlock());
539       hasAttributes = true;
540     }
541     if (isEHPad()) {
542       os << (hasAttributes ? ", " : " (");
543       os << "landing-pad";
544       hasAttributes = true;
545     }
546     if (isInlineAsmBrIndirectTarget()) {
547       os << (hasAttributes ? ", " : " (");
548       os << "inlineasm-br-indirect-target";
549       hasAttributes = true;
550     }
551     if (isEHFuncletEntry()) {
552       os << (hasAttributes ? ", " : " (");
553       os << "ehfunclet-entry";
554       hasAttributes = true;
555     }
556     if (getAlignment() != Align(1)) {
557       os << (hasAttributes ? ", " : " (");
558       os << "align " << getAlignment().value();
559       hasAttributes = true;
560     }
561     if (getSectionID() != MBBSectionID(0)) {
562       os << (hasAttributes ? ", " : " (");
563       os << "bbsections ";
564       switch (getSectionID().Type) {
565       case MBBSectionID::SectionType::Exception:
566         os << "Exception";
567         break;
568       case MBBSectionID::SectionType::Cold:
569         os << "Cold";
570         break;
571       default:
572         os << getSectionID().Number;
573       }
574       hasAttributes = true;
575     }
576     if (getBBID().has_value()) {
577       os << (hasAttributes ? ", " : " (");
578       os << "bb_id " << getBBID()->BaseID;
579       if (getBBID()->CloneID != 0)
580         os << " " << getBBID()->CloneID;
581       hasAttributes = true;
582     }
583     if (CallFrameSize != 0) {
584       os << (hasAttributes ? ", " : " (");
585       os << "call-frame-size " << CallFrameSize;
586       hasAttributes = true;
587     }
588   }
589 
590   if (hasAttributes)
591     os << ')';
592 }
593 
594 void MachineBasicBlock::printAsOperand(raw_ostream &OS,
595                                        bool /*PrintType*/) const {
596   OS << '%';
597   printName(OS, 0);
598 }
599 
600 void MachineBasicBlock::removeLiveIn(MCRegister Reg, LaneBitmask LaneMask) {
601   LiveInVector::iterator I = find_if(
602       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
603   if (I == LiveIns.end())
604     return;
605 
606   I->LaneMask &= ~LaneMask;
607   if (I->LaneMask.none())
608     LiveIns.erase(I);
609 }
610 
611 MachineBasicBlock::livein_iterator
612 MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
613   // Get non-const version of iterator.
614   LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
615   return LiveIns.erase(LI);
616 }
617 
618 bool MachineBasicBlock::isLiveIn(MCRegister Reg, LaneBitmask LaneMask) const {
619   livein_iterator I = find_if(
620       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
621   return I != livein_end() && (I->LaneMask & LaneMask).any();
622 }
623 
624 void MachineBasicBlock::sortUniqueLiveIns() {
625   llvm::sort(LiveIns,
626              [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
627                return LI0.PhysReg < LI1.PhysReg;
628              });
629   // Liveins are sorted by physreg now we can merge their lanemasks.
630   LiveInVector::const_iterator I = LiveIns.begin();
631   LiveInVector::const_iterator J;
632   LiveInVector::iterator Out = LiveIns.begin();
633   for (; I != LiveIns.end(); ++Out, I = J) {
634     MCRegister PhysReg = I->PhysReg;
635     LaneBitmask LaneMask = I->LaneMask;
636     for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
637       LaneMask |= J->LaneMask;
638     Out->PhysReg = PhysReg;
639     Out->LaneMask = LaneMask;
640   }
641   LiveIns.erase(Out, LiveIns.end());
642 }
643 
644 Register
645 MachineBasicBlock::addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC) {
646   assert(getParent() && "MBB must be inserted in function");
647   assert(PhysReg.isPhysical() && "Expected physreg");
648   assert(RC && "Register class is required");
649   assert((isEHPad() || this == &getParent()->front()) &&
650          "Only the entry block and landing pads can have physreg live ins");
651 
652   bool LiveIn = isLiveIn(PhysReg);
653   iterator I = SkipPHIsAndLabels(begin()), E = end();
654   MachineRegisterInfo &MRI = getParent()->getRegInfo();
655   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
656 
657   // Look for an existing copy.
658   if (LiveIn)
659     for (;I != E && I->isCopy(); ++I)
660       if (I->getOperand(1).getReg() == PhysReg) {
661         Register VirtReg = I->getOperand(0).getReg();
662         if (!MRI.constrainRegClass(VirtReg, RC))
663           llvm_unreachable("Incompatible live-in register class.");
664         return VirtReg;
665       }
666 
667   // No luck, create a virtual register.
668   Register VirtReg = MRI.createVirtualRegister(RC);
669   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
670     .addReg(PhysReg, RegState::Kill);
671   if (!LiveIn)
672     addLiveIn(PhysReg);
673   return VirtReg;
674 }
675 
676 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
677   getParent()->splice(NewAfter->getIterator(), getIterator());
678 }
679 
680 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
681   getParent()->splice(++NewBefore->getIterator(), getIterator());
682 }
683 
684 static int findJumpTableIndex(const MachineBasicBlock &MBB) {
685   MachineBasicBlock::const_iterator TerminatorI = MBB.getFirstTerminator();
686   if (TerminatorI == MBB.end())
687     return -1;
688   const MachineInstr &Terminator = *TerminatorI;
689   const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
690   return TII->getJumpTableIndex(Terminator);
691 }
692 
693 void MachineBasicBlock::updateTerminator(
694     MachineBasicBlock *PreviousLayoutSuccessor) {
695   LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
696                     << "\n");
697 
698   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
699   // A block with no successors has no concerns with fall-through edges.
700   if (this->succ_empty())
701     return;
702 
703   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
704   SmallVector<MachineOperand, 4> Cond;
705   DebugLoc DL = findBranchDebugLoc();
706   bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
707   (void) B;
708   assert(!B && "UpdateTerminators requires analyzable predecessors!");
709   if (Cond.empty()) {
710     if (TBB) {
711       // The block has an unconditional branch. If its successor is now its
712       // layout successor, delete the branch.
713       if (isLayoutSuccessor(TBB))
714         TII->removeBranch(*this);
715     } else {
716       // The block has an unconditional fallthrough, or the end of the block is
717       // unreachable.
718 
719       // Unfortunately, whether the end of the block is unreachable is not
720       // immediately obvious; we must fall back to checking the successor list,
721       // and assuming that if the passed in block is in the succesor list and
722       // not an EHPad, it must be the intended target.
723       if (!PreviousLayoutSuccessor || !isSuccessor(PreviousLayoutSuccessor) ||
724           PreviousLayoutSuccessor->isEHPad())
725         return;
726 
727       // If the unconditional successor block is not the current layout
728       // successor, insert a branch to jump to it.
729       if (!isLayoutSuccessor(PreviousLayoutSuccessor))
730         TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
731     }
732     return;
733   }
734 
735   if (FBB) {
736     // The block has a non-fallthrough conditional branch. If one of its
737     // successors is its layout successor, rewrite it to a fallthrough
738     // conditional branch.
739     if (isLayoutSuccessor(TBB)) {
740       if (TII->reverseBranchCondition(Cond))
741         return;
742       TII->removeBranch(*this);
743       TII->insertBranch(*this, FBB, nullptr, Cond, DL);
744     } else if (isLayoutSuccessor(FBB)) {
745       TII->removeBranch(*this);
746       TII->insertBranch(*this, TBB, nullptr, Cond, DL);
747     }
748     return;
749   }
750 
751   // We now know we're going to fallthrough to PreviousLayoutSuccessor.
752   assert(PreviousLayoutSuccessor);
753   assert(!PreviousLayoutSuccessor->isEHPad());
754   assert(isSuccessor(PreviousLayoutSuccessor));
755 
756   if (PreviousLayoutSuccessor == TBB) {
757     // We had a fallthrough to the same basic block as the conditional jump
758     // targets.  Remove the conditional jump, leaving an unconditional
759     // fallthrough or an unconditional jump.
760     TII->removeBranch(*this);
761     if (!isLayoutSuccessor(TBB)) {
762       Cond.clear();
763       TII->insertBranch(*this, TBB, nullptr, Cond, DL);
764     }
765     return;
766   }
767 
768   // The block has a fallthrough conditional branch.
769   if (isLayoutSuccessor(TBB)) {
770     if (TII->reverseBranchCondition(Cond)) {
771       // We can't reverse the condition, add an unconditional branch.
772       Cond.clear();
773       TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
774       return;
775     }
776     TII->removeBranch(*this);
777     TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
778   } else if (!isLayoutSuccessor(PreviousLayoutSuccessor)) {
779     TII->removeBranch(*this);
780     TII->insertBranch(*this, TBB, PreviousLayoutSuccessor, Cond, DL);
781   }
782 }
783 
784 void MachineBasicBlock::validateSuccProbs() const {
785 #ifndef NDEBUG
786   int64_t Sum = 0;
787   for (auto Prob : Probs)
788     Sum += Prob.getNumerator();
789   // Due to precision issue, we assume that the sum of probabilities is one if
790   // the difference between the sum of their numerators and the denominator is
791   // no greater than the number of successors.
792   assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
793              Probs.size() &&
794          "The sum of successors's probabilities exceeds one.");
795 #endif // NDEBUG
796 }
797 
798 void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
799                                      BranchProbability Prob) {
800   // Probability list is either empty (if successor list isn't empty, this means
801   // disabled optimization) or has the same size as successor list.
802   if (!(Probs.empty() && !Successors.empty()))
803     Probs.push_back(Prob);
804   Successors.push_back(Succ);
805   Succ->addPredecessor(this);
806 }
807 
808 void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
809   // We need to make sure probability list is either empty or has the same size
810   // of successor list. When this function is called, we can safely delete all
811   // probability in the list.
812   Probs.clear();
813   Successors.push_back(Succ);
814   Succ->addPredecessor(this);
815 }
816 
817 void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
818                                        MachineBasicBlock *New,
819                                        bool NormalizeSuccProbs) {
820   succ_iterator OldI = llvm::find(successors(), Old);
821   assert(OldI != succ_end() && "Old is not a successor of this block!");
822   assert(!llvm::is_contained(successors(), New) &&
823          "New is already a successor of this block!");
824 
825   // Add a new successor with equal probability as the original one. Note
826   // that we directly copy the probability using the iterator rather than
827   // getting a potentially synthetic probability computed when unknown. This
828   // preserves the probabilities as-is and then we can renormalize them and
829   // query them effectively afterward.
830   addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
831                                   : *getProbabilityIterator(OldI));
832   if (NormalizeSuccProbs)
833     normalizeSuccProbs();
834 }
835 
836 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
837                                         bool NormalizeSuccProbs) {
838   succ_iterator I = find(Successors, Succ);
839   removeSuccessor(I, NormalizeSuccProbs);
840 }
841 
842 MachineBasicBlock::succ_iterator
843 MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
844   assert(I != Successors.end() && "Not a current successor!");
845 
846   // If probability list is empty it means we don't use it (disabled
847   // optimization).
848   if (!Probs.empty()) {
849     probability_iterator WI = getProbabilityIterator(I);
850     Probs.erase(WI);
851     if (NormalizeSuccProbs)
852       normalizeSuccProbs();
853   }
854 
855   (*I)->removePredecessor(this);
856   return Successors.erase(I);
857 }
858 
859 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
860                                          MachineBasicBlock *New) {
861   if (Old == New)
862     return;
863 
864   succ_iterator E = succ_end();
865   succ_iterator NewI = E;
866   succ_iterator OldI = E;
867   for (succ_iterator I = succ_begin(); I != E; ++I) {
868     if (*I == Old) {
869       OldI = I;
870       if (NewI != E)
871         break;
872     }
873     if (*I == New) {
874       NewI = I;
875       if (OldI != E)
876         break;
877     }
878   }
879   assert(OldI != E && "Old is not a successor of this block");
880 
881   // If New isn't already a successor, let it take Old's place.
882   if (NewI == E) {
883     Old->removePredecessor(this);
884     New->addPredecessor(this);
885     *OldI = New;
886     return;
887   }
888 
889   // New is already a successor.
890   // Update its probability instead of adding a duplicate edge.
891   if (!Probs.empty()) {
892     auto ProbIter = getProbabilityIterator(NewI);
893     if (!ProbIter->isUnknown())
894       *ProbIter += *getProbabilityIterator(OldI);
895   }
896   removeSuccessor(OldI);
897 }
898 
899 void MachineBasicBlock::copySuccessor(const MachineBasicBlock *Orig,
900                                       succ_iterator I) {
901   if (!Orig->Probs.empty())
902     addSuccessor(*I, Orig->getSuccProbability(I));
903   else
904     addSuccessorWithoutProb(*I);
905 }
906 
907 void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
908   Predecessors.push_back(Pred);
909 }
910 
911 void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
912   pred_iterator I = find(Predecessors, Pred);
913   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
914   Predecessors.erase(I);
915 }
916 
917 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
918   if (this == FromMBB)
919     return;
920 
921   while (!FromMBB->succ_empty()) {
922     MachineBasicBlock *Succ = *FromMBB->succ_begin();
923 
924     // If probability list is empty it means we don't use it (disabled
925     // optimization).
926     if (!FromMBB->Probs.empty()) {
927       auto Prob = *FromMBB->Probs.begin();
928       addSuccessor(Succ, Prob);
929     } else
930       addSuccessorWithoutProb(Succ);
931 
932     FromMBB->removeSuccessor(Succ);
933   }
934 }
935 
936 void
937 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
938   if (this == FromMBB)
939     return;
940 
941   while (!FromMBB->succ_empty()) {
942     MachineBasicBlock *Succ = *FromMBB->succ_begin();
943     if (!FromMBB->Probs.empty()) {
944       auto Prob = *FromMBB->Probs.begin();
945       addSuccessor(Succ, Prob);
946     } else
947       addSuccessorWithoutProb(Succ);
948     FromMBB->removeSuccessor(Succ);
949 
950     // Fix up any PHI nodes in the successor.
951     Succ->replacePhiUsesWith(FromMBB, this);
952   }
953   normalizeSuccProbs();
954 }
955 
956 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
957   return is_contained(predecessors(), MBB);
958 }
959 
960 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
961   return is_contained(successors(), MBB);
962 }
963 
964 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
965   MachineFunction::const_iterator I(this);
966   return std::next(I) == MachineFunction::const_iterator(MBB);
967 }
968 
969 const MachineBasicBlock *MachineBasicBlock::getSingleSuccessor() const {
970   return Successors.size() == 1 ? Successors[0] : nullptr;
971 }
972 
973 const MachineBasicBlock *MachineBasicBlock::getSinglePredecessor() const {
974   return Predecessors.size() == 1 ? Predecessors[0] : nullptr;
975 }
976 
977 MachineBasicBlock *MachineBasicBlock::getFallThrough(bool JumpToFallThrough) {
978   MachineFunction::iterator Fallthrough = getIterator();
979   ++Fallthrough;
980   // If FallthroughBlock is off the end of the function, it can't fall through.
981   if (Fallthrough == getParent()->end())
982     return nullptr;
983 
984   // If FallthroughBlock isn't a successor, no fallthrough is possible.
985   if (!isSuccessor(&*Fallthrough))
986     return nullptr;
987 
988   // Analyze the branches, if any, at the end of the block.
989   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
990   SmallVector<MachineOperand, 4> Cond;
991   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
992   if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
993     // If we couldn't analyze the branch, examine the last instruction.
994     // If the block doesn't end in a known control barrier, assume fallthrough
995     // is possible. The isPredicated check is needed because this code can be
996     // called during IfConversion, where an instruction which is normally a
997     // Barrier is predicated and thus no longer an actual control barrier.
998     return (empty() || !back().isBarrier() || TII->isPredicated(back()))
999                ? &*Fallthrough
1000                : nullptr;
1001   }
1002 
1003   // If there is no branch, control always falls through.
1004   if (!TBB) return &*Fallthrough;
1005 
1006   // If there is some explicit branch to the fallthrough block, it can obviously
1007   // reach, even though the branch should get folded to fall through implicitly.
1008   if (JumpToFallThrough && (MachineFunction::iterator(TBB) == Fallthrough ||
1009                             MachineFunction::iterator(FBB) == Fallthrough))
1010     return &*Fallthrough;
1011 
1012   // If it's an unconditional branch to some block not the fall through, it
1013   // doesn't fall through.
1014   if (Cond.empty()) return nullptr;
1015 
1016   // Otherwise, if it is conditional and has no explicit false block, it falls
1017   // through.
1018   return (FBB == nullptr) ? &*Fallthrough : nullptr;
1019 }
1020 
1021 bool MachineBasicBlock::canFallThrough() {
1022   return getFallThrough() != nullptr;
1023 }
1024 
1025 MachineBasicBlock *MachineBasicBlock::splitAt(MachineInstr &MI,
1026                                               bool UpdateLiveIns,
1027                                               LiveIntervals *LIS) {
1028   MachineBasicBlock::iterator SplitPoint(&MI);
1029   ++SplitPoint;
1030 
1031   if (SplitPoint == end()) {
1032     // Don't bother with a new block.
1033     return this;
1034   }
1035 
1036   MachineFunction *MF = getParent();
1037 
1038   LivePhysRegs LiveRegs;
1039   if (UpdateLiveIns) {
1040     // Make sure we add any physregs we define in the block as liveins to the
1041     // new block.
1042     MachineBasicBlock::iterator Prev(&MI);
1043     LiveRegs.init(*MF->getSubtarget().getRegisterInfo());
1044     LiveRegs.addLiveOuts(*this);
1045     for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I)
1046       LiveRegs.stepBackward(*I);
1047   }
1048 
1049   MachineBasicBlock *SplitBB = MF->CreateMachineBasicBlock(getBasicBlock());
1050 
1051   MF->insert(++MachineFunction::iterator(this), SplitBB);
1052   SplitBB->splice(SplitBB->begin(), this, SplitPoint, end());
1053 
1054   SplitBB->transferSuccessorsAndUpdatePHIs(this);
1055   addSuccessor(SplitBB);
1056 
1057   if (UpdateLiveIns)
1058     addLiveIns(*SplitBB, LiveRegs);
1059 
1060   if (LIS)
1061     LIS->insertMBBInMaps(SplitBB);
1062 
1063   return SplitBB;
1064 }
1065 
1066 // Returns `true` if there are possibly other users of the jump table at
1067 // `JumpTableIndex` except for the ones in `IgnoreMBB`.
1068 static bool jumpTableHasOtherUses(const MachineFunction &MF,
1069                                   const MachineBasicBlock &IgnoreMBB,
1070                                   int JumpTableIndex) {
1071   assert(JumpTableIndex >= 0 && "need valid index");
1072   const MachineJumpTableInfo &MJTI = *MF.getJumpTableInfo();
1073   const MachineJumpTableEntry &MJTE = MJTI.getJumpTables()[JumpTableIndex];
1074   // Take any basic block from the table; every user of the jump table must
1075   // show up in the predecessor list.
1076   const MachineBasicBlock *MBB = nullptr;
1077   for (MachineBasicBlock *B : MJTE.MBBs) {
1078     if (B != nullptr) {
1079       MBB = B;
1080       break;
1081     }
1082   }
1083   if (MBB == nullptr)
1084     return true; // can't rule out other users if there isn't any block.
1085   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1086   SmallVector<MachineOperand, 4> Cond;
1087   for (MachineBasicBlock *Pred : MBB->predecessors()) {
1088     if (Pred == &IgnoreMBB)
1089       continue;
1090     MachineBasicBlock *DummyT = nullptr;
1091     MachineBasicBlock *DummyF = nullptr;
1092     Cond.clear();
1093     if (!TII.analyzeBranch(*Pred, DummyT, DummyF, Cond,
1094                            /*AllowModify=*/false)) {
1095       // analyzable direct jump
1096       continue;
1097     }
1098     int PredJTI = findJumpTableIndex(*Pred);
1099     if (PredJTI >= 0) {
1100       if (PredJTI == JumpTableIndex)
1101         return true;
1102       continue;
1103     }
1104     // Be conservative for unanalyzable jumps.
1105     return true;
1106   }
1107   return false;
1108 }
1109 
1110 class SlotIndexUpdateDelegate : public MachineFunction::Delegate {
1111 private:
1112   MachineFunction &MF;
1113   SlotIndexes *Indexes;
1114   SmallSetVector<MachineInstr *, 2> Insertions;
1115 
1116 public:
1117   SlotIndexUpdateDelegate(MachineFunction &MF, SlotIndexes *Indexes)
1118       : MF(MF), Indexes(Indexes) {
1119     MF.setDelegate(this);
1120   }
1121 
1122   ~SlotIndexUpdateDelegate() {
1123     MF.resetDelegate(this);
1124     for (auto MI : Insertions)
1125       Indexes->insertMachineInstrInMaps(*MI);
1126   }
1127 
1128   void MF_HandleInsertion(MachineInstr &MI) override {
1129     // This is called before MI is inserted into block so defer index update.
1130     if (Indexes)
1131       Insertions.insert(&MI);
1132   }
1133 
1134   void MF_HandleRemoval(MachineInstr &MI) override {
1135     if (Indexes && !Insertions.remove(&MI))
1136       Indexes->removeMachineInstrFromMaps(MI);
1137   }
1138 };
1139 
1140 #define GET_RESULT(RESULT, GETTER, INFIX)                                      \
1141   [MF, P, MFAM]() {                                                            \
1142     if (P) {                                                                   \
1143       auto *Wrapper = P->getAnalysisIfAvailable<RESULT##INFIX##WrapperPass>(); \
1144       return Wrapper ? &Wrapper->GETTER() : nullptr;                           \
1145     }                                                                          \
1146     return MFAM->getCachedResult<RESULT##Analysis>(*MF);                       \
1147   }()
1148 
1149 MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
1150     MachineBasicBlock *Succ, Pass *P, MachineFunctionAnalysisManager *MFAM,
1151     std::vector<SparseBitVector<>> *LiveInSets, MachineDomTreeUpdater *MDTU) {
1152   assert((P || MFAM) && "Need a way to get analysis results!");
1153   if (!canSplitCriticalEdge(Succ))
1154     return nullptr;
1155 
1156   MachineFunction *MF = getParent();
1157   MachineBasicBlock *PrevFallthrough = getNextNode();
1158 
1159   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
1160   NMBB->setCallFrameSize(Succ->getCallFrameSize());
1161 
1162   // Is there an indirect jump with jump table?
1163   bool ChangedIndirectJump = false;
1164   int JTI = findJumpTableIndex(*this);
1165   if (JTI >= 0) {
1166     MachineJumpTableInfo &MJTI = *MF->getJumpTableInfo();
1167     MJTI.ReplaceMBBInJumpTable(JTI, Succ, NMBB);
1168     ChangedIndirectJump = true;
1169   }
1170 
1171   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
1172   LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
1173                     << " -- " << printMBBReference(*NMBB) << " -- "
1174                     << printMBBReference(*Succ) << '\n');
1175 
1176   LiveIntervals *LIS = GET_RESULT(LiveIntervals, getLIS, );
1177   SlotIndexes *Indexes = GET_RESULT(SlotIndexes, getSI, );
1178   if (LIS)
1179     LIS->insertMBBInMaps(NMBB);
1180   else if (Indexes)
1181     Indexes->insertMBBInMaps(NMBB);
1182 
1183   // On some targets like Mips, branches may kill virtual registers. Make sure
1184   // that LiveVariables is properly updated after updateTerminator replaces the
1185   // terminators.
1186   LiveVariables *LV = GET_RESULT(LiveVariables, getLV, );
1187 
1188   // Collect a list of virtual registers killed by the terminators.
1189   SmallVector<Register, 4> KilledRegs;
1190   if (LV)
1191     for (MachineInstr &MI :
1192          llvm::make_range(getFirstInstrTerminator(), instr_end())) {
1193       for (MachineOperand &MO : MI.all_uses()) {
1194         if (MO.getReg() == 0 || !MO.isKill() || MO.isUndef())
1195           continue;
1196         Register Reg = MO.getReg();
1197         if (Reg.isPhysical() || LV->getVarInfo(Reg).removeKill(MI)) {
1198           KilledRegs.push_back(Reg);
1199           LLVM_DEBUG(dbgs() << "Removing terminator kill: " << MI);
1200           MO.setIsKill(false);
1201         }
1202       }
1203     }
1204 
1205   SmallVector<Register, 4> UsedRegs;
1206   if (LIS) {
1207     for (MachineInstr &MI :
1208          llvm::make_range(getFirstInstrTerminator(), instr_end())) {
1209       for (const MachineOperand &MO : MI.operands()) {
1210         if (!MO.isReg() || MO.getReg() == 0)
1211           continue;
1212 
1213         Register Reg = MO.getReg();
1214         if (!is_contained(UsedRegs, Reg))
1215           UsedRegs.push_back(Reg);
1216       }
1217     }
1218   }
1219 
1220   ReplaceUsesOfBlockWith(Succ, NMBB);
1221 
1222   // Since we replaced all uses of Succ with NMBB, that should also be treated
1223   // as the fallthrough successor
1224   if (Succ == PrevFallthrough)
1225     PrevFallthrough = NMBB;
1226 
1227   if (!ChangedIndirectJump) {
1228     SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1229     updateTerminator(PrevFallthrough);
1230   }
1231 
1232   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
1233   NMBB->addSuccessor(Succ);
1234   if (!NMBB->isLayoutSuccessor(Succ)) {
1235     SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1236     SmallVector<MachineOperand, 4> Cond;
1237     const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
1238 
1239     // In original 'this' BB, there must be a branch instruction targeting at
1240     // Succ. We can not find it out since currently getBranchDestBlock was not
1241     // implemented for all targets. However, if the merged DL has column or line
1242     // number, the scope and non-zero column and line number is same with that
1243     // branch instruction so we can safely use it.
1244     DebugLoc DL, MergedDL = findBranchDebugLoc();
1245     if (MergedDL && (MergedDL.getLine() || MergedDL.getCol()))
1246       DL = MergedDL;
1247     TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
1248   }
1249 
1250   // Fix PHI nodes in Succ so they refer to NMBB instead of this.
1251   Succ->replacePhiUsesWith(this, NMBB);
1252 
1253   // Inherit live-ins from the successor
1254   for (const auto &LI : Succ->liveins())
1255     NMBB->addLiveIn(LI);
1256 
1257   // Update LiveVariables.
1258   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1259   if (LV) {
1260     // Restore kills of virtual registers that were killed by the terminators.
1261     while (!KilledRegs.empty()) {
1262       Register Reg = KilledRegs.pop_back_val();
1263       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
1264         if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false))
1265           continue;
1266         if (Reg.isVirtual())
1267           LV->getVarInfo(Reg).Kills.push_back(&*I);
1268         LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
1269         break;
1270       }
1271     }
1272     // Update relevant live-through information.
1273     if (LiveInSets != nullptr)
1274       LV->addNewBlock(NMBB, this, Succ, *LiveInSets);
1275     else
1276       LV->addNewBlock(NMBB, this, Succ);
1277   }
1278 
1279   if (LIS) {
1280     // After splitting the edge and updating SlotIndexes, live intervals may be
1281     // in one of two situations, depending on whether this block was the last in
1282     // the function. If the original block was the last in the function, all
1283     // live intervals will end prior to the beginning of the new split block. If
1284     // the original block was not at the end of the function, all live intervals
1285     // will extend to the end of the new split block.
1286 
1287     bool isLastMBB =
1288       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
1289 
1290     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
1291     SlotIndex PrevIndex = StartIndex.getPrevSlot();
1292     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
1293 
1294     // Find the registers used from NMBB in PHIs in Succ.
1295     SmallSet<Register, 8> PHISrcRegs;
1296     for (MachineBasicBlock::instr_iterator
1297          I = Succ->instr_begin(), E = Succ->instr_end();
1298          I != E && I->isPHI(); ++I) {
1299       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
1300         if (I->getOperand(ni+1).getMBB() == NMBB) {
1301           MachineOperand &MO = I->getOperand(ni);
1302           Register Reg = MO.getReg();
1303           PHISrcRegs.insert(Reg);
1304           if (MO.isUndef())
1305             continue;
1306 
1307           LiveInterval &LI = LIS->getInterval(Reg);
1308           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1309           assert(VNI &&
1310                  "PHI sources should be live out of their predecessors.");
1311           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1312           for (auto &SR : LI.subranges())
1313             SR.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1314         }
1315       }
1316     }
1317 
1318     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
1319     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1320       Register Reg = Register::index2VirtReg(i);
1321       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
1322         continue;
1323 
1324       LiveInterval &LI = LIS->getInterval(Reg);
1325       if (!LI.liveAt(PrevIndex))
1326         continue;
1327 
1328       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
1329       if (isLiveOut && isLastMBB) {
1330         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1331         assert(VNI && "LiveInterval should have VNInfo where it is live.");
1332         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1333         // Update subranges with live values
1334         for (auto &SR : LI.subranges()) {
1335           VNInfo *VNI = SR.getVNInfoAt(PrevIndex);
1336           if (VNI)
1337             SR.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1338         }
1339       } else if (!isLiveOut && !isLastMBB) {
1340         LI.removeSegment(StartIndex, EndIndex);
1341         for (auto &SR : LI.subranges())
1342           SR.removeSegment(StartIndex, EndIndex);
1343       }
1344     }
1345 
1346     // Update all intervals for registers whose uses may have been modified by
1347     // updateTerminator().
1348     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
1349   }
1350 
1351   if (MDTU)
1352     MDTU->splitCriticalEdge(this, Succ, NMBB);
1353 
1354   if (MachineLoopInfo *MLI = GET_RESULT(MachineLoop, getLI, Info))
1355     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
1356       // If one or the other blocks were not in a loop, the new block is not
1357       // either, and thus LI doesn't need to be updated.
1358       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
1359         if (TIL == DestLoop) {
1360           // Both in the same loop, the NMBB joins loop.
1361           DestLoop->addBasicBlockToLoop(NMBB, *MLI);
1362         } else if (TIL->contains(DestLoop)) {
1363           // Edge from an outer loop to an inner loop.  Add to the outer loop.
1364           TIL->addBasicBlockToLoop(NMBB, *MLI);
1365         } else if (DestLoop->contains(TIL)) {
1366           // Edge from an inner loop to an outer loop.  Add to the outer loop.
1367           DestLoop->addBasicBlockToLoop(NMBB, *MLI);
1368         } else {
1369           // Edge from two loops with no containment relation.  Because these
1370           // are natural loops, we know that the destination block must be the
1371           // header of its loop (adding a branch into a loop elsewhere would
1372           // create an irreducible loop).
1373           assert(DestLoop->getHeader() == Succ &&
1374                  "Should not create irreducible loops!");
1375           if (MachineLoop *P = DestLoop->getParentLoop())
1376             P->addBasicBlockToLoop(NMBB, *MLI);
1377         }
1378       }
1379     }
1380 
1381   return NMBB;
1382 }
1383 
1384 bool MachineBasicBlock::canSplitCriticalEdge(
1385     const MachineBasicBlock *Succ) const {
1386   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1387   // it in this generic function.
1388   if (Succ->isEHPad())
1389     return false;
1390 
1391   // Splitting the critical edge to a callbr's indirect block isn't advised.
1392   // Don't do it in this generic function.
1393   if (Succ->isInlineAsmBrIndirectTarget())
1394     return false;
1395 
1396   const MachineFunction *MF = getParent();
1397   // Performance might be harmed on HW that implements branching using exec mask
1398   // where both sides of the branches are always executed.
1399   if (MF->getTarget().requiresStructuredCFG())
1400     return false;
1401 
1402   // Do we have an Indirect jump with a jumptable that we can rewrite?
1403   int JTI = findJumpTableIndex(*this);
1404   if (JTI >= 0 && !jumpTableHasOtherUses(*MF, *this, JTI))
1405     return true;
1406 
1407   // We may need to update this's terminator, but we can't do that if
1408   // analyzeBranch fails.
1409   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1410   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1411   SmallVector<MachineOperand, 4> Cond;
1412   // AnalyzeBanch should modify this, since we did not allow modification.
1413   if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
1414                          /*AllowModify*/ false))
1415     return false;
1416 
1417   // Avoid bugpoint weirdness: A block may end with a conditional branch but
1418   // jumps to the same MBB is either case. We have duplicate CFG edges in that
1419   // case that we can't handle. Since this never happens in properly optimized
1420   // code, just skip those edges.
1421   if (TBB && TBB == FBB) {
1422     LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
1423                       << printMBBReference(*this) << '\n');
1424     return false;
1425   }
1426   return true;
1427 }
1428 
1429 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1430 /// neighboring instructions so the bundle won't be broken by removing MI.
1431 static void unbundleSingleMI(MachineInstr *MI) {
1432   // Removing the first instruction in a bundle.
1433   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1434     MI->unbundleFromSucc();
1435   // Removing the last instruction in a bundle.
1436   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1437     MI->unbundleFromPred();
1438   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1439   // are already fine.
1440 }
1441 
1442 MachineBasicBlock::instr_iterator
1443 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
1444   unbundleSingleMI(&*I);
1445   return Insts.erase(I);
1446 }
1447 
1448 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
1449   unbundleSingleMI(MI);
1450   MI->clearFlag(MachineInstr::BundledPred);
1451   MI->clearFlag(MachineInstr::BundledSucc);
1452   return Insts.remove(MI);
1453 }
1454 
1455 MachineBasicBlock::instr_iterator
1456 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1457   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1458          "Cannot insert instruction with bundle flags");
1459   // Set the bundle flags when inserting inside a bundle.
1460   if (I != instr_end() && I->isBundledWithPred()) {
1461     MI->setFlag(MachineInstr::BundledPred);
1462     MI->setFlag(MachineInstr::BundledSucc);
1463   }
1464   return Insts.insert(I, MI);
1465 }
1466 
1467 /// This method unlinks 'this' from the containing function, and returns it, but
1468 /// does not delete it.
1469 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1470   assert(getParent() && "Not embedded in a function!");
1471   getParent()->remove(this);
1472   return this;
1473 }
1474 
1475 /// This method unlinks 'this' from the containing function, and deletes it.
1476 void MachineBasicBlock::eraseFromParent() {
1477   assert(getParent() && "Not embedded in a function!");
1478   getParent()->erase(this);
1479 }
1480 
1481 /// Given a machine basic block that branched to 'Old', change the code and CFG
1482 /// so that it branches to 'New' instead.
1483 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1484                                                MachineBasicBlock *New) {
1485   assert(Old != New && "Cannot replace self with self!");
1486 
1487   MachineBasicBlock::instr_iterator I = instr_end();
1488   while (I != instr_begin()) {
1489     --I;
1490     if (!I->isTerminator()) break;
1491 
1492     // Scan the operands of this machine instruction, replacing any uses of Old
1493     // with New.
1494     for (MachineOperand &MO : I->operands())
1495       if (MO.isMBB() && MO.getMBB() == Old)
1496         MO.setMBB(New);
1497   }
1498 
1499   // Update the successor information.
1500   replaceSuccessor(Old, New);
1501 }
1502 
1503 void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old,
1504                                            MachineBasicBlock *New) {
1505   for (MachineInstr &MI : phis())
1506     for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
1507       MachineOperand &MO = MI.getOperand(i);
1508       if (MO.getMBB() == Old)
1509         MO.setMBB(New);
1510     }
1511 }
1512 
1513 /// Find the next valid DebugLoc starting at MBBI, skipping any debug
1514 /// instructions.  Return UnknownLoc if there is none.
1515 DebugLoc
1516 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1517   // Skip debug declarations, we don't want a DebugLoc from them.
1518   MBBI = skipDebugInstructionsForward(MBBI, instr_end());
1519   if (MBBI != instr_end())
1520     return MBBI->getDebugLoc();
1521   return {};
1522 }
1523 
1524 DebugLoc MachineBasicBlock::rfindDebugLoc(reverse_instr_iterator MBBI) {
1525   if (MBBI == instr_rend())
1526     return findDebugLoc(instr_begin());
1527   // Skip debug declarations, we don't want a DebugLoc from them.
1528   MBBI = skipDebugInstructionsBackward(MBBI, instr_rbegin());
1529   if (!MBBI->isDebugInstr())
1530     return MBBI->getDebugLoc();
1531   return {};
1532 }
1533 
1534 /// Find the previous valid DebugLoc preceding MBBI, skipping any debug
1535 /// instructions.  Return UnknownLoc if there is none.
1536 DebugLoc MachineBasicBlock::findPrevDebugLoc(instr_iterator MBBI) {
1537   if (MBBI == instr_begin())
1538     return {};
1539   // Skip debug instructions, we don't want a DebugLoc from them.
1540   MBBI = prev_nodbg(MBBI, instr_begin());
1541   if (!MBBI->isDebugInstr())
1542     return MBBI->getDebugLoc();
1543   return {};
1544 }
1545 
1546 DebugLoc MachineBasicBlock::rfindPrevDebugLoc(reverse_instr_iterator MBBI) {
1547   if (MBBI == instr_rend())
1548     return {};
1549   // Skip debug declarations, we don't want a DebugLoc from them.
1550   MBBI = next_nodbg(MBBI, instr_rend());
1551   if (MBBI != instr_rend())
1552     return MBBI->getDebugLoc();
1553   return {};
1554 }
1555 
1556 /// Find and return the merged DebugLoc of the branch instructions of the block.
1557 /// Return UnknownLoc if there is none.
1558 DebugLoc
1559 MachineBasicBlock::findBranchDebugLoc() {
1560   DebugLoc DL;
1561   auto TI = getFirstTerminator();
1562   while (TI != end() && !TI->isBranch())
1563     ++TI;
1564 
1565   if (TI != end()) {
1566     DL = TI->getDebugLoc();
1567     for (++TI ; TI != end() ; ++TI)
1568       if (TI->isBranch())
1569         DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
1570   }
1571   return DL;
1572 }
1573 
1574 /// Return probability of the edge from this block to MBB.
1575 BranchProbability
1576 MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
1577   if (Probs.empty())
1578     return BranchProbability(1, succ_size());
1579 
1580   const auto &Prob = *getProbabilityIterator(Succ);
1581   if (Prob.isUnknown()) {
1582     // For unknown probabilities, collect the sum of all known ones, and evenly
1583     // ditribute the complemental of the sum to each unknown probability.
1584     unsigned KnownProbNum = 0;
1585     auto Sum = BranchProbability::getZero();
1586     for (const auto &P : Probs) {
1587       if (!P.isUnknown()) {
1588         Sum += P;
1589         KnownProbNum++;
1590       }
1591     }
1592     return Sum.getCompl() / (Probs.size() - KnownProbNum);
1593   } else
1594     return Prob;
1595 }
1596 
1597 /// Set successor probability of a given iterator.
1598 void MachineBasicBlock::setSuccProbability(succ_iterator I,
1599                                            BranchProbability Prob) {
1600   assert(!Prob.isUnknown());
1601   if (Probs.empty())
1602     return;
1603   *getProbabilityIterator(I) = Prob;
1604 }
1605 
1606 /// Return probability iterator corresonding to the I successor iterator
1607 MachineBasicBlock::const_probability_iterator
1608 MachineBasicBlock::getProbabilityIterator(
1609     MachineBasicBlock::const_succ_iterator I) const {
1610   assert(Probs.size() == Successors.size() && "Async probability list!");
1611   const size_t index = std::distance(Successors.begin(), I);
1612   assert(index < Probs.size() && "Not a current successor!");
1613   return Probs.begin() + index;
1614 }
1615 
1616 /// Return probability iterator corresonding to the I successor iterator.
1617 MachineBasicBlock::probability_iterator
1618 MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1619   assert(Probs.size() == Successors.size() && "Async probability list!");
1620   const size_t index = std::distance(Successors.begin(), I);
1621   assert(index < Probs.size() && "Not a current successor!");
1622   return Probs.begin() + index;
1623 }
1624 
1625 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1626 /// as of just before "MI".
1627 ///
1628 /// Search is localised to a neighborhood of
1629 /// Neighborhood instructions before (searching for defs or kills) and N
1630 /// instructions after (searching just for defs) MI.
1631 MachineBasicBlock::LivenessQueryResult
1632 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1633                                            MCRegister Reg, const_iterator Before,
1634                                            unsigned Neighborhood) const {
1635   unsigned N = Neighborhood;
1636 
1637   // Try searching forwards from Before, looking for reads or defs.
1638   const_iterator I(Before);
1639   for (; I != end() && N > 0; ++I) {
1640     if (I->isDebugOrPseudoInstr())
1641       continue;
1642 
1643     --N;
1644 
1645     PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
1646 
1647     // Register is live when we read it here.
1648     if (Info.Read)
1649       return LQR_Live;
1650     // Register is dead if we can fully overwrite or clobber it here.
1651     if (Info.FullyDefined || Info.Clobbered)
1652       return LQR_Dead;
1653   }
1654 
1655   // If we reached the end, it is safe to clobber Reg at the end of a block of
1656   // no successor has it live in.
1657   if (I == end()) {
1658     for (MachineBasicBlock *S : successors()) {
1659       for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
1660         if (TRI->regsOverlap(LI.PhysReg, Reg))
1661           return LQR_Live;
1662       }
1663     }
1664 
1665     return LQR_Dead;
1666   }
1667 
1668 
1669   N = Neighborhood;
1670 
1671   // Start by searching backwards from Before, looking for kills, reads or defs.
1672   I = const_iterator(Before);
1673   // If this is the first insn in the block, don't search backwards.
1674   if (I != begin()) {
1675     do {
1676       --I;
1677 
1678       if (I->isDebugOrPseudoInstr())
1679         continue;
1680 
1681       --N;
1682 
1683       PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
1684 
1685       // Defs happen after uses so they take precedence if both are present.
1686 
1687       // Register is dead after a dead def of the full register.
1688       if (Info.DeadDef)
1689         return LQR_Dead;
1690       // Register is (at least partially) live after a def.
1691       if (Info.Defined) {
1692         if (!Info.PartialDeadDef)
1693           return LQR_Live;
1694         // As soon as we saw a partial definition (dead or not),
1695         // we cannot tell if the value is partial live without
1696         // tracking the lanemasks. We are not going to do this,
1697         // so fall back on the remaining of the analysis.
1698         break;
1699       }
1700       // Register is dead after a full kill or clobber and no def.
1701       if (Info.Killed || Info.Clobbered)
1702         return LQR_Dead;
1703       // Register must be live if we read it.
1704       if (Info.Read)
1705         return LQR_Live;
1706 
1707     } while (I != begin() && N > 0);
1708   }
1709 
1710   // If all the instructions before this in the block are debug instructions,
1711   // skip over them.
1712   while (I != begin() && std::prev(I)->isDebugOrPseudoInstr())
1713     --I;
1714 
1715   // Did we get to the start of the block?
1716   if (I == begin()) {
1717     // If so, the register's state is definitely defined by the live-in state.
1718     for (const MachineBasicBlock::RegisterMaskPair &LI : liveins())
1719       if (TRI->regsOverlap(LI.PhysReg, Reg))
1720         return LQR_Live;
1721 
1722     return LQR_Dead;
1723   }
1724 
1725   // At this point we have no idea of the liveness of the register.
1726   return LQR_Unknown;
1727 }
1728 
1729 const uint32_t *
1730 MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
1731   // EH funclet entry does not preserve any registers.
1732   return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1733 }
1734 
1735 const uint32_t *
1736 MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
1737   // If we see a return block with successors, this must be a funclet return,
1738   // which does not preserve any registers. If there are no successors, we don't
1739   // care what kind of return it is, putting a mask after it is a no-op.
1740   return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1741 }
1742 
1743 void MachineBasicBlock::clearLiveIns() {
1744   LiveIns.clear();
1745 }
1746 
1747 void MachineBasicBlock::clearLiveIns(
1748     std::vector<RegisterMaskPair> &OldLiveIns) {
1749   assert(OldLiveIns.empty() && "Vector must be empty");
1750   std::swap(LiveIns, OldLiveIns);
1751 }
1752 
1753 MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
1754   assert(getParent()->getProperties().hasProperty(
1755       MachineFunctionProperties::Property::TracksLiveness) &&
1756       "Liveness information is accurate");
1757   return LiveIns.begin();
1758 }
1759 
1760 MachineBasicBlock::liveout_iterator MachineBasicBlock::liveout_begin() const {
1761   const MachineFunction &MF = *getParent();
1762   assert(MF.getProperties().hasProperty(
1763       MachineFunctionProperties::Property::TracksLiveness) &&
1764       "Liveness information is accurate");
1765 
1766   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1767   MCPhysReg ExceptionPointer = 0, ExceptionSelector = 0;
1768   if (MF.getFunction().hasPersonalityFn()) {
1769     auto PersonalityFn = MF.getFunction().getPersonalityFn();
1770     ExceptionPointer = TLI.getExceptionPointerRegister(PersonalityFn);
1771     ExceptionSelector = TLI.getExceptionSelectorRegister(PersonalityFn);
1772   }
1773 
1774   return liveout_iterator(*this, ExceptionPointer, ExceptionSelector, false);
1775 }
1776 
1777 bool MachineBasicBlock::sizeWithoutDebugLargerThan(unsigned Limit) const {
1778   unsigned Cntr = 0;
1779   auto R = instructionsWithoutDebug(begin(), end());
1780   for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1781     if (++Cntr > Limit)
1782       return true;
1783   }
1784   return false;
1785 }
1786 
1787 const MBBSectionID MBBSectionID::ColdSectionID(MBBSectionID::SectionType::Cold);
1788 const MBBSectionID
1789     MBBSectionID::ExceptionSectionID(MBBSectionID::SectionType::Exception);
1790