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