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>
38using namespace llvm;
39
40#define DEBUG_TYPE "codegen"
41
42static 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
48MachineBasicBlock::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
55MachineBasicBlock::~MachineBasicBlock() {
56}
57
58/// Return the MCSymbol for this basic block.
59MCSymbol *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
104raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
105  MBB.print(OS);
106  return OS;
107}
108
109Printable 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.
120void 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
132void 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.
140void 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.
153void 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.
167void 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
185void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
186  assert(!MI->getParent() && "MI is still in a block!");
187  Parent->getParent()->DeleteMachineInstr(MI);
188}
189
190MachineBasicBlock::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
199MachineBasicBlock::iterator
200MachineBasicBlock::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
214MachineBasicBlock::iterator
215MachineBasicBlock::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
230MachineBasicBlock::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
239MachineBasicBlock::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
248MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() {
249  // Skip over begin-of-block dbg_value instructions.
250  return skipDebugInstructionsForward(begin(), end());
251}
252
253MachineBasicBlock::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
267bool 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)
275LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
276  print(dbgs());
277}
278#endif
279
280bool MachineBasicBlock::mayHaveInlineAsmBr() const {
281  for (const MachineBasicBlock *Succ : successors()) {
282    if (Succ->isInlineAsmBrIndirectTarget())
283      return true;
284  }
285  return false;
286}
287
288bool MachineBasicBlock::isLegalToHoistInto() const {
289  if (isReturnBlock() || hasEHPadSuccessor() || mayHaveInlineAsmBr())
290    return false;
291  return true;
292}
293
294StringRef 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.
302std::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
313void 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
328void 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  OS << "bb." << getNumber();
342  bool HasAttributes = false;
343  if (const auto *BB = getBasicBlock()) {
344    if (BB->hasName()) {
345      OS << "." << BB->getName();
346    } else {
347      HasAttributes = true;
348      OS << " (";
349      int Slot = MST.getLocalSlot(BB);
350      if (Slot == -1)
351        OS << "<ir-block badref>";
352      else
353        OS << (Twine("%ir-block.") + Twine(Slot)).str();
354    }
355  }
356
357  if (hasAddressTaken()) {
358    OS << (HasAttributes ? ", " : " (");
359    OS << "address-taken";
360    HasAttributes = true;
361  }
362  if (isEHPad()) {
363    OS << (HasAttributes ? ", " : " (");
364    OS << "landing-pad";
365    HasAttributes = true;
366  }
367  if (getAlignment() != Align(1)) {
368    OS << (HasAttributes ? ", " : " (");
369    OS << "align " << Log2(getAlignment());
370    HasAttributes = true;
371  }
372  if (HasAttributes)
373    OS << ")";
374  OS << ":\n";
375
376  const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
377  const MachineRegisterInfo &MRI = MF->getRegInfo();
378  const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
379  bool HasLineAttributes = false;
380
381  // Print the preds of this block according to the CFG.
382  if (!pred_empty() && IsStandalone) {
383    if (Indexes) OS << '\t';
384    // Don't indent(2), align with previous line attributes.
385    OS << "; predecessors: ";
386    for (auto I = pred_begin(), E = pred_end(); I != E; ++I) {
387      if (I != pred_begin())
388        OS << ", ";
389      OS << printMBBReference(**I);
390    }
391    OS << '\n';
392    HasLineAttributes = true;
393  }
394
395  if (!succ_empty()) {
396    if (Indexes) OS << '\t';
397    // Print the successors
398    OS.indent(2) << "successors: ";
399    for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
400      if (I != succ_begin())
401        OS << ", ";
402      OS << printMBBReference(**I);
403      if (!Probs.empty())
404        OS << '('
405           << format("0x%08" PRIx32, getSuccProbability(I).getNumerator())
406           << ')';
407    }
408    if (!Probs.empty() && IsStandalone) {
409      // Print human readable probabilities as comments.
410      OS << "; ";
411      for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
412        const BranchProbability &BP = getSuccProbability(I);
413        if (I != succ_begin())
414          OS << ", ";
415        OS << printMBBReference(**I) << '('
416           << format("%.2f%%",
417                     rint(((double)BP.getNumerator() / BP.getDenominator()) *
418                          100.0 * 100.0) /
419                         100.0)
420           << ')';
421      }
422    }
423
424    OS << '\n';
425    HasLineAttributes = true;
426  }
427
428  if (!livein_empty() && MRI.tracksLiveness()) {
429    if (Indexes) OS << '\t';
430    OS.indent(2) << "liveins: ";
431
432    bool First = true;
433    for (const auto &LI : liveins()) {
434      if (!First)
435        OS << ", ";
436      First = false;
437      OS << printReg(LI.PhysReg, TRI);
438      if (!LI.LaneMask.all())
439        OS << ":0x" << PrintLaneMask(LI.LaneMask);
440    }
441    HasLineAttributes = true;
442  }
443
444  if (HasLineAttributes)
445    OS << '\n';
446
447  bool IsInBundle = false;
448  for (const MachineInstr &MI : instrs()) {
449    if (Indexes && PrintSlotIndexes) {
450      if (Indexes->hasIndex(MI))
451        OS << Indexes->getInstructionIndex(MI);
452      OS << '\t';
453    }
454
455    if (IsInBundle && !MI.isInsideBundle()) {
456      OS.indent(2) << "}\n";
457      IsInBundle = false;
458    }
459
460    OS.indent(IsInBundle ? 4 : 2);
461    MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
462             /*AddNewLine=*/false, &TII);
463
464    if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
465      OS << " {";
466      IsInBundle = true;
467    }
468    OS << '\n';
469  }
470
471  if (IsInBundle)
472    OS.indent(2) << "}\n";
473
474  if (IrrLoopHeaderWeight && IsStandalone) {
475    if (Indexes) OS << '\t';
476    OS.indent(2) << "; Irreducible loop header weight: "
477                 << IrrLoopHeaderWeight.getValue() << '\n';
478  }
479}
480
481void MachineBasicBlock::printAsOperand(raw_ostream &OS,
482                                       bool /*PrintType*/) const {
483  OS << "%bb." << getNumber();
484}
485
486void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
487  LiveInVector::iterator I = find_if(
488      LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
489  if (I == LiveIns.end())
490    return;
491
492  I->LaneMask &= ~LaneMask;
493  if (I->LaneMask.none())
494    LiveIns.erase(I);
495}
496
497MachineBasicBlock::livein_iterator
498MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
499  // Get non-const version of iterator.
500  LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
501  return LiveIns.erase(LI);
502}
503
504bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
505  livein_iterator I = find_if(
506      LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
507  return I != livein_end() && (I->LaneMask & LaneMask).any();
508}
509
510void MachineBasicBlock::sortUniqueLiveIns() {
511  llvm::sort(LiveIns,
512             [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
513               return LI0.PhysReg < LI1.PhysReg;
514             });
515  // Liveins are sorted by physreg now we can merge their lanemasks.
516  LiveInVector::const_iterator I = LiveIns.begin();
517  LiveInVector::const_iterator J;
518  LiveInVector::iterator Out = LiveIns.begin();
519  for (; I != LiveIns.end(); ++Out, I = J) {
520    MCRegister PhysReg = I->PhysReg;
521    LaneBitmask LaneMask = I->LaneMask;
522    for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
523      LaneMask |= J->LaneMask;
524    Out->PhysReg = PhysReg;
525    Out->LaneMask = LaneMask;
526  }
527  LiveIns.erase(Out, LiveIns.end());
528}
529
530Register
531MachineBasicBlock::addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC) {
532  assert(getParent() && "MBB must be inserted in function");
533  assert(PhysReg.isPhysical() && "Expected physreg");
534  assert(RC && "Register class is required");
535  assert((isEHPad() || this == &getParent()->front()) &&
536         "Only the entry block and landing pads can have physreg live ins");
537
538  bool LiveIn = isLiveIn(PhysReg);
539  iterator I = SkipPHIsAndLabels(begin()), E = end();
540  MachineRegisterInfo &MRI = getParent()->getRegInfo();
541  const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
542
543  // Look for an existing copy.
544  if (LiveIn)
545    for (;I != E && I->isCopy(); ++I)
546      if (I->getOperand(1).getReg() == PhysReg) {
547        Register VirtReg = I->getOperand(0).getReg();
548        if (!MRI.constrainRegClass(VirtReg, RC))
549          llvm_unreachable("Incompatible live-in register class.");
550        return VirtReg;
551      }
552
553  // No luck, create a virtual register.
554  Register VirtReg = MRI.createVirtualRegister(RC);
555  BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
556    .addReg(PhysReg, RegState::Kill);
557  if (!LiveIn)
558    addLiveIn(PhysReg);
559  return VirtReg;
560}
561
562void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
563  getParent()->splice(NewAfter->getIterator(), getIterator());
564}
565
566void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
567  getParent()->splice(++NewBefore->getIterator(), getIterator());
568}
569
570void MachineBasicBlock::updateTerminator(
571    MachineBasicBlock *PreviousLayoutSuccessor) {
572  LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
573                    << "\n");
574
575  const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
576  // A block with no successors has no concerns with fall-through edges.
577  if (this->succ_empty())
578    return;
579
580  MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
581  SmallVector<MachineOperand, 4> Cond;
582  DebugLoc DL = findBranchDebugLoc();
583  bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
584  (void) B;
585  assert(!B && "UpdateTerminators requires analyzable predecessors!");
586  if (Cond.empty()) {
587    if (TBB) {
588      // The block has an unconditional branch. If its successor is now its
589      // layout successor, delete the branch.
590      if (isLayoutSuccessor(TBB))
591        TII->removeBranch(*this);
592    } else {
593      // The block has an unconditional fallthrough, or the end of the block is
594      // unreachable.
595
596      // Unfortunately, whether the end of the block is unreachable is not
597      // immediately obvious; we must fall back to checking the successor list,
598      // and assuming that if the passed in block is in the succesor list and
599      // not an EHPad, it must be the intended target.
600      if (!PreviousLayoutSuccessor || !isSuccessor(PreviousLayoutSuccessor) ||
601          PreviousLayoutSuccessor->isEHPad())
602        return;
603
604      // If the unconditional successor block is not the current layout
605      // successor, insert a branch to jump to it.
606      if (!isLayoutSuccessor(PreviousLayoutSuccessor))
607        TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
608    }
609    return;
610  }
611
612  if (FBB) {
613    // The block has a non-fallthrough conditional branch. If one of its
614    // successors is its layout successor, rewrite it to a fallthrough
615    // conditional branch.
616    if (isLayoutSuccessor(TBB)) {
617      if (TII->reverseBranchCondition(Cond))
618        return;
619      TII->removeBranch(*this);
620      TII->insertBranch(*this, FBB, nullptr, Cond, DL);
621    } else if (isLayoutSuccessor(FBB)) {
622      TII->removeBranch(*this);
623      TII->insertBranch(*this, TBB, nullptr, Cond, DL);
624    }
625    return;
626  }
627
628  // We now know we're going to fallthrough to PreviousLayoutSuccessor.
629  assert(PreviousLayoutSuccessor);
630  assert(!PreviousLayoutSuccessor->isEHPad());
631  assert(isSuccessor(PreviousLayoutSuccessor));
632
633  if (PreviousLayoutSuccessor == TBB) {
634    // We had a fallthrough to the same basic block as the conditional jump
635    // targets.  Remove the conditional jump, leaving an unconditional
636    // fallthrough or an unconditional jump.
637    TII->removeBranch(*this);
638    if (!isLayoutSuccessor(TBB)) {
639      Cond.clear();
640      TII->insertBranch(*this, TBB, nullptr, Cond, DL);
641    }
642    return;
643  }
644
645  // The block has a fallthrough conditional branch.
646  if (isLayoutSuccessor(TBB)) {
647    if (TII->reverseBranchCondition(Cond)) {
648      // We can't reverse the condition, add an unconditional branch.
649      Cond.clear();
650      TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
651      return;
652    }
653    TII->removeBranch(*this);
654    TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
655  } else if (!isLayoutSuccessor(PreviousLayoutSuccessor)) {
656    TII->removeBranch(*this);
657    TII->insertBranch(*this, TBB, PreviousLayoutSuccessor, Cond, DL);
658  }
659}
660
661void MachineBasicBlock::validateSuccProbs() const {
662#ifndef NDEBUG
663  int64_t Sum = 0;
664  for (auto Prob : Probs)
665    Sum += Prob.getNumerator();
666  // Due to precision issue, we assume that the sum of probabilities is one if
667  // the difference between the sum of their numerators and the denominator is
668  // no greater than the number of successors.
669  assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
670             Probs.size() &&
671         "The sum of successors's probabilities exceeds one.");
672#endif // NDEBUG
673}
674
675void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
676                                     BranchProbability Prob) {
677  // Probability list is either empty (if successor list isn't empty, this means
678  // disabled optimization) or has the same size as successor list.
679  if (!(Probs.empty() && !Successors.empty()))
680    Probs.push_back(Prob);
681  Successors.push_back(Succ);
682  Succ->addPredecessor(this);
683}
684
685void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
686  // We need to make sure probability list is either empty or has the same size
687  // of successor list. When this function is called, we can safely delete all
688  // probability in the list.
689  Probs.clear();
690  Successors.push_back(Succ);
691  Succ->addPredecessor(this);
692}
693
694void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
695                                       MachineBasicBlock *New,
696                                       bool NormalizeSuccProbs) {
697  succ_iterator OldI = llvm::find(successors(), Old);
698  assert(OldI != succ_end() && "Old is not a successor of this block!");
699  assert(llvm::find(successors(), New) == succ_end() &&
700         "New is already a successor of this block!");
701
702  // Add a new successor with equal probability as the original one. Note
703  // that we directly copy the probability using the iterator rather than
704  // getting a potentially synthetic probability computed when unknown. This
705  // preserves the probabilities as-is and then we can renormalize them and
706  // query them effectively afterward.
707  addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
708                                  : *getProbabilityIterator(OldI));
709  if (NormalizeSuccProbs)
710    normalizeSuccProbs();
711}
712
713void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
714                                        bool NormalizeSuccProbs) {
715  succ_iterator I = find(Successors, Succ);
716  removeSuccessor(I, NormalizeSuccProbs);
717}
718
719MachineBasicBlock::succ_iterator
720MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
721  assert(I != Successors.end() && "Not a current successor!");
722
723  // If probability list is empty it means we don't use it (disabled
724  // optimization).
725  if (!Probs.empty()) {
726    probability_iterator WI = getProbabilityIterator(I);
727    Probs.erase(WI);
728    if (NormalizeSuccProbs)
729      normalizeSuccProbs();
730  }
731
732  (*I)->removePredecessor(this);
733  return Successors.erase(I);
734}
735
736void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
737                                         MachineBasicBlock *New) {
738  if (Old == New)
739    return;
740
741  succ_iterator E = succ_end();
742  succ_iterator NewI = E;
743  succ_iterator OldI = E;
744  for (succ_iterator I = succ_begin(); I != E; ++I) {
745    if (*I == Old) {
746      OldI = I;
747      if (NewI != E)
748        break;
749    }
750    if (*I == New) {
751      NewI = I;
752      if (OldI != E)
753        break;
754    }
755  }
756  assert(OldI != E && "Old is not a successor of this block");
757
758  // If New isn't already a successor, let it take Old's place.
759  if (NewI == E) {
760    Old->removePredecessor(this);
761    New->addPredecessor(this);
762    *OldI = New;
763    return;
764  }
765
766  // New is already a successor.
767  // Update its probability instead of adding a duplicate edge.
768  if (!Probs.empty()) {
769    auto ProbIter = getProbabilityIterator(NewI);
770    if (!ProbIter->isUnknown())
771      *ProbIter += *getProbabilityIterator(OldI);
772  }
773  removeSuccessor(OldI);
774}
775
776void MachineBasicBlock::copySuccessor(MachineBasicBlock *Orig,
777                                      succ_iterator I) {
778  if (Orig->Probs.empty())
779    addSuccessor(*I, Orig->getSuccProbability(I));
780  else
781    addSuccessorWithoutProb(*I);
782}
783
784void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
785  Predecessors.push_back(Pred);
786}
787
788void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
789  pred_iterator I = find(Predecessors, Pred);
790  assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
791  Predecessors.erase(I);
792}
793
794void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
795  if (this == FromMBB)
796    return;
797
798  while (!FromMBB->succ_empty()) {
799    MachineBasicBlock *Succ = *FromMBB->succ_begin();
800
801    // If probability list is empty it means we don't use it (disabled
802    // optimization).
803    if (!FromMBB->Probs.empty()) {
804      auto Prob = *FromMBB->Probs.begin();
805      addSuccessor(Succ, Prob);
806    } else
807      addSuccessorWithoutProb(Succ);
808
809    FromMBB->removeSuccessor(Succ);
810  }
811}
812
813void
814MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
815  if (this == FromMBB)
816    return;
817
818  while (!FromMBB->succ_empty()) {
819    MachineBasicBlock *Succ = *FromMBB->succ_begin();
820    if (!FromMBB->Probs.empty()) {
821      auto Prob = *FromMBB->Probs.begin();
822      addSuccessor(Succ, Prob);
823    } else
824      addSuccessorWithoutProb(Succ);
825    FromMBB->removeSuccessor(Succ);
826
827    // Fix up any PHI nodes in the successor.
828    Succ->replacePhiUsesWith(FromMBB, this);
829  }
830  normalizeSuccProbs();
831}
832
833bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
834  return is_contained(predecessors(), MBB);
835}
836
837bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
838  return is_contained(successors(), MBB);
839}
840
841bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
842  MachineFunction::const_iterator I(this);
843  return std::next(I) == MachineFunction::const_iterator(MBB);
844}
845
846MachineBasicBlock *MachineBasicBlock::getFallThrough() {
847  MachineFunction::iterator Fallthrough = getIterator();
848  ++Fallthrough;
849  // If FallthroughBlock is off the end of the function, it can't fall through.
850  if (Fallthrough == getParent()->end())
851    return nullptr;
852
853  // If FallthroughBlock isn't a successor, no fallthrough is possible.
854  if (!isSuccessor(&*Fallthrough))
855    return nullptr;
856
857  // Analyze the branches, if any, at the end of the block.
858  MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
859  SmallVector<MachineOperand, 4> Cond;
860  const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
861  if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
862    // If we couldn't analyze the branch, examine the last instruction.
863    // If the block doesn't end in a known control barrier, assume fallthrough
864    // is possible. The isPredicated check is needed because this code can be
865    // called during IfConversion, where an instruction which is normally a
866    // Barrier is predicated and thus no longer an actual control barrier.
867    return (empty() || !back().isBarrier() || TII->isPredicated(back()))
868               ? &*Fallthrough
869               : nullptr;
870  }
871
872  // If there is no branch, control always falls through.
873  if (!TBB) return &*Fallthrough;
874
875  // If there is some explicit branch to the fallthrough block, it can obviously
876  // reach, even though the branch should get folded to fall through implicitly.
877  if (MachineFunction::iterator(TBB) == Fallthrough ||
878      MachineFunction::iterator(FBB) == Fallthrough)
879    return &*Fallthrough;
880
881  // If it's an unconditional branch to some block not the fall through, it
882  // doesn't fall through.
883  if (Cond.empty()) return nullptr;
884
885  // Otherwise, if it is conditional and has no explicit false block, it falls
886  // through.
887  return (FBB == nullptr) ? &*Fallthrough : nullptr;
888}
889
890bool MachineBasicBlock::canFallThrough() {
891  return getFallThrough() != nullptr;
892}
893
894MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
895    MachineBasicBlock *Succ, Pass &P,
896    std::vector<SparseBitVector<>> *LiveInSets) {
897  if (!canSplitCriticalEdge(Succ))
898    return nullptr;
899
900  MachineFunction *MF = getParent();
901  MachineBasicBlock *PrevFallthrough = getNextNode();
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  // Since we replaced all uses of Succ with NMBB, that should also be treated
973  // as the fallthrough successor
974  if (Succ == PrevFallthrough)
975    PrevFallthrough = NMBB;
976  updateTerminator(PrevFallthrough);
977
978  if (Indexes) {
979    SmallVector<MachineInstr*, 4> NewTerminators;
980    for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
981         I != E; ++I)
982      NewTerminators.push_back(&*I);
983
984    for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
985        E = Terminators.end(); I != E; ++I) {
986      if (!is_contained(NewTerminators, *I))
987        Indexes->removeMachineInstrFromMaps(**I);
988    }
989  }
990
991  // Insert unconditional "jump Succ" instruction in NMBB if necessary.
992  NMBB->addSuccessor(Succ);
993  if (!NMBB->isLayoutSuccessor(Succ)) {
994    SmallVector<MachineOperand, 4> Cond;
995    const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
996    TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
997
998    if (Indexes) {
999      for (MachineInstr &MI : NMBB->instrs()) {
1000        // Some instructions may have been moved to NMBB by updateTerminator(),
1001        // so we first remove any instruction that already has an index.
1002        if (Indexes->hasIndex(MI))
1003          Indexes->removeMachineInstrFromMaps(MI);
1004        Indexes->insertMachineInstrInMaps(MI);
1005      }
1006    }
1007  }
1008
1009  // Fix PHI nodes in Succ so they refer to NMBB instead of this.
1010  Succ->replacePhiUsesWith(this, NMBB);
1011
1012  // Inherit live-ins from the successor
1013  for (const auto &LI : Succ->liveins())
1014    NMBB->addLiveIn(LI);
1015
1016  // Update LiveVariables.
1017  const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1018  if (LV) {
1019    // Restore kills of virtual registers that were killed by the terminators.
1020    while (!KilledRegs.empty()) {
1021      Register Reg = KilledRegs.pop_back_val();
1022      for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
1023        if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false))
1024          continue;
1025        if (Register::isVirtualRegister(Reg))
1026          LV->getVarInfo(Reg).Kills.push_back(&*I);
1027        LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
1028        break;
1029      }
1030    }
1031    // Update relevant live-through information.
1032    if (LiveInSets != nullptr)
1033      LV->addNewBlock(NMBB, this, Succ, *LiveInSets);
1034    else
1035      LV->addNewBlock(NMBB, this, Succ);
1036  }
1037
1038  if (LIS) {
1039    // After splitting the edge and updating SlotIndexes, live intervals may be
1040    // in one of two situations, depending on whether this block was the last in
1041    // the function. If the original block was the last in the function, all
1042    // live intervals will end prior to the beginning of the new split block. If
1043    // the original block was not at the end of the function, all live intervals
1044    // will extend to the end of the new split block.
1045
1046    bool isLastMBB =
1047      std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
1048
1049    SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
1050    SlotIndex PrevIndex = StartIndex.getPrevSlot();
1051    SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
1052
1053    // Find the registers used from NMBB in PHIs in Succ.
1054    SmallSet<Register, 8> PHISrcRegs;
1055    for (MachineBasicBlock::instr_iterator
1056         I = Succ->instr_begin(), E = Succ->instr_end();
1057         I != E && I->isPHI(); ++I) {
1058      for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
1059        if (I->getOperand(ni+1).getMBB() == NMBB) {
1060          MachineOperand &MO = I->getOperand(ni);
1061          Register Reg = MO.getReg();
1062          PHISrcRegs.insert(Reg);
1063          if (MO.isUndef())
1064            continue;
1065
1066          LiveInterval &LI = LIS->getInterval(Reg);
1067          VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1068          assert(VNI &&
1069                 "PHI sources should be live out of their predecessors.");
1070          LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1071        }
1072      }
1073    }
1074
1075    MachineRegisterInfo *MRI = &getParent()->getRegInfo();
1076    for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1077      Register Reg = Register::index2VirtReg(i);
1078      if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
1079        continue;
1080
1081      LiveInterval &LI = LIS->getInterval(Reg);
1082      if (!LI.liveAt(PrevIndex))
1083        continue;
1084
1085      bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
1086      if (isLiveOut && isLastMBB) {
1087        VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1088        assert(VNI && "LiveInterval should have VNInfo where it is live.");
1089        LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1090      } else if (!isLiveOut && !isLastMBB) {
1091        LI.removeSegment(StartIndex, EndIndex);
1092      }
1093    }
1094
1095    // Update all intervals for registers whose uses may have been modified by
1096    // updateTerminator().
1097    LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
1098  }
1099
1100  if (MachineDominatorTree *MDT =
1101          P.getAnalysisIfAvailable<MachineDominatorTree>())
1102    MDT->recordSplitCriticalEdge(this, Succ, NMBB);
1103
1104  if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
1105    if (MachineLoop *TIL = MLI->getLoopFor(this)) {
1106      // If one or the other blocks were not in a loop, the new block is not
1107      // either, and thus LI doesn't need to be updated.
1108      if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
1109        if (TIL == DestLoop) {
1110          // Both in the same loop, the NMBB joins loop.
1111          DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1112        } else if (TIL->contains(DestLoop)) {
1113          // Edge from an outer loop to an inner loop.  Add to the outer loop.
1114          TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
1115        } else if (DestLoop->contains(TIL)) {
1116          // Edge from an inner loop to an outer loop.  Add to the outer loop.
1117          DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1118        } else {
1119          // Edge from two loops with no containment relation.  Because these
1120          // are natural loops, we know that the destination block must be the
1121          // header of its loop (adding a branch into a loop elsewhere would
1122          // create an irreducible loop).
1123          assert(DestLoop->getHeader() == Succ &&
1124                 "Should not create irreducible loops!");
1125          if (MachineLoop *P = DestLoop->getParentLoop())
1126            P->addBasicBlockToLoop(NMBB, MLI->getBase());
1127        }
1128      }
1129    }
1130
1131  return NMBB;
1132}
1133
1134bool MachineBasicBlock::canSplitCriticalEdge(
1135    const MachineBasicBlock *Succ) const {
1136  // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1137  // it in this generic function.
1138  if (Succ->isEHPad())
1139    return false;
1140
1141  // Splitting the critical edge to a callbr's indirect block isn't advised.
1142  // Don't do it in this generic function.
1143  if (Succ->isInlineAsmBrIndirectTarget())
1144    return false;
1145
1146  const MachineFunction *MF = getParent();
1147  // Performance might be harmed on HW that implements branching using exec mask
1148  // where both sides of the branches are always executed.
1149  if (MF->getTarget().requiresStructuredCFG())
1150    return false;
1151
1152  // We may need to update this's terminator, but we can't do that if
1153  // analyzeBranch fails. If this uses a jump table, we won't touch it.
1154  const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1155  MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1156  SmallVector<MachineOperand, 4> Cond;
1157  // AnalyzeBanch should modify this, since we did not allow modification.
1158  if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
1159                         /*AllowModify*/ false))
1160    return false;
1161
1162  // Avoid bugpoint weirdness: A block may end with a conditional branch but
1163  // jumps to the same MBB is either case. We have duplicate CFG edges in that
1164  // case that we can't handle. Since this never happens in properly optimized
1165  // code, just skip those edges.
1166  if (TBB && TBB == FBB) {
1167    LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
1168                      << printMBBReference(*this) << '\n');
1169    return false;
1170  }
1171  return true;
1172}
1173
1174/// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1175/// neighboring instructions so the bundle won't be broken by removing MI.
1176static void unbundleSingleMI(MachineInstr *MI) {
1177  // Removing the first instruction in a bundle.
1178  if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1179    MI->unbundleFromSucc();
1180  // Removing the last instruction in a bundle.
1181  if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1182    MI->unbundleFromPred();
1183  // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1184  // are already fine.
1185}
1186
1187MachineBasicBlock::instr_iterator
1188MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
1189  unbundleSingleMI(&*I);
1190  return Insts.erase(I);
1191}
1192
1193MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
1194  unbundleSingleMI(MI);
1195  MI->clearFlag(MachineInstr::BundledPred);
1196  MI->clearFlag(MachineInstr::BundledSucc);
1197  return Insts.remove(MI);
1198}
1199
1200MachineBasicBlock::instr_iterator
1201MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1202  assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1203         "Cannot insert instruction with bundle flags");
1204  // Set the bundle flags when inserting inside a bundle.
1205  if (I != instr_end() && I->isBundledWithPred()) {
1206    MI->setFlag(MachineInstr::BundledPred);
1207    MI->setFlag(MachineInstr::BundledSucc);
1208  }
1209  return Insts.insert(I, MI);
1210}
1211
1212/// This method unlinks 'this' from the containing function, and returns it, but
1213/// does not delete it.
1214MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1215  assert(getParent() && "Not embedded in a function!");
1216  getParent()->remove(this);
1217  return this;
1218}
1219
1220/// This method unlinks 'this' from the containing function, and deletes it.
1221void MachineBasicBlock::eraseFromParent() {
1222  assert(getParent() && "Not embedded in a function!");
1223  getParent()->erase(this);
1224}
1225
1226/// Given a machine basic block that branched to 'Old', change the code and CFG
1227/// so that it branches to 'New' instead.
1228void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1229                                               MachineBasicBlock *New) {
1230  assert(Old != New && "Cannot replace self with self!");
1231
1232  MachineBasicBlock::instr_iterator I = instr_end();
1233  while (I != instr_begin()) {
1234    --I;
1235    if (!I->isTerminator()) break;
1236
1237    // Scan the operands of this machine instruction, replacing any uses of Old
1238    // with New.
1239    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1240      if (I->getOperand(i).isMBB() &&
1241          I->getOperand(i).getMBB() == Old)
1242        I->getOperand(i).setMBB(New);
1243  }
1244
1245  // Update the successor information.
1246  replaceSuccessor(Old, New);
1247}
1248
1249void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old,
1250                                           MachineBasicBlock *New) {
1251  for (MachineInstr &MI : phis())
1252    for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
1253      MachineOperand &MO = MI.getOperand(i);
1254      if (MO.getMBB() == Old)
1255        MO.setMBB(New);
1256    }
1257}
1258
1259/// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
1260/// instructions.  Return UnknownLoc if there is none.
1261DebugLoc
1262MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1263  // Skip debug declarations, we don't want a DebugLoc from them.
1264  MBBI = skipDebugInstructionsForward(MBBI, instr_end());
1265  if (MBBI != instr_end())
1266    return MBBI->getDebugLoc();
1267  return {};
1268}
1269
1270/// Find the previous valid DebugLoc preceding MBBI, skipping and DBG_VALUE
1271/// instructions.  Return UnknownLoc if there is none.
1272DebugLoc MachineBasicBlock::findPrevDebugLoc(instr_iterator MBBI) {
1273  if (MBBI == instr_begin()) return {};
1274  // Skip debug instructions, we don't want a DebugLoc from them.
1275  MBBI = prev_nodbg(MBBI, instr_begin());
1276  if (!MBBI->isDebugInstr()) return MBBI->getDebugLoc();
1277  return {};
1278}
1279
1280/// Find and return the merged DebugLoc of the branch instructions of the block.
1281/// Return UnknownLoc if there is none.
1282DebugLoc
1283MachineBasicBlock::findBranchDebugLoc() {
1284  DebugLoc DL;
1285  auto TI = getFirstTerminator();
1286  while (TI != end() && !TI->isBranch())
1287    ++TI;
1288
1289  if (TI != end()) {
1290    DL = TI->getDebugLoc();
1291    for (++TI ; TI != end() ; ++TI)
1292      if (TI->isBranch())
1293        DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
1294  }
1295  return DL;
1296}
1297
1298/// Return probability of the edge from this block to MBB.
1299BranchProbability
1300MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
1301  if (Probs.empty())
1302    return BranchProbability(1, succ_size());
1303
1304  const auto &Prob = *getProbabilityIterator(Succ);
1305  if (Prob.isUnknown()) {
1306    // For unknown probabilities, collect the sum of all known ones, and evenly
1307    // ditribute the complemental of the sum to each unknown probability.
1308    unsigned KnownProbNum = 0;
1309    auto Sum = BranchProbability::getZero();
1310    for (auto &P : Probs) {
1311      if (!P.isUnknown()) {
1312        Sum += P;
1313        KnownProbNum++;
1314      }
1315    }
1316    return Sum.getCompl() / (Probs.size() - KnownProbNum);
1317  } else
1318    return Prob;
1319}
1320
1321/// Set successor probability of a given iterator.
1322void MachineBasicBlock::setSuccProbability(succ_iterator I,
1323                                           BranchProbability Prob) {
1324  assert(!Prob.isUnknown());
1325  if (Probs.empty())
1326    return;
1327  *getProbabilityIterator(I) = Prob;
1328}
1329
1330/// Return probability iterator corresonding to the I successor iterator
1331MachineBasicBlock::const_probability_iterator
1332MachineBasicBlock::getProbabilityIterator(
1333    MachineBasicBlock::const_succ_iterator I) const {
1334  assert(Probs.size() == Successors.size() && "Async probability list!");
1335  const size_t index = std::distance(Successors.begin(), I);
1336  assert(index < Probs.size() && "Not a current successor!");
1337  return Probs.begin() + index;
1338}
1339
1340/// Return probability iterator corresonding to the I successor iterator.
1341MachineBasicBlock::probability_iterator
1342MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1343  assert(Probs.size() == Successors.size() && "Async probability list!");
1344  const size_t index = std::distance(Successors.begin(), I);
1345  assert(index < Probs.size() && "Not a current successor!");
1346  return Probs.begin() + index;
1347}
1348
1349/// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1350/// as of just before "MI".
1351///
1352/// Search is localised to a neighborhood of
1353/// Neighborhood instructions before (searching for defs or kills) and N
1354/// instructions after (searching just for defs) MI.
1355MachineBasicBlock::LivenessQueryResult
1356MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1357                                           MCRegister Reg, const_iterator Before,
1358                                           unsigned Neighborhood) const {
1359  unsigned N = Neighborhood;
1360
1361  // Try searching forwards from Before, looking for reads or defs.
1362  const_iterator I(Before);
1363  for (; I != end() && N > 0; ++I) {
1364    if (I->isDebugInstr())
1365      continue;
1366
1367    --N;
1368
1369    PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
1370
1371    // Register is live when we read it here.
1372    if (Info.Read)
1373      return LQR_Live;
1374    // Register is dead if we can fully overwrite or clobber it here.
1375    if (Info.FullyDefined || Info.Clobbered)
1376      return LQR_Dead;
1377  }
1378
1379  // If we reached the end, it is safe to clobber Reg at the end of a block of
1380  // no successor has it live in.
1381  if (I == end()) {
1382    for (MachineBasicBlock *S : successors()) {
1383      for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
1384        if (TRI->regsOverlap(LI.PhysReg, Reg))
1385          return LQR_Live;
1386      }
1387    }
1388
1389    return LQR_Dead;
1390  }
1391
1392
1393  N = Neighborhood;
1394
1395  // Start by searching backwards from Before, looking for kills, reads or defs.
1396  I = const_iterator(Before);
1397  // If this is the first insn in the block, don't search backwards.
1398  if (I != begin()) {
1399    do {
1400      --I;
1401
1402      if (I->isDebugInstr())
1403        continue;
1404
1405      --N;
1406
1407      PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
1408
1409      // Defs happen after uses so they take precedence if both are present.
1410
1411      // Register is dead after a dead def of the full register.
1412      if (Info.DeadDef)
1413        return LQR_Dead;
1414      // Register is (at least partially) live after a def.
1415      if (Info.Defined) {
1416        if (!Info.PartialDeadDef)
1417          return LQR_Live;
1418        // As soon as we saw a partial definition (dead or not),
1419        // we cannot tell if the value is partial live without
1420        // tracking the lanemasks. We are not going to do this,
1421        // so fall back on the remaining of the analysis.
1422        break;
1423      }
1424      // Register is dead after a full kill or clobber and no def.
1425      if (Info.Killed || Info.Clobbered)
1426        return LQR_Dead;
1427      // Register must be live if we read it.
1428      if (Info.Read)
1429        return LQR_Live;
1430
1431    } while (I != begin() && N > 0);
1432  }
1433
1434  // If all the instructions before this in the block are debug instructions,
1435  // skip over them.
1436  while (I != begin() && std::prev(I)->isDebugInstr())
1437    --I;
1438
1439  // Did we get to the start of the block?
1440  if (I == begin()) {
1441    // If so, the register's state is definitely defined by the live-in state.
1442    for (const MachineBasicBlock::RegisterMaskPair &LI : liveins())
1443      if (TRI->regsOverlap(LI.PhysReg, Reg))
1444        return LQR_Live;
1445
1446    return LQR_Dead;
1447  }
1448
1449  // At this point we have no idea of the liveness of the register.
1450  return LQR_Unknown;
1451}
1452
1453const uint32_t *
1454MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
1455  // EH funclet entry does not preserve any registers.
1456  return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1457}
1458
1459const uint32_t *
1460MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
1461  // If we see a return block with successors, this must be a funclet return,
1462  // which does not preserve any registers. If there are no successors, we don't
1463  // care what kind of return it is, putting a mask after it is a no-op.
1464  return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1465}
1466
1467void MachineBasicBlock::clearLiveIns() {
1468  LiveIns.clear();
1469}
1470
1471MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
1472  assert(getParent()->getProperties().hasProperty(
1473      MachineFunctionProperties::Property::TracksLiveness) &&
1474      "Liveness information is accurate");
1475  return LiveIns.begin();
1476}
1477
1478const MBBSectionID MBBSectionID::ColdSectionID(MBBSectionID::SectionType::Cold);
1479const MBBSectionID
1480    MBBSectionID::ExceptionSectionID(MBBSectionID::SectionType::Exception);
1481