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