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