xref: /llvm-project/llvm/lib/CodeGen/MachineBasicBlock.cpp (revision 10ce1bc8d02738c20a7e6c49f51b28a26d93927f)
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     // We emit a non-temporary symbol for every basic block if we have BBLabels
66     // or -- with basic block sections -- when a basic block begins a section.
67     bool BasicBlockSymbols = isBeginSection() || MF->hasBBLabels();
68     auto Delimiter = BasicBlockSymbols ? "." : "_";
69     assert(getNumber() >= 0 && "cannot get label for unreachable MBB");
70 
71     // With Basic Block Sections, we emit a symbol for every basic block. To
72     // keep the size of strtab small, we choose a unary encoding which can
73     // compress the symbol names significantly.  The basic blocks for function
74     // foo are named a.BB.foo, aa.BB.foo, and so on.
75     if (BasicBlockSymbols) {
76       auto Iter = MF->getBBSectionsSymbolPrefix().begin();
77       if (getNumber() < 0 ||
78           getNumber() >= (int)MF->getBBSectionsSymbolPrefix().size())
79         report_fatal_error("Unreachable MBB: " + Twine(getNumber()));
80       std::string Prefix(Iter + 1, Iter + getNumber() + 1);
81       std::reverse(Prefix.begin(), Prefix.end());
82       CachedMCSymbol =
83           Ctx.getOrCreateSymbol(Prefix + Twine(Delimiter) + "BB" +
84                                 Twine(Delimiter) + Twine(MF->getName()));
85     } else {
86       CachedMCSymbol = Ctx.getOrCreateSymbol(
87           Twine(Prefix) + "BB" + Twine(MF->getFunctionNumber()) +
88           Twine(Delimiter) + Twine(getNumber()));
89     }
90   }
91   return CachedMCSymbol;
92 }
93 
94 
95 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
96   MBB.print(OS);
97   return OS;
98 }
99 
100 Printable llvm::printMBBReference(const MachineBasicBlock &MBB) {
101   return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); });
102 }
103 
104 /// When an MBB is added to an MF, we need to update the parent pointer of the
105 /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
106 /// operand list for registers.
107 ///
108 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
109 /// gets the next available unique MBB number. If it is removed from a
110 /// MachineFunction, it goes back to being #-1.
111 void ilist_callback_traits<MachineBasicBlock>::addNodeToList(
112     MachineBasicBlock *N) {
113   MachineFunction &MF = *N->getParent();
114   N->Number = MF.addToMBBNumbering(N);
115 
116   // Make sure the instructions have their operands in the reginfo lists.
117   MachineRegisterInfo &RegInfo = MF.getRegInfo();
118   for (MachineBasicBlock::instr_iterator
119          I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
120     I->AddRegOperandsToUseLists(RegInfo);
121 }
122 
123 void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList(
124     MachineBasicBlock *N) {
125   N->getParent()->removeFromMBBNumbering(N->Number);
126   N->Number = -1;
127 }
128 
129 /// When we add an instruction to a basic block list, we update its parent
130 /// pointer and add its operands from reg use/def lists if appropriate.
131 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
132   assert(!N->getParent() && "machine instruction already in a basic block");
133   N->setParent(Parent);
134 
135   // Add the instruction's register operands to their corresponding
136   // use/def lists.
137   MachineFunction *MF = Parent->getParent();
138   N->AddRegOperandsToUseLists(MF->getRegInfo());
139   MF->handleInsertion(*N);
140 }
141 
142 /// When we remove an instruction from a basic block list, we update its parent
143 /// pointer and remove its operands from reg use/def lists if appropriate.
144 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
145   assert(N->getParent() && "machine instruction not in a basic block");
146 
147   // Remove from the use/def lists.
148   if (MachineFunction *MF = N->getMF()) {
149     MF->handleRemoval(*N);
150     N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
151   }
152 
153   N->setParent(nullptr);
154 }
155 
156 /// When moving a range of instructions from one MBB list to another, we need to
157 /// update the parent pointers and the use/def lists.
158 void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList,
159                                                        instr_iterator First,
160                                                        instr_iterator Last) {
161   assert(Parent->getParent() == FromList.Parent->getParent() &&
162          "cannot transfer MachineInstrs between MachineFunctions");
163 
164   // If it's within the same BB, there's nothing to do.
165   if (this == &FromList)
166     return;
167 
168   assert(Parent != FromList.Parent && "Two lists have the same parent?");
169 
170   // If splicing between two blocks within the same function, just update the
171   // parent pointers.
172   for (; First != Last; ++First)
173     First->setParent(Parent);
174 }
175 
176 void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
177   assert(!MI->getParent() && "MI is still in a block!");
178   Parent->getParent()->DeleteMachineInstr(MI);
179 }
180 
181 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
182   instr_iterator I = instr_begin(), E = instr_end();
183   while (I != E && I->isPHI())
184     ++I;
185   assert((I == E || !I->isInsideBundle()) &&
186          "First non-phi MI cannot be inside a bundle!");
187   return I;
188 }
189 
190 MachineBasicBlock::iterator
191 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
192   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
193 
194   iterator E = end();
195   while (I != E && (I->isPHI() || I->isPosition() ||
196                     TII->isBasicBlockPrologue(*I)))
197     ++I;
198   // FIXME: This needs to change if we wish to bundle labels
199   // inside the bundle.
200   assert((I == E || !I->isInsideBundle()) &&
201          "First non-phi / non-label instruction is inside a bundle!");
202   return I;
203 }
204 
205 MachineBasicBlock::iterator
206 MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I) {
207   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
208 
209   iterator E = end();
210   while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() ||
211                     TII->isBasicBlockPrologue(*I)))
212     ++I;
213   // FIXME: This needs to change if we wish to bundle labels / dbg_values
214   // inside the bundle.
215   assert((I == E || !I->isInsideBundle()) &&
216          "First non-phi / non-label / non-debug "
217          "instruction is inside a bundle!");
218   return I;
219 }
220 
221 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
222   iterator B = begin(), E = end(), I = E;
223   while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
224     ; /*noop */
225   while (I != E && !I->isTerminator())
226     ++I;
227   return I;
228 }
229 
230 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
231   instr_iterator B = instr_begin(), E = instr_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::iterator MachineBasicBlock::getFirstNonDebugInstr() {
240   // Skip over begin-of-block dbg_value instructions.
241   return skipDebugInstructionsForward(begin(), end());
242 }
243 
244 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
245   // Skip over end-of-block dbg_value instructions.
246   instr_iterator B = instr_begin(), I = instr_end();
247   while (I != B) {
248     --I;
249     // Return instruction that starts a bundle.
250     if (I->isDebugInstr() || I->isInsideBundle())
251       continue;
252     return I;
253   }
254   // The block is all debug values.
255   return end();
256 }
257 
258 bool MachineBasicBlock::hasEHPadSuccessor() const {
259   for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
260     if ((*I)->isEHPad())
261       return true;
262   return false;
263 }
264 
265 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
266 LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
267   print(dbgs());
268 }
269 #endif
270 
271 bool MachineBasicBlock::isLegalToHoistInto() const {
272   if (isReturnBlock() || hasEHPadSuccessor())
273     return false;
274   return true;
275 }
276 
277 StringRef MachineBasicBlock::getName() const {
278   if (const BasicBlock *LBB = getBasicBlock())
279     return LBB->getName();
280   else
281     return StringRef("", 0);
282 }
283 
284 /// Return a hopefully unique identifier for this block.
285 std::string MachineBasicBlock::getFullName() const {
286   std::string Name;
287   if (getParent())
288     Name = (getParent()->getName() + ":").str();
289   if (getBasicBlock())
290     Name += getBasicBlock()->getName();
291   else
292     Name += ("BB" + Twine(getNumber())).str();
293   return Name;
294 }
295 
296 void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes,
297                               bool IsStandalone) const {
298   const MachineFunction *MF = getParent();
299   if (!MF) {
300     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
301        << " is null\n";
302     return;
303   }
304   const Function &F = MF->getFunction();
305   const Module *M = F.getParent();
306   ModuleSlotTracker MST(M);
307   MST.incorporateFunction(F);
308   print(OS, MST, Indexes, IsStandalone);
309 }
310 
311 void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
312                               const SlotIndexes *Indexes,
313                               bool IsStandalone) const {
314   const MachineFunction *MF = getParent();
315   if (!MF) {
316     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
317        << " is null\n";
318     return;
319   }
320 
321   if (Indexes && PrintSlotIndexes)
322     OS << Indexes->getMBBStartIdx(this) << '\t';
323 
324   OS << "bb." << getNumber();
325   bool HasAttributes = false;
326   if (const auto *BB = getBasicBlock()) {
327     if (BB->hasName()) {
328       OS << "." << BB->getName();
329     } else {
330       HasAttributes = true;
331       OS << " (";
332       int Slot = MST.getLocalSlot(BB);
333       if (Slot == -1)
334         OS << "<ir-block badref>";
335       else
336         OS << (Twine("%ir-block.") + Twine(Slot)).str();
337     }
338   }
339 
340   if (hasAddressTaken()) {
341     OS << (HasAttributes ? ", " : " (");
342     OS << "address-taken";
343     HasAttributes = true;
344   }
345   if (isEHPad()) {
346     OS << (HasAttributes ? ", " : " (");
347     OS << "landing-pad";
348     HasAttributes = true;
349   }
350   if (getAlignment() != Align(1)) {
351     OS << (HasAttributes ? ", " : " (");
352     OS << "align " << Log2(getAlignment());
353     HasAttributes = true;
354   }
355   if (HasAttributes)
356     OS << ")";
357   OS << ":\n";
358 
359   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
360   const MachineRegisterInfo &MRI = MF->getRegInfo();
361   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
362   bool HasLineAttributes = false;
363 
364   // Print the preds of this block according to the CFG.
365   if (!pred_empty() && IsStandalone) {
366     if (Indexes) OS << '\t';
367     // Don't indent(2), align with previous line attributes.
368     OS << "; predecessors: ";
369     for (auto I = pred_begin(), E = pred_end(); I != E; ++I) {
370       if (I != pred_begin())
371         OS << ", ";
372       OS << printMBBReference(**I);
373     }
374     OS << '\n';
375     HasLineAttributes = true;
376   }
377 
378   if (!succ_empty()) {
379     if (Indexes) OS << '\t';
380     // Print the successors
381     OS.indent(2) << "successors: ";
382     for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
383       if (I != succ_begin())
384         OS << ", ";
385       OS << printMBBReference(**I);
386       if (!Probs.empty())
387         OS << '('
388            << format("0x%08" PRIx32, getSuccProbability(I).getNumerator())
389            << ')';
390     }
391     if (!Probs.empty() && IsStandalone) {
392       // Print human readable probabilities as comments.
393       OS << "; ";
394       for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
395         const BranchProbability &BP = getSuccProbability(I);
396         if (I != succ_begin())
397           OS << ", ";
398         OS << printMBBReference(**I) << '('
399            << format("%.2f%%",
400                      rint(((double)BP.getNumerator() / BP.getDenominator()) *
401                           100.0 * 100.0) /
402                          100.0)
403            << ')';
404       }
405     }
406 
407     OS << '\n';
408     HasLineAttributes = true;
409   }
410 
411   if (!livein_empty() && MRI.tracksLiveness()) {
412     if (Indexes) OS << '\t';
413     OS.indent(2) << "liveins: ";
414 
415     bool First = true;
416     for (const auto &LI : liveins()) {
417       if (!First)
418         OS << ", ";
419       First = false;
420       OS << printReg(LI.PhysReg, TRI);
421       if (!LI.LaneMask.all())
422         OS << ":0x" << PrintLaneMask(LI.LaneMask);
423     }
424     HasLineAttributes = true;
425   }
426 
427   if (HasLineAttributes)
428     OS << '\n';
429 
430   bool IsInBundle = false;
431   for (const MachineInstr &MI : instrs()) {
432     if (Indexes && PrintSlotIndexes) {
433       if (Indexes->hasIndex(MI))
434         OS << Indexes->getInstructionIndex(MI);
435       OS << '\t';
436     }
437 
438     if (IsInBundle && !MI.isInsideBundle()) {
439       OS.indent(2) << "}\n";
440       IsInBundle = false;
441     }
442 
443     OS.indent(IsInBundle ? 4 : 2);
444     MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
445              /*AddNewLine=*/false, &TII);
446 
447     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
448       OS << " {";
449       IsInBundle = true;
450     }
451     OS << '\n';
452   }
453 
454   if (IsInBundle)
455     OS.indent(2) << "}\n";
456 
457   if (IrrLoopHeaderWeight && IsStandalone) {
458     if (Indexes) OS << '\t';
459     OS.indent(2) << "; Irreducible loop header weight: "
460                  << IrrLoopHeaderWeight.getValue() << '\n';
461   }
462 }
463 
464 void MachineBasicBlock::printAsOperand(raw_ostream &OS,
465                                        bool /*PrintType*/) const {
466   OS << "%bb." << getNumber();
467 }
468 
469 void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
470   LiveInVector::iterator I = find_if(
471       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
472   if (I == LiveIns.end())
473     return;
474 
475   I->LaneMask &= ~LaneMask;
476   if (I->LaneMask.none())
477     LiveIns.erase(I);
478 }
479 
480 MachineBasicBlock::livein_iterator
481 MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
482   // Get non-const version of iterator.
483   LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
484   return LiveIns.erase(LI);
485 }
486 
487 bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
488   livein_iterator I = find_if(
489       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
490   return I != livein_end() && (I->LaneMask & LaneMask).any();
491 }
492 
493 void MachineBasicBlock::sortUniqueLiveIns() {
494   llvm::sort(LiveIns,
495              [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
496                return LI0.PhysReg < LI1.PhysReg;
497              });
498   // Liveins are sorted by physreg now we can merge their lanemasks.
499   LiveInVector::const_iterator I = LiveIns.begin();
500   LiveInVector::const_iterator J;
501   LiveInVector::iterator Out = LiveIns.begin();
502   for (; I != LiveIns.end(); ++Out, I = J) {
503     MCRegister PhysReg = I->PhysReg;
504     LaneBitmask LaneMask = I->LaneMask;
505     for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
506       LaneMask |= J->LaneMask;
507     Out->PhysReg = PhysReg;
508     Out->LaneMask = LaneMask;
509   }
510   LiveIns.erase(Out, LiveIns.end());
511 }
512 
513 Register
514 MachineBasicBlock::addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC) {
515   assert(getParent() && "MBB must be inserted in function");
516   assert(PhysReg.isPhysical() && "Expected physreg");
517   assert(RC && "Register class is required");
518   assert((isEHPad() || this == &getParent()->front()) &&
519          "Only the entry block and landing pads can have physreg live ins");
520 
521   bool LiveIn = isLiveIn(PhysReg);
522   iterator I = SkipPHIsAndLabels(begin()), E = end();
523   MachineRegisterInfo &MRI = getParent()->getRegInfo();
524   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
525 
526   // Look for an existing copy.
527   if (LiveIn)
528     for (;I != E && I->isCopy(); ++I)
529       if (I->getOperand(1).getReg() == PhysReg) {
530         Register VirtReg = I->getOperand(0).getReg();
531         if (!MRI.constrainRegClass(VirtReg, RC))
532           llvm_unreachable("Incompatible live-in register class.");
533         return VirtReg;
534       }
535 
536   // No luck, create a virtual register.
537   Register VirtReg = MRI.createVirtualRegister(RC);
538   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
539     .addReg(PhysReg, RegState::Kill);
540   if (!LiveIn)
541     addLiveIn(PhysReg);
542   return VirtReg;
543 }
544 
545 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
546   getParent()->splice(NewAfter->getIterator(), getIterator());
547 }
548 
549 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
550   getParent()->splice(++NewBefore->getIterator(), getIterator());
551 }
552 
553 void MachineBasicBlock::updateTerminator() {
554   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
555   // A block with no successors has no concerns with fall-through edges.
556   if (this->succ_empty())
557     return;
558 
559   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
560   SmallVector<MachineOperand, 4> Cond;
561   DebugLoc DL = findBranchDebugLoc();
562   bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
563   (void) B;
564   assert(!B && "UpdateTerminators requires analyzable predecessors!");
565   if (Cond.empty()) {
566     if (TBB) {
567       // The block has an unconditional branch. If its successor is now its
568       // layout successor, delete the branch.
569       if (isLayoutSuccessor(TBB))
570         TII->removeBranch(*this);
571     } else {
572       // The block has an unconditional fallthrough. If its successor is not its
573       // layout successor, insert a branch. First we have to locate the only
574       // non-landing-pad successor, as that is the fallthrough block.
575       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
576         if ((*SI)->isEHPad())
577           continue;
578         assert(!TBB && "Found more than one non-landing-pad successor!");
579         TBB = *SI;
580       }
581 
582       // If there is no non-landing-pad successor, the block has no fall-through
583       // edges to be concerned with.
584       if (!TBB)
585         return;
586 
587       // Finally update the unconditional successor to be reached via a branch
588       // if it would not be reached by fallthrough.
589       if (!isLayoutSuccessor(TBB))
590         TII->insertBranch(*this, TBB, nullptr, Cond, DL);
591     }
592     return;
593   }
594 
595   if (FBB) {
596     // The block has a non-fallthrough conditional branch. If one of its
597     // successors is its layout successor, rewrite it to a fallthrough
598     // conditional branch.
599     if (isLayoutSuccessor(TBB)) {
600       if (TII->reverseBranchCondition(Cond))
601         return;
602       TII->removeBranch(*this);
603       TII->insertBranch(*this, FBB, nullptr, Cond, DL);
604     } else if (isLayoutSuccessor(FBB)) {
605       TII->removeBranch(*this);
606       TII->insertBranch(*this, TBB, nullptr, Cond, DL);
607     }
608     return;
609   }
610 
611   // Walk through the successors and find the successor which is not a landing
612   // pad and is not the conditional branch destination (in TBB) as the
613   // fallthrough successor.
614   MachineBasicBlock *FallthroughBB = nullptr;
615   for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
616     if ((*SI)->isEHPad() || *SI == TBB)
617       continue;
618     assert(!FallthroughBB && "Found more than one fallthrough successor.");
619     FallthroughBB = *SI;
620   }
621 
622   if (!FallthroughBB) {
623     if (canFallThrough()) {
624       // We fallthrough to the same basic block as the conditional jump targets.
625       // Remove the conditional jump, leaving unconditional fallthrough.
626       // FIXME: This does not seem like a reasonable pattern to support, but it
627       // has been seen in the wild coming out of degenerate ARM test cases.
628       TII->removeBranch(*this);
629 
630       // Finally update the unconditional successor to be reached via a branch if
631       // it would not be reached by fallthrough.
632       if (!isLayoutSuccessor(TBB))
633         TII->insertBranch(*this, TBB, nullptr, Cond, DL);
634       return;
635     }
636 
637     // We enter here iff exactly one successor is TBB which cannot fallthrough
638     // and the rest successors if any are EHPads.  In this case, we need to
639     // change the conditional branch into unconditional branch.
640     TII->removeBranch(*this);
641     Cond.clear();
642     TII->insertBranch(*this, TBB, nullptr, Cond, DL);
643     return;
644   }
645 
646   // The block has a fallthrough conditional branch.
647   if (isLayoutSuccessor(TBB)) {
648     if (TII->reverseBranchCondition(Cond)) {
649       // We can't reverse the condition, add an unconditional branch.
650       Cond.clear();
651       TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
652       return;
653     }
654     TII->removeBranch(*this);
655     TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
656   } else if (!isLayoutSuccessor(FallthroughBB)) {
657     TII->removeBranch(*this);
658     TII->insertBranch(*this, TBB, FallthroughBB, Cond, DL);
659   }
660 }
661 
662 void MachineBasicBlock::validateSuccProbs() const {
663 #ifndef NDEBUG
664   int64_t Sum = 0;
665   for (auto Prob : Probs)
666     Sum += Prob.getNumerator();
667   // Due to precision issue, we assume that the sum of probabilities is one if
668   // the difference between the sum of their numerators and the denominator is
669   // no greater than the number of successors.
670   assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
671              Probs.size() &&
672          "The sum of successors's probabilities exceeds one.");
673 #endif // NDEBUG
674 }
675 
676 void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
677                                      BranchProbability Prob) {
678   // Probability list is either empty (if successor list isn't empty, this means
679   // disabled optimization) or has the same size as successor list.
680   if (!(Probs.empty() && !Successors.empty()))
681     Probs.push_back(Prob);
682   Successors.push_back(Succ);
683   Succ->addPredecessor(this);
684 }
685 
686 void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
687   // We need to make sure probability list is either empty or has the same size
688   // of successor list. When this function is called, we can safely delete all
689   // probability in the list.
690   Probs.clear();
691   Successors.push_back(Succ);
692   Succ->addPredecessor(this);
693 }
694 
695 void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
696                                        MachineBasicBlock *New,
697                                        bool NormalizeSuccProbs) {
698   succ_iterator OldI = llvm::find(successors(), Old);
699   assert(OldI != succ_end() && "Old is not a successor of this block!");
700   assert(llvm::find(successors(), New) == succ_end() &&
701          "New is already a successor of this block!");
702 
703   // Add a new successor with equal probability as the original one. Note
704   // that we directly copy the probability using the iterator rather than
705   // getting a potentially synthetic probability computed when unknown. This
706   // preserves the probabilities as-is and then we can renormalize them and
707   // query them effectively afterward.
708   addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
709                                   : *getProbabilityIterator(OldI));
710   if (NormalizeSuccProbs)
711     normalizeSuccProbs();
712 }
713 
714 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
715                                         bool NormalizeSuccProbs) {
716   succ_iterator I = find(Successors, Succ);
717   removeSuccessor(I, NormalizeSuccProbs);
718 }
719 
720 MachineBasicBlock::succ_iterator
721 MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
722   assert(I != Successors.end() && "Not a current successor!");
723 
724   // If probability list is empty it means we don't use it (disabled
725   // optimization).
726   if (!Probs.empty()) {
727     probability_iterator WI = getProbabilityIterator(I);
728     Probs.erase(WI);
729     if (NormalizeSuccProbs)
730       normalizeSuccProbs();
731   }
732 
733   (*I)->removePredecessor(this);
734   return Successors.erase(I);
735 }
736 
737 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
738                                          MachineBasicBlock *New) {
739   if (Old == New)
740     return;
741 
742   succ_iterator E = succ_end();
743   succ_iterator NewI = E;
744   succ_iterator OldI = E;
745   for (succ_iterator I = succ_begin(); I != E; ++I) {
746     if (*I == Old) {
747       OldI = I;
748       if (NewI != E)
749         break;
750     }
751     if (*I == New) {
752       NewI = I;
753       if (OldI != E)
754         break;
755     }
756   }
757   assert(OldI != E && "Old is not a successor of this block");
758 
759   // If New isn't already a successor, let it take Old's place.
760   if (NewI == E) {
761     Old->removePredecessor(this);
762     New->addPredecessor(this);
763     *OldI = New;
764     return;
765   }
766 
767   // New is already a successor.
768   // Update its probability instead of adding a duplicate edge.
769   if (!Probs.empty()) {
770     auto ProbIter = getProbabilityIterator(NewI);
771     if (!ProbIter->isUnknown())
772       *ProbIter += *getProbabilityIterator(OldI);
773   }
774   removeSuccessor(OldI);
775 }
776 
777 void MachineBasicBlock::copySuccessor(MachineBasicBlock *Orig,
778                                       succ_iterator I) {
779   if (Orig->Probs.empty())
780     addSuccessor(*I, Orig->getSuccProbability(I));
781   else
782     addSuccessorWithoutProb(*I);
783 }
784 
785 void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
786   Predecessors.push_back(Pred);
787 }
788 
789 void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
790   pred_iterator I = find(Predecessors, Pred);
791   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
792   Predecessors.erase(I);
793 }
794 
795 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
796   if (this == FromMBB)
797     return;
798 
799   while (!FromMBB->succ_empty()) {
800     MachineBasicBlock *Succ = *FromMBB->succ_begin();
801 
802     // If probability list is empty it means we don't use it (disabled
803     // optimization).
804     if (!FromMBB->Probs.empty()) {
805       auto Prob = *FromMBB->Probs.begin();
806       addSuccessor(Succ, Prob);
807     } else
808       addSuccessorWithoutProb(Succ);
809 
810     FromMBB->removeSuccessor(Succ);
811   }
812 }
813 
814 void
815 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
816   if (this == FromMBB)
817     return;
818 
819   while (!FromMBB->succ_empty()) {
820     MachineBasicBlock *Succ = *FromMBB->succ_begin();
821     if (!FromMBB->Probs.empty()) {
822       auto Prob = *FromMBB->Probs.begin();
823       addSuccessor(Succ, Prob);
824     } else
825       addSuccessorWithoutProb(Succ);
826     FromMBB->removeSuccessor(Succ);
827 
828     // Fix up any PHI nodes in the successor.
829     Succ->replacePhiUsesWith(FromMBB, this);
830   }
831   normalizeSuccProbs();
832 }
833 
834 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
835   return is_contained(predecessors(), MBB);
836 }
837 
838 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
839   return is_contained(successors(), MBB);
840 }
841 
842 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
843   MachineFunction::const_iterator I(this);
844   return std::next(I) == MachineFunction::const_iterator(MBB);
845 }
846 
847 MachineBasicBlock *MachineBasicBlock::getFallThrough() {
848   MachineFunction::iterator Fallthrough = getIterator();
849   ++Fallthrough;
850   // If FallthroughBlock is off the end of the function, it can't fall through.
851   if (Fallthrough == getParent()->end())
852     return nullptr;
853 
854   // If FallthroughBlock isn't a successor, no fallthrough is possible.
855   if (!isSuccessor(&*Fallthrough))
856     return nullptr;
857 
858   // Analyze the branches, if any, at the end of the block.
859   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
860   SmallVector<MachineOperand, 4> Cond;
861   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
862   if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
863     // If we couldn't analyze the branch, examine the last instruction.
864     // If the block doesn't end in a known control barrier, assume fallthrough
865     // is possible. The isPredicated check is needed because this code can be
866     // called during IfConversion, where an instruction which is normally a
867     // Barrier is predicated and thus no longer an actual control barrier.
868     return (empty() || !back().isBarrier() || TII->isPredicated(back()))
869                ? &*Fallthrough
870                : nullptr;
871   }
872 
873   // If there is no branch, control always falls through.
874   if (!TBB) return &*Fallthrough;
875 
876   // If there is some explicit branch to the fallthrough block, it can obviously
877   // reach, even though the branch should get folded to fall through implicitly.
878   if (MachineFunction::iterator(TBB) == Fallthrough ||
879       MachineFunction::iterator(FBB) == Fallthrough)
880     return &*Fallthrough;
881 
882   // If it's an unconditional branch to some block not the fall through, it
883   // doesn't fall through.
884   if (Cond.empty()) return nullptr;
885 
886   // Otherwise, if it is conditional and has no explicit false block, it falls
887   // through.
888   return (FBB == nullptr) ? &*Fallthrough : nullptr;
889 }
890 
891 bool MachineBasicBlock::canFallThrough() {
892   return getFallThrough() != nullptr;
893 }
894 
895 MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
896     MachineBasicBlock *Succ, Pass &P,
897     std::vector<SparseBitVector<>> *LiveInSets) {
898   if (!canSplitCriticalEdge(Succ))
899     return nullptr;
900 
901   MachineFunction *MF = getParent();
902   DebugLoc DL;  // FIXME: this is nowhere
903 
904   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
905   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
906   LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
907                     << " -- " << printMBBReference(*NMBB) << " -- "
908                     << printMBBReference(*Succ) << '\n');
909 
910   LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
911   SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
912   if (LIS)
913     LIS->insertMBBInMaps(NMBB);
914   else if (Indexes)
915     Indexes->insertMBBInMaps(NMBB);
916 
917   // On some targets like Mips, branches may kill virtual registers. Make sure
918   // that LiveVariables is properly updated after updateTerminator replaces the
919   // terminators.
920   LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
921 
922   // Collect a list of virtual registers killed by the terminators.
923   SmallVector<Register, 4> KilledRegs;
924   if (LV)
925     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
926          I != E; ++I) {
927       MachineInstr *MI = &*I;
928       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
929            OE = MI->operands_end(); OI != OE; ++OI) {
930         if (!OI->isReg() || OI->getReg() == 0 ||
931             !OI->isUse() || !OI->isKill() || OI->isUndef())
932           continue;
933         Register Reg = OI->getReg();
934         if (Register::isPhysicalRegister(Reg) ||
935             LV->getVarInfo(Reg).removeKill(*MI)) {
936           KilledRegs.push_back(Reg);
937           LLVM_DEBUG(dbgs() << "Removing terminator kill: " << *MI);
938           OI->setIsKill(false);
939         }
940       }
941     }
942 
943   SmallVector<Register, 4> UsedRegs;
944   if (LIS) {
945     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
946          I != E; ++I) {
947       MachineInstr *MI = &*I;
948 
949       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
950            OE = MI->operands_end(); OI != OE; ++OI) {
951         if (!OI->isReg() || OI->getReg() == 0)
952           continue;
953 
954         Register Reg = OI->getReg();
955         if (!is_contained(UsedRegs, Reg))
956           UsedRegs.push_back(Reg);
957       }
958     }
959   }
960 
961   ReplaceUsesOfBlockWith(Succ, NMBB);
962 
963   // If updateTerminator() removes instructions, we need to remove them from
964   // SlotIndexes.
965   SmallVector<MachineInstr*, 4> Terminators;
966   if (Indexes) {
967     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
968          I != E; ++I)
969       Terminators.push_back(&*I);
970   }
971 
972   updateTerminator();
973 
974   if (Indexes) {
975     SmallVector<MachineInstr*, 4> NewTerminators;
976     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
977          I != E; ++I)
978       NewTerminators.push_back(&*I);
979 
980     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
981         E = Terminators.end(); I != E; ++I) {
982       if (!is_contained(NewTerminators, *I))
983         Indexes->removeMachineInstrFromMaps(**I);
984     }
985   }
986 
987   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
988   NMBB->addSuccessor(Succ);
989   if (!NMBB->isLayoutSuccessor(Succ)) {
990     SmallVector<MachineOperand, 4> Cond;
991     const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
992     TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
993 
994     if (Indexes) {
995       for (MachineInstr &MI : NMBB->instrs()) {
996         // Some instructions may have been moved to NMBB by updateTerminator(),
997         // so we first remove any instruction that already has an index.
998         if (Indexes->hasIndex(MI))
999           Indexes->removeMachineInstrFromMaps(MI);
1000         Indexes->insertMachineInstrInMaps(MI);
1001       }
1002     }
1003   }
1004 
1005   // Fix PHI nodes in Succ so they refer to NMBB instead of this.
1006   Succ->replacePhiUsesWith(this, NMBB);
1007 
1008   // Inherit live-ins from the successor
1009   for (const auto &LI : Succ->liveins())
1010     NMBB->addLiveIn(LI);
1011 
1012   // Update LiveVariables.
1013   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1014   if (LV) {
1015     // Restore kills of virtual registers that were killed by the terminators.
1016     while (!KilledRegs.empty()) {
1017       Register Reg = KilledRegs.pop_back_val();
1018       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
1019         if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false))
1020           continue;
1021         if (Register::isVirtualRegister(Reg))
1022           LV->getVarInfo(Reg).Kills.push_back(&*I);
1023         LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
1024         break;
1025       }
1026     }
1027     // Update relevant live-through information.
1028     if (LiveInSets != nullptr)
1029       LV->addNewBlock(NMBB, this, Succ, *LiveInSets);
1030     else
1031       LV->addNewBlock(NMBB, this, Succ);
1032   }
1033 
1034   if (LIS) {
1035     // After splitting the edge and updating SlotIndexes, live intervals may be
1036     // in one of two situations, depending on whether this block was the last in
1037     // the function. If the original block was the last in the function, all
1038     // live intervals will end prior to the beginning of the new split block. If
1039     // the original block was not at the end of the function, all live intervals
1040     // will extend to the end of the new split block.
1041 
1042     bool isLastMBB =
1043       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
1044 
1045     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
1046     SlotIndex PrevIndex = StartIndex.getPrevSlot();
1047     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
1048 
1049     // Find the registers used from NMBB in PHIs in Succ.
1050     SmallSet<Register, 8> PHISrcRegs;
1051     for (MachineBasicBlock::instr_iterator
1052          I = Succ->instr_begin(), E = Succ->instr_end();
1053          I != E && I->isPHI(); ++I) {
1054       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
1055         if (I->getOperand(ni+1).getMBB() == NMBB) {
1056           MachineOperand &MO = I->getOperand(ni);
1057           Register Reg = MO.getReg();
1058           PHISrcRegs.insert(Reg);
1059           if (MO.isUndef())
1060             continue;
1061 
1062           LiveInterval &LI = LIS->getInterval(Reg);
1063           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1064           assert(VNI &&
1065                  "PHI sources should be live out of their predecessors.");
1066           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1067         }
1068       }
1069     }
1070 
1071     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
1072     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1073       Register Reg = Register::index2VirtReg(i);
1074       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
1075         continue;
1076 
1077       LiveInterval &LI = LIS->getInterval(Reg);
1078       if (!LI.liveAt(PrevIndex))
1079         continue;
1080 
1081       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
1082       if (isLiveOut && isLastMBB) {
1083         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1084         assert(VNI && "LiveInterval should have VNInfo where it is live.");
1085         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1086       } else if (!isLiveOut && !isLastMBB) {
1087         LI.removeSegment(StartIndex, EndIndex);
1088       }
1089     }
1090 
1091     // Update all intervals for registers whose uses may have been modified by
1092     // updateTerminator().
1093     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
1094   }
1095 
1096   if (MachineDominatorTree *MDT =
1097           P.getAnalysisIfAvailable<MachineDominatorTree>())
1098     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
1099 
1100   if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
1101     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
1102       // If one or the other blocks were not in a loop, the new block is not
1103       // either, and thus LI doesn't need to be updated.
1104       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
1105         if (TIL == DestLoop) {
1106           // Both in the same loop, the NMBB joins loop.
1107           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1108         } else if (TIL->contains(DestLoop)) {
1109           // Edge from an outer loop to an inner loop.  Add to the outer loop.
1110           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
1111         } else if (DestLoop->contains(TIL)) {
1112           // Edge from an inner loop to an outer loop.  Add to the outer loop.
1113           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1114         } else {
1115           // Edge from two loops with no containment relation.  Because these
1116           // are natural loops, we know that the destination block must be the
1117           // header of its loop (adding a branch into a loop elsewhere would
1118           // create an irreducible loop).
1119           assert(DestLoop->getHeader() == Succ &&
1120                  "Should not create irreducible loops!");
1121           if (MachineLoop *P = DestLoop->getParentLoop())
1122             P->addBasicBlockToLoop(NMBB, MLI->getBase());
1123         }
1124       }
1125     }
1126 
1127   return NMBB;
1128 }
1129 
1130 bool MachineBasicBlock::canSplitCriticalEdge(
1131     const MachineBasicBlock *Succ) const {
1132   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1133   // it in this generic function.
1134   if (Succ->isEHPad())
1135     return false;
1136 
1137   // Splitting the critical edge to a callbr's indirect block isn't advised.
1138   // Don't do it in this generic function.
1139   if (isInlineAsmBrIndirectTarget(Succ))
1140     return false;
1141 
1142   const MachineFunction *MF = getParent();
1143   // Performance might be harmed on HW that implements branching using exec mask
1144   // where both sides of the branches are always executed.
1145   if (MF->getTarget().requiresStructuredCFG())
1146     return false;
1147 
1148   // We may need to update this's terminator, but we can't do that if
1149   // analyzeBranch fails. If this uses a jump table, we won't touch it.
1150   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1151   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1152   SmallVector<MachineOperand, 4> Cond;
1153   // AnalyzeBanch should modify this, since we did not allow modification.
1154   if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
1155                          /*AllowModify*/ false))
1156     return false;
1157 
1158   // Avoid bugpoint weirdness: A block may end with a conditional branch but
1159   // jumps to the same MBB is either case. We have duplicate CFG edges in that
1160   // case that we can't handle. Since this never happens in properly optimized
1161   // code, just skip those edges.
1162   if (TBB && TBB == FBB) {
1163     LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
1164                       << printMBBReference(*this) << '\n');
1165     return false;
1166   }
1167   return true;
1168 }
1169 
1170 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1171 /// neighboring instructions so the bundle won't be broken by removing MI.
1172 static void unbundleSingleMI(MachineInstr *MI) {
1173   // Removing the first instruction in a bundle.
1174   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1175     MI->unbundleFromSucc();
1176   // Removing the last instruction in a bundle.
1177   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1178     MI->unbundleFromPred();
1179   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1180   // are already fine.
1181 }
1182 
1183 MachineBasicBlock::instr_iterator
1184 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
1185   unbundleSingleMI(&*I);
1186   return Insts.erase(I);
1187 }
1188 
1189 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
1190   unbundleSingleMI(MI);
1191   MI->clearFlag(MachineInstr::BundledPred);
1192   MI->clearFlag(MachineInstr::BundledSucc);
1193   return Insts.remove(MI);
1194 }
1195 
1196 MachineBasicBlock::instr_iterator
1197 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1198   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1199          "Cannot insert instruction with bundle flags");
1200   // Set the bundle flags when inserting inside a bundle.
1201   if (I != instr_end() && I->isBundledWithPred()) {
1202     MI->setFlag(MachineInstr::BundledPred);
1203     MI->setFlag(MachineInstr::BundledSucc);
1204   }
1205   return Insts.insert(I, MI);
1206 }
1207 
1208 /// This method unlinks 'this' from the containing function, and returns it, but
1209 /// does not delete it.
1210 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1211   assert(getParent() && "Not embedded in a function!");
1212   getParent()->remove(this);
1213   return this;
1214 }
1215 
1216 /// This method unlinks 'this' from the containing function, and deletes it.
1217 void MachineBasicBlock::eraseFromParent() {
1218   assert(getParent() && "Not embedded in a function!");
1219   getParent()->erase(this);
1220 }
1221 
1222 /// Given a machine basic block that branched to 'Old', change the code and CFG
1223 /// so that it branches to 'New' instead.
1224 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1225                                                MachineBasicBlock *New) {
1226   assert(Old != New && "Cannot replace self with self!");
1227 
1228   MachineBasicBlock::instr_iterator I = instr_end();
1229   while (I != instr_begin()) {
1230     --I;
1231     if (!I->isTerminator()) break;
1232 
1233     // Scan the operands of this machine instruction, replacing any uses of Old
1234     // with New.
1235     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1236       if (I->getOperand(i).isMBB() &&
1237           I->getOperand(i).getMBB() == Old)
1238         I->getOperand(i).setMBB(New);
1239   }
1240 
1241   // Update the successor information.
1242   replaceSuccessor(Old, New);
1243 }
1244 
1245 void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old,
1246                                            MachineBasicBlock *New) {
1247   for (MachineInstr &MI : phis())
1248     for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
1249       MachineOperand &MO = MI.getOperand(i);
1250       if (MO.getMBB() == Old)
1251         MO.setMBB(New);
1252     }
1253 }
1254 
1255 /// Various pieces of code can cause excess edges in the CFG to be inserted.  If
1256 /// we have proven that MBB can only branch to DestA and DestB, remove any other
1257 /// MBB successors from the CFG.  DestA and DestB can be null.
1258 ///
1259 /// Besides DestA and DestB, retain other edges leading to LandingPads
1260 /// (currently there can be only one; we don't check or require that here).
1261 /// Note it is possible that DestA and/or DestB are LandingPads.
1262 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1263                                              MachineBasicBlock *DestB,
1264                                              bool IsCond) {
1265   // The values of DestA and DestB frequently come from a call to the
1266   // 'TargetInstrInfo::analyzeBranch' method. We take our meaning of the initial
1267   // values from there.
1268   //
1269   // 1. If both DestA and DestB are null, then the block ends with no branches
1270   //    (it falls through to its successor).
1271   // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends
1272   //    with only an unconditional branch.
1273   // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends
1274   //    with a conditional branch that falls through to a successor (DestB).
1275   // 4. If DestA and DestB is set and IsCond is true, then the block ends with a
1276   //    conditional branch followed by an unconditional branch. DestA is the
1277   //    'true' destination and DestB is the 'false' destination.
1278 
1279   bool Changed = false;
1280 
1281   MachineBasicBlock *FallThru = getNextNode();
1282 
1283   if (!DestA && !DestB) {
1284     // Block falls through to successor.
1285     DestA = FallThru;
1286     DestB = FallThru;
1287   } else if (DestA && !DestB) {
1288     if (IsCond)
1289       // Block ends in conditional jump that falls through to successor.
1290       DestB = FallThru;
1291   } else {
1292     assert(DestA && DestB && IsCond &&
1293            "CFG in a bad state. Cannot correct CFG edges");
1294   }
1295 
1296   // Remove superfluous edges. I.e., those which aren't destinations of this
1297   // basic block, duplicate edges, or landing pads.
1298   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1299   MachineBasicBlock::succ_iterator SI = succ_begin();
1300   while (SI != succ_end()) {
1301     const MachineBasicBlock *MBB = *SI;
1302     if (!SeenMBBs.insert(MBB).second ||
1303         (MBB != DestA && MBB != DestB && !MBB->isEHPad())) {
1304       // This is a superfluous edge, remove it.
1305       SI = removeSuccessor(SI);
1306       Changed = true;
1307     } else {
1308       ++SI;
1309     }
1310   }
1311 
1312   if (Changed)
1313     normalizeSuccProbs();
1314   return Changed;
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