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