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