LLVM 22.0.0git
MachineBasicBlock.cpp
Go to the documentation of this file.
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
14#include "llvm/ADT/STLExtras.h"
31#include "llvm/Config/llvm-config.h"
32#include "llvm/IR/BasicBlock.h"
34#include "llvm/MC/MCAsmInfo.h"
35#include "llvm/MC/MCContext.h"
36#include "llvm/Support/Debug.h"
39#include <algorithm>
40#include <cmath>
41using namespace llvm;
42
43#define DEBUG_TYPE "codegen"
44
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);
50
51MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
52 : BB(B), Number(-1), xParent(&MF) {
53 Insts.Parent = this;
54 if (B)
55 IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight();
56}
57
58MachineBasicBlock::~MachineBasicBlock() = default;
59
60/// Return the MCSymbol for this basic block.
62 if (!CachedMCSymbol) {
63 const MachineFunction *MF = getParent();
64 MCContext &Ctx = MF->getContext();
65
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();
80 }
81 CachedMCSymbol = Ctx.getOrCreateSymbol(MF->getName() + Suffix);
82 } else {
83 // If the block occurs as label in inline assembly, parsing the assembly
84 // needs an actual label name => set AlwaysEmit in these cases.
85 CachedMCSymbol = Ctx.createBlockSymbol(
86 "BB" + Twine(MF->getFunctionNumber()) + "_" + Twine(getNumber()),
87 /*AlwaysEmit=*/hasLabelMustBeEmitted());
88 }
89 }
90 return CachedMCSymbol;
91}
92
94 if (!CachedEHContMCSymbol) {
95 const MachineFunction *MF = getParent();
96 SmallString<128> SymbolName;
97 raw_svector_ostream(SymbolName)
98 << "$ehgcr_" << MF->getFunctionNumber() << '_' << getNumber();
99 CachedEHContMCSymbol = MF->getContext().getOrCreateSymbol(SymbolName);
100 }
101 return CachedEHContMCSymbol;
102}
103
105 if (!CachedEndMCSymbol) {
106 const MachineFunction *MF = getParent();
107 MCContext &Ctx = MF->getContext();
108 CachedEndMCSymbol = Ctx.createBlockSymbol(
109 "BB_END" + Twine(MF->getFunctionNumber()) + "_" + Twine(getNumber()),
110 /*AlwaysEmit=*/false);
111 }
112 return CachedEndMCSymbol;
113}
114
116 MBB.print(OS);
117 return OS;
118}
119
121 return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); });
122}
123
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.
127///
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.
133 MachineFunction &MF = *N->getParent();
134 N->Number = MF.addToMBBNumbering(N);
135
136 // Make sure the instructions have their operands in the reginfo lists.
138 for (MachineInstr &MI : N->instrs())
139 MI.addRegOperandsToUseLists(RegInfo);
140}
141
144 N->getParent()->removeFromMBBNumbering(N->Number);
145 N->Number = -1;
146}
147
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.
151 assert(!N->getParent() && "machine instruction already in a basic block");
152 N->setParent(Parent);
153
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);
159}
160
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.
164 assert(N->getParent() && "machine instruction not in a basic block");
165
166 // Remove from the use/def lists.
167 if (MachineFunction *MF = N->getMF()) {
168 MF->handleRemoval(*N);
169 N->removeRegOperandsFromUseLists(MF->getRegInfo());
170 }
171
172 N->setParent(nullptr);
173}
174
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.
178 instr_iterator First,
179 instr_iterator Last) {
180 assert(Parent->getParent() == FromList.Parent->getParent() &&
181 "cannot transfer MachineInstrs between MachineFunctions");
182
183 // If it's within the same BB, there's nothing to do.
184 if (this == &FromList)
185 return;
186
187 assert(Parent != FromList.Parent && "Two lists have the same parent?");
188
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);
193}
194
196 assert(!MI->getParent() && "MI is still in a block!");
197 Parent->getParent()->deleteMachineInstr(MI);
198}
199
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;
207}
208
212
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;
222}
223
226 Register Reg, bool SkipPseudoOp) {
228
229 iterator E = end();
230 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() ||
231 (SkipPseudoOp && I->isPseudoProbe()) ||
232 TII->isBasicBlockPrologue(*I, Reg)))
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;
240}
241
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;
249}
250
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;
258}
259
261 return find_if(instrs(), [](auto &II) { return II.isTerminator(); });
262}
263
266 // Skip over begin-of-block dbg_value instructions.
267 return skipDebugInstructionsForward(begin(), end(), SkipPseudoOp);
268}
269
272 // Skip over end-of-block dbg_value instructions.
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;
282 }
283 // The block is all debug values.
284 return end();
285}
286
288 for (const MachineBasicBlock *Succ : successors())
289 if (Succ->isEHPad())
290 return true;
291 return false;
292}
293
295 return getParent()->begin() == getIterator();
296}
297
298#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
302#endif
303
305 for (const MachineBasicBlock *Succ : successors()) {
306 if (Succ->isInlineAsmBrIndirectTarget())
307 return true;
308 }
309 return false;
310}
311
314 return false;
315 return true;
316}
317
319 if (const BasicBlock *LBB = getBasicBlock())
320 return LBB->hasName();
321 return false;
322}
323
325 if (const BasicBlock *LBB = getBasicBlock())
326 return LBB->getName();
327 else
328 return StringRef("", 0);
329}
330
331/// Return a hopefully unique identifier for this block.
333 std::string Name;
334 if (getParent())
335 Name = (getParent()->getName() + ":").str();
336 if (getBasicBlock())
337 Name += getBasicBlock()->getName();
338 else
339 Name += ("BB" + Twine(getNumber())).str();
340 return Name;
341}
342
344 bool IsStandalone) const {
345 const MachineFunction *MF = getParent();
346 if (!MF) {
347 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
348 << " is null\n";
349 return;
350 }
351 const Function &F = MF->getFunction();
352 const Module *M = F.getParent();
353 ModuleSlotTracker MST(M);
355 print(OS, MST, Indexes, IsStandalone);
356}
357
359 const SlotIndexes *Indexes,
360 bool IsStandalone) const {
361 const MachineFunction *MF = getParent();
362 if (!MF) {
363 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
364 << " is null\n";
365 return;
366 }
367
368 if (Indexes && PrintSlotIndexes)
369 OS << Indexes->getMBBStartIdx(this) << '\t';
370
372 OS << ":\n";
373
375 const MachineRegisterInfo &MRI = MF->getRegInfo();
377 bool HasLineAttributes = false;
378
379 // Print the preds of this block according to the CFG.
380 if (!pred_empty() && IsStandalone) {
381 if (Indexes) OS << '\t';
382 // Don't indent(2), align with previous line attributes.
383 OS << "; predecessors: ";
384 ListSeparator LS;
385 for (auto *Pred : predecessors())
386 OS << LS << printMBBReference(*Pred);
387 OS << '\n';
388 HasLineAttributes = true;
389 }
390
391 if (!succ_empty()) {
392 if (Indexes) OS << '\t';
393 // Print the successors
394 OS.indent(2) << "successors: ";
395 ListSeparator LS;
396 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
397 OS << LS << printMBBReference(**I);
398 if (!Probs.empty())
399 OS << '('
400 << format("0x%08" PRIx32, getSuccProbability(I).getNumerator())
401 << ')';
402 }
403 if (!Probs.empty() && IsStandalone) {
404 // Print human readable probabilities as comments.
405 OS << "; ";
406 ListSeparator LS;
407 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
409 OS << LS << printMBBReference(**I) << '('
410 << format("%.2f%%",
411 rint(((double)BP.getNumerator() / BP.getDenominator()) *
412 100.0 * 100.0) /
413 100.0)
414 << ')';
415 }
416 }
417
418 OS << '\n';
419 HasLineAttributes = true;
420 }
421
422 if (!livein_empty() && MRI.tracksLiveness()) {
423 if (Indexes) OS << '\t';
424 OS.indent(2) << "liveins: ";
425
426 ListSeparator LS;
427 for (const auto &LI : liveins()) {
428 OS << LS << printReg(LI.PhysReg, TRI);
429 if (!LI.LaneMask.all())
430 OS << ":0x" << PrintLaneMask(LI.LaneMask);
431 }
432 HasLineAttributes = true;
433 }
434
435 if (HasLineAttributes)
436 OS << '\n';
437
438 bool IsInBundle = false;
439 for (const MachineInstr &MI : instrs()) {
440 if (Indexes && PrintSlotIndexes) {
441 if (Indexes->hasIndex(MI))
442 OS << Indexes->getInstructionIndex(MI);
443 OS << '\t';
444 }
445
446 if (IsInBundle && !MI.isInsideBundle()) {
447 OS.indent(2) << "}\n";
448 IsInBundle = false;
449 }
450
451 OS.indent(IsInBundle ? 4 : 2);
452 MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
453 /*AddNewLine=*/false, &TII);
454
455 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
456 OS << " {";
457 IsInBundle = true;
458 }
459 OS << '\n';
460 }
461
462 if (IsInBundle)
463 OS.indent(2) << "}\n";
464
465 if (IrrLoopHeaderWeight && IsStandalone) {
466 if (Indexes) OS << '\t';
467 OS.indent(2) << "; Irreducible loop header weight: " << *IrrLoopHeaderWeight
468 << '\n';
469 }
470}
471
472/// Print the basic block's name as:
473///
474/// bb.{number}[.{ir-name}] [(attributes...)]
475///
476/// The {ir-name} is only printed when the \ref PrintNameIr flag is passed
477/// (which is the default). If the IR block has no name, it is identified
478/// numerically using the attribute syntax as "(%ir-block.{ir-slot})".
479///
480/// When the \ref PrintNameAttributes flag is passed, additional attributes
481/// of the block are printed when set.
482///
483/// \param printNameFlags Combination of \ref PrintNameFlag flags indicating
484/// the parts to print.
485/// \param moduleSlotTracker Optional ModuleSlotTracker. This method will
486/// incorporate its own tracker when necessary to
487/// determine the block's IR name.
488void MachineBasicBlock::printName(raw_ostream &os, unsigned printNameFlags,
489 ModuleSlotTracker *moduleSlotTracker) const {
490 os << "bb." << getNumber();
491 bool hasAttributes = false;
492
493 auto PrintBBRef = [&](const BasicBlock *bb) {
494 os << "%ir-block.";
495 if (bb->hasName()) {
496 os << bb->getName();
497 } else {
498 int slot = -1;
499
500 if (moduleSlotTracker) {
501 slot = moduleSlotTracker->getLocalSlot(bb);
502 } else if (bb->getParent()) {
503 ModuleSlotTracker tmpTracker(bb->getModule(), false);
504 tmpTracker.incorporateFunction(*bb->getParent());
505 slot = tmpTracker.getLocalSlot(bb);
506 }
507
508 if (slot == -1)
509 os << "<ir-block badref>";
510 else
511 os << slot;
512 }
513 };
514
515 if (printNameFlags & PrintNameIr) {
516 if (const auto *bb = getBasicBlock()) {
517 if (bb->hasName()) {
518 os << '.' << bb->getName();
519 } else {
520 hasAttributes = true;
521 os << " (";
522 PrintBBRef(bb);
523 }
524 }
525 }
526
527 if (printNameFlags & PrintNameAttributes) {
529 os << (hasAttributes ? ", " : " (");
530 os << "machine-block-address-taken";
531 hasAttributes = true;
532 }
533 if (isIRBlockAddressTaken()) {
534 os << (hasAttributes ? ", " : " (");
535 os << "ir-block-address-taken ";
536 PrintBBRef(getAddressTakenIRBlock());
537 hasAttributes = true;
538 }
539 if (isEHPad()) {
540 os << (hasAttributes ? ", " : " (");
541 os << "landing-pad";
542 hasAttributes = true;
543 }
545 os << (hasAttributes ? ", " : " (");
546 os << "inlineasm-br-indirect-target";
547 hasAttributes = true;
548 }
549 if (isEHFuncletEntry()) {
550 os << (hasAttributes ? ", " : " (");
551 os << "ehfunclet-entry";
552 hasAttributes = true;
553 }
554 if (getAlignment() != Align(1)) {
555 os << (hasAttributes ? ", " : " (");
556 os << "align " << getAlignment().value();
557 hasAttributes = true;
558 }
559 if (getSectionID() != MBBSectionID(0)) {
560 os << (hasAttributes ? ", " : " (");
561 os << "bbsections ";
562 switch (getSectionID().Type) {
564 os << "Exception";
565 break;
567 os << "Cold";
568 break;
569 default:
570 os << getSectionID().Number;
571 }
572 hasAttributes = true;
573 }
574 if (getBBID().has_value()) {
575 os << (hasAttributes ? ", " : " (");
576 os << "bb_id " << getBBID()->BaseID;
577 if (getBBID()->CloneID != 0)
578 os << " " << getBBID()->CloneID;
579 hasAttributes = true;
580 }
581 if (CallFrameSize != 0) {
582 os << (hasAttributes ? ", " : " (");
583 os << "call-frame-size " << CallFrameSize;
584 hasAttributes = true;
585 }
586 }
587
588 if (hasAttributes)
589 os << ')';
590}
591
593 bool /*PrintType*/) const {
594 OS << '%';
595 printName(OS, 0);
596}
597
599 assert(Reg.isPhysical());
600 LiveInVector::iterator I = find_if(
601 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
602 if (I == LiveIns.end())
603 return;
604
605 I->LaneMask &= ~LaneMask;
606 if (I->LaneMask.none())
607 LiveIns.erase(I);
608}
609
611 const MachineFunction *MF = getParent();
613 // Remove Reg and its subregs from live in set.
614 for (MCPhysReg S : TRI->subregs_inclusive(Reg))
615 removeLiveIn(S);
616
617 // Remove live-in bitmask in super registers as well.
618 for (MCPhysReg Super : TRI->superregs(Reg)) {
619 for (MCSubRegIndexIterator SRI(Super, TRI); SRI.isValid(); ++SRI) {
620 if (Reg == SRI.getSubReg()) {
621 unsigned SubRegIndex = SRI.getSubRegIndex();
622 LaneBitmask SubRegLaneMask = TRI->getSubRegIndexLaneMask(SubRegIndex);
623 removeLiveIn(Super, SubRegLaneMask);
624 break;
625 }
626 }
627 }
628}
629
632 // Get non-const version of iterator.
633 LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
634 return LiveIns.erase(LI);
635}
636
638 assert(Reg.isPhysical());
640 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
641 return I != livein_end() && (I->LaneMask & LaneMask).any();
642}
643
645 llvm::sort(LiveIns,
646 [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
647 return LI0.PhysReg < LI1.PhysReg;
648 });
649 // Liveins are sorted by physreg now we can merge their lanemasks.
650 LiveInVector::const_iterator I = LiveIns.begin();
651 LiveInVector::const_iterator J;
652 LiveInVector::iterator Out = LiveIns.begin();
653 for (; I != LiveIns.end(); ++Out, I = J) {
654 MCRegister PhysReg = I->PhysReg;
655 LaneBitmask LaneMask = I->LaneMask;
656 for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
657 LaneMask |= J->LaneMask;
658 Out->PhysReg = PhysReg;
659 Out->LaneMask = LaneMask;
660 }
661 LiveIns.erase(Out, LiveIns.end());
662}
663
666 assert(getParent() && "MBB must be inserted in function");
667 assert(PhysReg.isPhysical() && "Expected physreg");
668 assert(RC && "Register class is required");
669 assert((isEHPad() || this == &getParent()->front()) &&
670 "Only the entry block and landing pads can have physreg live ins");
671
672 bool LiveIn = isLiveIn(PhysReg);
676
677 // Look for an existing copy.
678 if (LiveIn)
679 for (;I != E && I->isCopy(); ++I)
680 if (I->getOperand(1).getReg() == PhysReg) {
681 Register VirtReg = I->getOperand(0).getReg();
682 if (!MRI.constrainRegClass(VirtReg, RC))
683 llvm_unreachable("Incompatible live-in register class.");
684 return VirtReg;
685 }
686
687 // No luck, create a virtual register.
688 Register VirtReg = MRI.createVirtualRegister(RC);
689 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
690 .addReg(PhysReg, RegState::Kill);
691 if (!LiveIn)
692 addLiveIn(PhysReg);
693 return VirtReg;
694}
695
696void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
697 getParent()->splice(NewAfter->getIterator(), getIterator());
698}
699
700void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
701 getParent()->splice(++NewBefore->getIterator(), getIterator());
702}
703
705 MachineBasicBlock::const_iterator TerminatorI = MBB.getFirstTerminator();
706 if (TerminatorI == MBB.end())
707 return -1;
708 const MachineInstr &Terminator = *TerminatorI;
709 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
710 return TII->getJumpTableIndex(Terminator);
711}
712
714 MachineBasicBlock *PreviousLayoutSuccessor) {
715 LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
716 << "\n");
717
719 // A block with no successors has no concerns with fall-through edges.
720 if (this->succ_empty())
721 return;
722
723 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
726 bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
727 (void) B;
728 assert(!B && "UpdateTerminators requires analyzable predecessors!");
729 if (Cond.empty()) {
730 if (TBB) {
731 // The block has an unconditional branch. If its successor is now its
732 // layout successor, delete the branch.
734 TII->removeBranch(*this);
735 } else {
736 // The block has an unconditional fallthrough, or the end of the block is
737 // unreachable.
738
739 // Unfortunately, whether the end of the block is unreachable is not
740 // immediately obvious; we must fall back to checking the successor list,
741 // and assuming that if the passed in block is in the succesor list and
742 // not an EHPad, it must be the intended target.
743 if (!PreviousLayoutSuccessor || !isSuccessor(PreviousLayoutSuccessor) ||
744 PreviousLayoutSuccessor->isEHPad())
745 return;
746
747 // If the unconditional successor block is not the current layout
748 // successor, insert a branch to jump to it.
749 if (!isLayoutSuccessor(PreviousLayoutSuccessor))
750 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
751 }
752 return;
753 }
754
755 if (FBB) {
756 // The block has a non-fallthrough conditional branch. If one of its
757 // successors is its layout successor, rewrite it to a fallthrough
758 // conditional branch.
759 if (isLayoutSuccessor(TBB)) {
760 if (TII->reverseBranchCondition(Cond))
761 return;
762 TII->removeBranch(*this);
763 TII->insertBranch(*this, FBB, nullptr, Cond, DL);
764 } else if (isLayoutSuccessor(FBB)) {
765 TII->removeBranch(*this);
766 TII->insertBranch(*this, TBB, nullptr, Cond, DL);
767 }
768 return;
769 }
770
771 // We now know we're going to fallthrough to PreviousLayoutSuccessor.
772 assert(PreviousLayoutSuccessor);
773 assert(!PreviousLayoutSuccessor->isEHPad());
774 assert(isSuccessor(PreviousLayoutSuccessor));
775
776 if (PreviousLayoutSuccessor == TBB) {
777 // We had a fallthrough to the same basic block as the conditional jump
778 // targets. Remove the conditional jump, leaving an unconditional
779 // fallthrough or an unconditional jump.
780 TII->removeBranch(*this);
781 if (!isLayoutSuccessor(TBB)) {
782 Cond.clear();
783 TII->insertBranch(*this, TBB, nullptr, Cond, DL);
784 }
785 return;
786 }
787
788 // The block has a fallthrough conditional branch.
789 if (isLayoutSuccessor(TBB)) {
790 if (TII->reverseBranchCondition(Cond)) {
791 // We can't reverse the condition, add an unconditional branch.
792 Cond.clear();
793 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
794 return;
795 }
796 TII->removeBranch(*this);
797 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
798 } else if (!isLayoutSuccessor(PreviousLayoutSuccessor)) {
799 TII->removeBranch(*this);
800 TII->insertBranch(*this, TBB, PreviousLayoutSuccessor, Cond, DL);
801 }
802}
803
805#ifndef NDEBUG
806 int64_t Sum = 0;
807 for (auto Prob : Probs)
808 Sum += Prob.getNumerator();
809 // Due to precision issue, we assume that the sum of probabilities is one if
810 // the difference between the sum of their numerators and the denominator is
811 // no greater than the number of successors.
813 Probs.size() &&
814 "The sum of successors's probabilities exceeds one.");
815#endif // NDEBUG
816}
817
818void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
819 BranchProbability Prob) {
820 // Probability list is either empty (if successor list isn't empty, this means
821 // disabled optimization) or has the same size as successor list.
822 if (!(Probs.empty() && !Successors.empty()))
823 Probs.push_back(Prob);
824 Successors.push_back(Succ);
825 Succ->addPredecessor(this);
826}
827
828void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
829 // We need to make sure probability list is either empty or has the same size
830 // of successor list. When this function is called, we can safely delete all
831 // probability in the list.
832 Probs.clear();
833 Successors.push_back(Succ);
834 Succ->addPredecessor(this);
835}
836
837void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
838 MachineBasicBlock *New,
839 bool NormalizeSuccProbs) {
840 succ_iterator OldI = llvm::find(successors(), Old);
841 assert(OldI != succ_end() && "Old is not a successor of this block!");
843 "New is already a successor of this block!");
844
845 // Add a new successor with equal probability as the original one. Note
846 // that we directly copy the probability using the iterator rather than
847 // getting a potentially synthetic probability computed when unknown. This
848 // preserves the probabilities as-is and then we can renormalize them and
849 // query them effectively afterward.
850 addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
851 : *getProbabilityIterator(OldI));
852 if (NormalizeSuccProbs)
854}
855
856void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
857 bool NormalizeSuccProbs) {
858 succ_iterator I = find(Successors, Succ);
859 removeSuccessor(I, NormalizeSuccProbs);
860}
861
864 assert(I != Successors.end() && "Not a current successor!");
865
866 // If probability list is empty it means we don't use it (disabled
867 // optimization).
868 if (!Probs.empty()) {
869 probability_iterator WI = getProbabilityIterator(I);
870 Probs.erase(WI);
871 if (NormalizeSuccProbs)
873 }
874
875 (*I)->removePredecessor(this);
876 return Successors.erase(I);
877}
878
879void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
880 MachineBasicBlock *New) {
881 if (Old == New)
882 return;
883
885 succ_iterator NewI = E;
886 succ_iterator OldI = E;
887 for (succ_iterator I = succ_begin(); I != E; ++I) {
888 if (*I == Old) {
889 OldI = I;
890 if (NewI != E)
891 break;
892 }
893 if (*I == New) {
894 NewI = I;
895 if (OldI != E)
896 break;
897 }
898 }
899 assert(OldI != E && "Old is not a successor of this block");
900
901 // If New isn't already a successor, let it take Old's place.
902 if (NewI == E) {
903 Old->removePredecessor(this);
904 New->addPredecessor(this);
905 *OldI = New;
906 return;
907 }
908
909 // New is already a successor.
910 // Update its probability instead of adding a duplicate edge.
911 if (!Probs.empty()) {
912 auto ProbIter = getProbabilityIterator(NewI);
913 if (!ProbIter->isUnknown())
914 *ProbIter += *getProbabilityIterator(OldI);
915 }
916 removeSuccessor(OldI);
917}
918
919void MachineBasicBlock::copySuccessor(const MachineBasicBlock *Orig,
921 if (!Orig->Probs.empty())
923 else
925}
926
927void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
928 Predecessors.push_back(Pred);
929}
930
931void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
932 pred_iterator I = find(Predecessors, Pred);
933 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
934 Predecessors.erase(I);
935}
936
937void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
938 if (this == FromMBB)
939 return;
940
941 while (!FromMBB->succ_empty()) {
942 MachineBasicBlock *Succ = *FromMBB->succ_begin();
943
944 // If probability list is empty it means we don't use it (disabled
945 // optimization).
946 if (!FromMBB->Probs.empty()) {
947 auto Prob = *FromMBB->Probs.begin();
948 addSuccessor(Succ, Prob);
949 } else
951
952 FromMBB->removeSuccessor(Succ);
953 }
954}
955
956void
958 if (this == FromMBB)
959 return;
960
961 while (!FromMBB->succ_empty()) {
962 MachineBasicBlock *Succ = *FromMBB->succ_begin();
963 if (!FromMBB->Probs.empty()) {
964 auto Prob = *FromMBB->Probs.begin();
965 addSuccessor(Succ, Prob);
966 } else
968 FromMBB->removeSuccessor(Succ);
969
970 // Fix up any PHI nodes in the successor.
971 Succ->replacePhiUsesWith(FromMBB, this);
972 }
974}
975
976bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
977 return is_contained(predecessors(), MBB);
978}
979
980bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
981 return is_contained(successors(), MBB);
982}
983
984bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
986 return std::next(I) == MachineFunction::const_iterator(MBB);
987}
988
989const MachineBasicBlock *MachineBasicBlock::getSingleSuccessor() const {
990 return Successors.size() == 1 ? Successors[0] : nullptr;
991}
992
993const MachineBasicBlock *MachineBasicBlock::getSinglePredecessor() const {
994 return Predecessors.size() == 1 ? Predecessors[0] : nullptr;
995}
996
997MachineBasicBlock *MachineBasicBlock::getFallThrough(bool JumpToFallThrough) {
999 ++Fallthrough;
1000 // If FallthroughBlock is off the end of the function, it can't fall through.
1001 if (Fallthrough == getParent()->end())
1002 return nullptr;
1003
1004 // If FallthroughBlock isn't a successor, no fallthrough is possible.
1005 if (!isSuccessor(&*Fallthrough))
1006 return nullptr;
1007
1008 // Analyze the branches, if any, at the end of the block.
1009 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1012 if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
1013 // If we couldn't analyze the branch, examine the last instruction.
1014 // If the block doesn't end in a known control barrier, assume fallthrough
1015 // is possible. The isPredicated check is needed because this code can be
1016 // called during IfConversion, where an instruction which is normally a
1017 // Barrier is predicated and thus no longer an actual control barrier.
1018 return (empty() || !back().isBarrier() || TII->isPredicated(back()))
1019 ? &*Fallthrough
1020 : nullptr;
1021 }
1022
1023 // If there is no branch, control always falls through.
1024 if (!TBB) return &*Fallthrough;
1025
1026 // If there is some explicit branch to the fallthrough block, it can obviously
1027 // reach, even though the branch should get folded to fall through implicitly.
1028 if (JumpToFallThrough && (MachineFunction::iterator(TBB) == Fallthrough ||
1029 MachineFunction::iterator(FBB) == Fallthrough))
1030 return &*Fallthrough;
1031
1032 // If it's an unconditional branch to some block not the fall through, it
1033 // doesn't fall through.
1034 if (Cond.empty()) return nullptr;
1035
1036 // Otherwise, if it is conditional and has no explicit false block, it falls
1037 // through.
1038 return (FBB == nullptr) ? &*Fallthrough : nullptr;
1039}
1040
1042 return getFallThrough() != nullptr;
1043}
1044
1046 bool UpdateLiveIns,
1047 LiveIntervals *LIS) {
1048 MachineBasicBlock::iterator SplitPoint(&MI);
1049 ++SplitPoint;
1050
1051 if (SplitPoint == end()) {
1052 // Don't bother with a new block.
1053 return this;
1054 }
1055
1056 MachineFunction *MF = getParent();
1057
1059 if (UpdateLiveIns) {
1060 // Make sure we add any physregs we define in the block as liveins to the
1061 // new block.
1063 LiveRegs.init(*MF->getSubtarget().getRegisterInfo());
1064 LiveRegs.addLiveOuts(*this);
1065 for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I)
1066 LiveRegs.stepBackward(*I);
1067 }
1068
1069 MachineBasicBlock *SplitBB = MF->CreateMachineBasicBlock(getBasicBlock());
1070
1071 MF->insert(++MachineFunction::iterator(this), SplitBB);
1072 SplitBB->splice(SplitBB->begin(), this, SplitPoint, end());
1073
1074 SplitBB->transferSuccessorsAndUpdatePHIs(this);
1075 addSuccessor(SplitBB);
1076
1077 if (UpdateLiveIns)
1078 addLiveIns(*SplitBB, LiveRegs);
1079
1080 if (LIS)
1081 LIS->insertMBBInMaps(SplitBB);
1082
1083 return SplitBB;
1084}
1085
1086// Returns `true` if there are possibly other users of the jump table at
1087// `JumpTableIndex` except for the ones in `IgnoreMBB`.
1089 const MachineBasicBlock &IgnoreMBB,
1090 int JumpTableIndex) {
1091 assert(JumpTableIndex >= 0 && "need valid index");
1092 const MachineJumpTableInfo &MJTI = *MF.getJumpTableInfo();
1093 const MachineJumpTableEntry &MJTE = MJTI.getJumpTables()[JumpTableIndex];
1094 // Take any basic block from the table; every user of the jump table must
1095 // show up in the predecessor list.
1096 const MachineBasicBlock *MBB = nullptr;
1097 for (MachineBasicBlock *B : MJTE.MBBs) {
1098 if (B != nullptr) {
1099 MBB = B;
1100 break;
1101 }
1102 }
1103 if (MBB == nullptr)
1104 return true; // can't rule out other users if there isn't any block.
1107 for (MachineBasicBlock *Pred : MBB->predecessors()) {
1108 if (Pred == &IgnoreMBB)
1109 continue;
1110 MachineBasicBlock *DummyT = nullptr;
1111 MachineBasicBlock *DummyF = nullptr;
1112 Cond.clear();
1113 if (!TII.analyzeBranch(*Pred, DummyT, DummyF, Cond,
1114 /*AllowModify=*/false)) {
1115 // analyzable direct jump
1116 continue;
1117 }
1118 int PredJTI = findJumpTableIndex(*Pred);
1119 if (PredJTI >= 0) {
1120 if (PredJTI == JumpTableIndex)
1121 return true;
1122 continue;
1123 }
1124 // Be conservative for unanalyzable jumps.
1125 return true;
1126 }
1127 return false;
1128}
1129
1131private:
1132 MachineFunction &MF;
1133 SlotIndexes *Indexes;
1135
1136public:
1138 : MF(MF), Indexes(Indexes) {
1139 MF.setDelegate(this);
1140 }
1141
1143 MF.resetDelegate(this);
1144 for (auto MI : Insertions)
1145 Indexes->insertMachineInstrInMaps(*MI);
1146 }
1147
1149 // This is called before MI is inserted into block so defer index update.
1150 if (Indexes)
1151 Insertions.insert(&MI);
1152 }
1153
1155 if (Indexes && !Insertions.remove(&MI))
1156 Indexes->removeMachineInstrFromMaps(MI);
1157 }
1158};
1159
1161 MachineBasicBlock *Succ, Pass *P, MachineFunctionAnalysisManager *MFAM,
1162 std::vector<SparseBitVector<>> *LiveInSets, MachineDomTreeUpdater *MDTU) {
1163#define GET_RESULT(RESULT, GETTER, INFIX) \
1164 [MF, P, MFAM]() { \
1165 if (P) { \
1166 auto *Wrapper = P->getAnalysisIfAvailable<RESULT##INFIX##WrapperPass>(); \
1167 return Wrapper ? &Wrapper->GETTER() : nullptr; \
1168 } \
1169 return MFAM->getCachedResult<RESULT##Analysis>(*MF); \
1170 }()
1171
1172 assert((P || MFAM) && "Need a way to get analysis results!");
1173 MachineFunction *MF = getParent();
1174 LiveIntervals *LIS = GET_RESULT(LiveIntervals, getLIS, );
1175 SlotIndexes *Indexes = GET_RESULT(SlotIndexes, getSI, );
1176 LiveVariables *LV = GET_RESULT(LiveVariables, getLV, );
1177 MachineLoopInfo *MLI = GET_RESULT(MachineLoop, getLI, Info);
1178 return SplitCriticalEdge(Succ, {LIS, Indexes, LV, MLI}, LiveInSets, MDTU);
1179#undef GET_RESULT
1180}
1181
1183 MachineBasicBlock *Succ, const SplitCriticalEdgeAnalyses &Analyses,
1184 std::vector<SparseBitVector<>> *LiveInSets, MachineDomTreeUpdater *MDTU) {
1185 if (!canSplitCriticalEdge(Succ, Analyses.MLI))
1186 return nullptr;
1187
1188 MachineFunction *MF = getParent();
1189 MachineBasicBlock *PrevFallthrough = getNextNode();
1190
1191 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
1192 NMBB->setCallFrameSize(Succ->getCallFrameSize());
1193
1194 // Is there an indirect jump with jump table?
1195 bool ChangedIndirectJump = false;
1196 int JTI = findJumpTableIndex(*this);
1197 if (JTI >= 0) {
1199 MJTI.ReplaceMBBInJumpTable(JTI, Succ, NMBB);
1200 ChangedIndirectJump = true;
1201 }
1202
1203 MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
1204 LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
1205 << " -- " << printMBBReference(*NMBB) << " -- "
1206 << printMBBReference(*Succ) << '\n');
1207 auto *LIS = Analyses.LIS;
1208 if (LIS)
1209 LIS->insertMBBInMaps(NMBB);
1210 else if (Analyses.SI)
1211 Analyses.SI->insertMBBInMaps(NMBB);
1212
1213 // On some targets like Mips, branches may kill virtual registers. Make sure
1214 // that LiveVariables is properly updated after updateTerminator replaces the
1215 // terminators.
1216 auto *LV = Analyses.LV;
1217 // Collect a list of virtual registers killed by the terminators.
1218 SmallVector<Register, 4> KilledRegs;
1219 if (LV)
1220 for (MachineInstr &MI :
1222 for (MachineOperand &MO : MI.all_uses()) {
1223 if (MO.getReg() == 0 || !MO.isKill() || MO.isUndef())
1224 continue;
1225 Register Reg = MO.getReg();
1226 if (Reg.isPhysical() || LV->getVarInfo(Reg).removeKill(MI)) {
1227 KilledRegs.push_back(Reg);
1228 LLVM_DEBUG(dbgs() << "Removing terminator kill: " << MI);
1229 MO.setIsKill(false);
1230 }
1231 }
1232 }
1233
1234 SmallVector<Register, 4> UsedRegs;
1235 if (LIS) {
1236 for (MachineInstr &MI :
1238 for (const MachineOperand &MO : MI.operands()) {
1239 if (!MO.isReg() || MO.getReg() == 0)
1240 continue;
1241
1242 Register Reg = MO.getReg();
1243 if (!is_contained(UsedRegs, Reg))
1244 UsedRegs.push_back(Reg);
1245 }
1246 }
1247 }
1248
1249 ReplaceUsesOfBlockWith(Succ, NMBB);
1250
1251 // Since we replaced all uses of Succ with NMBB, that should also be treated
1252 // as the fallthrough successor
1253 if (Succ == PrevFallthrough)
1254 PrevFallthrough = NMBB;
1255 auto *Indexes = Analyses.SI;
1256 if (!ChangedIndirectJump) {
1257 SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1258 updateTerminator(PrevFallthrough);
1259 }
1260
1261 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
1262 NMBB->addSuccessor(Succ);
1263 if (!NMBB->isLayoutSuccessor(Succ)) {
1264 SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1267
1268 // In original 'this' BB, there must be a branch instruction targeting at
1269 // Succ. We can not find it out since currently getBranchDestBlock was not
1270 // implemented for all targets. However, if the merged DL has column or line
1271 // number, the scope and non-zero column and line number is same with that
1272 // branch instruction so we can safely use it.
1273 DebugLoc DL, MergedDL = findBranchDebugLoc();
1274 if (MergedDL && (MergedDL.getLine() || MergedDL.getCol()))
1275 DL = MergedDL;
1276 TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
1277 }
1278
1279 // Fix PHI nodes in Succ so they refer to NMBB instead of this.
1280 Succ->replacePhiUsesWith(this, NMBB);
1281
1282 // Inherit live-ins from the successor
1283 for (const auto &LI : Succ->liveins())
1284 NMBB->addLiveIn(LI);
1285
1286 // Update LiveVariables.
1288 if (LV) {
1289 // Restore kills of virtual registers that were killed by the terminators.
1290 while (!KilledRegs.empty()) {
1291 Register Reg = KilledRegs.pop_back_val();
1292 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
1293 if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false))
1294 continue;
1295 if (Reg.isVirtual())
1296 LV->getVarInfo(Reg).Kills.push_back(&*I);
1297 LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
1298 break;
1299 }
1300 }
1301 // Update relevant live-through information.
1302 if (LiveInSets != nullptr)
1303 LV->addNewBlock(NMBB, this, Succ, *LiveInSets);
1304 else
1305 LV->addNewBlock(NMBB, this, Succ);
1306 }
1307
1308 if (LIS) {
1309 // After splitting the edge and updating SlotIndexes, live intervals may be
1310 // in one of two situations, depending on whether this block was the last in
1311 // the function. If the original block was the last in the function, all
1312 // live intervals will end prior to the beginning of the new split block. If
1313 // the original block was not at the end of the function, all live intervals
1314 // will extend to the end of the new split block.
1315
1316 bool isLastMBB =
1317 std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
1318
1319 SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
1320 SlotIndex PrevIndex = StartIndex.getPrevSlot();
1321 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
1322
1323 // Find the registers used from NMBB in PHIs in Succ.
1324 SmallSet<Register, 8> PHISrcRegs;
1326 I = Succ->instr_begin(), E = Succ->instr_end();
1327 I != E && I->isPHI(); ++I) {
1328 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
1329 if (I->getOperand(ni+1).getMBB() == NMBB) {
1330 MachineOperand &MO = I->getOperand(ni);
1331 Register Reg = MO.getReg();
1332 PHISrcRegs.insert(Reg);
1333 if (MO.isUndef())
1334 continue;
1335
1336 LiveInterval &LI = LIS->getInterval(Reg);
1337 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1338 assert(VNI &&
1339 "PHI sources should be live out of their predecessors.");
1340 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1341 for (auto &SR : LI.subranges())
1342 SR.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1343 }
1344 }
1345 }
1346
1348 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1350 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
1351 continue;
1352
1353 LiveInterval &LI = LIS->getInterval(Reg);
1354 if (!LI.liveAt(PrevIndex))
1355 continue;
1356
1357 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
1358 if (isLiveOut && isLastMBB) {
1359 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1360 assert(VNI && "LiveInterval should have VNInfo where it is live.");
1361 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1362 // Update subranges with live values
1363 for (auto &SR : LI.subranges()) {
1364 VNInfo *VNI = SR.getVNInfoAt(PrevIndex);
1365 if (VNI)
1366 SR.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1367 }
1368 } else if (!isLiveOut && !isLastMBB) {
1369 LI.removeSegment(StartIndex, EndIndex);
1370 for (auto &SR : LI.subranges())
1371 SR.removeSegment(StartIndex, EndIndex);
1372 }
1373 }
1374
1375 // Update all intervals for registers whose uses may have been modified by
1376 // updateTerminator().
1377 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
1378 }
1379
1380 if (MDTU)
1381 MDTU->splitCriticalEdge(this, Succ, NMBB);
1382
1383 if (MachineLoopInfo *MLI = Analyses.MLI)
1384 if (MachineLoop *TIL = MLI->getLoopFor(this)) {
1385 // If one or the other blocks were not in a loop, the new block is not
1386 // either, and thus LI doesn't need to be updated.
1387 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
1388 if (TIL == DestLoop) {
1389 // Both in the same loop, the NMBB joins loop.
1390 DestLoop->addBasicBlockToLoop(NMBB, *MLI);
1391 } else if (TIL->contains(DestLoop)) {
1392 // Edge from an outer loop to an inner loop. Add to the outer loop.
1393 TIL->addBasicBlockToLoop(NMBB, *MLI);
1394 } else if (DestLoop->contains(TIL)) {
1395 // Edge from an inner loop to an outer loop. Add to the outer loop.
1396 DestLoop->addBasicBlockToLoop(NMBB, *MLI);
1397 } else {
1398 // Edge from two loops with no containment relation. Because these
1399 // are natural loops, we know that the destination block must be the
1400 // header of its loop (adding a branch into a loop elsewhere would
1401 // create an irreducible loop).
1402 assert(DestLoop->getHeader() == Succ &&
1403 "Should not create irreducible loops!");
1404 if (MachineLoop *P = DestLoop->getParentLoop())
1405 P->addBasicBlockToLoop(NMBB, *MLI);
1406 }
1407 }
1408 }
1409
1410 return NMBB;
1411}
1412
1413bool MachineBasicBlock::canSplitCriticalEdge(const MachineBasicBlock *Succ,
1414 const MachineLoopInfo *MLI) const {
1415 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1416 // it in this generic function.
1417 if (Succ->isEHPad())
1418 return false;
1419
1420 // Splitting the critical edge to a callbr's indirect block isn't advised.
1421 // Don't do it in this generic function.
1422 if (Succ->isInlineAsmBrIndirectTarget())
1423 return false;
1424
1425 const MachineFunction *MF = getParent();
1426 // Performance might be harmed on HW that implements branching using exec mask
1427 // where both sides of the branches are always executed.
1428
1429 if (MF->getTarget().requiresStructuredCFG()) {
1430 if (!MLI)
1431 return false;
1432 const MachineLoop *L = MLI->getLoopFor(Succ);
1433 // Only if `Succ` is a loop header, splitting the critical edge will not
1434 // break structured CFG. And fallthrough to check if this's terminator is
1435 // analyzable.
1436 if (!L || L->getHeader() != Succ)
1437 return false;
1438 }
1439
1440 // Do we have an Indirect jump with a jumptable that we can rewrite?
1441 int JTI = findJumpTableIndex(*this);
1442 if (JTI >= 0 && !jumpTableHasOtherUses(*MF, *this, JTI))
1443 return true;
1444
1445 // We may need to update this's terminator, but we can't do that if
1446 // analyzeBranch fails.
1448 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1450 // AnalyzeBanch should modify this, since we did not allow modification.
1451 if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
1452 /*AllowModify*/ false))
1453 return false;
1454
1455 // Avoid bugpoint weirdness: A block may end with a conditional branch but
1456 // jumps to the same MBB is either case. We have duplicate CFG edges in that
1457 // case that we can't handle. Since this never happens in properly optimized
1458 // code, just skip those edges.
1459 if (TBB && TBB == FBB) {
1460 LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
1461 << printMBBReference(*this) << '\n');
1462 return false;
1463 }
1464 return true;
1465}
1466
1467/// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1468/// neighboring instructions so the bundle won't be broken by removing MI.
1470 // Removing the first instruction in a bundle.
1471 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1472 MI->unbundleFromSucc();
1473 // Removing the last instruction in a bundle.
1474 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1475 MI->unbundleFromPred();
1476 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1477 // are already fine.
1478}
1479
1485
1488 MI->clearFlag(MachineInstr::BundledPred);
1489 MI->clearFlag(MachineInstr::BundledSucc);
1490 return Insts.remove(MI);
1491}
1492
1495 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1496 "Cannot insert instruction with bundle flags");
1497 // Set the bundle flags when inserting inside a bundle.
1498 if (I != instr_end() && I->isBundledWithPred()) {
1499 MI->setFlag(MachineInstr::BundledPred);
1500 MI->setFlag(MachineInstr::BundledSucc);
1501 }
1502 return Insts.insert(I, MI);
1503}
1504
1505/// This method unlinks 'this' from the containing function, and returns it, but
1506/// does not delete it.
1508 assert(getParent() && "Not embedded in a function!");
1509 getParent()->remove(this);
1510 return this;
1511}
1512
1513/// This method unlinks 'this' from the containing function, and deletes it.
1515 assert(getParent() && "Not embedded in a function!");
1516 getParent()->erase(this);
1517}
1518
1519/// Given a machine basic block that branched to 'Old', change the code and CFG
1520/// so that it branches to 'New' instead.
1522 MachineBasicBlock *New) {
1523 assert(Old != New && "Cannot replace self with self!");
1524
1526 while (I != instr_begin()) {
1527 --I;
1528 if (!I->isTerminator()) break;
1529
1530 // Scan the operands of this machine instruction, replacing any uses of Old
1531 // with New.
1532 for (MachineOperand &MO : I->operands())
1533 if (MO.isMBB() && MO.getMBB() == Old)
1534 MO.setMBB(New);
1535 }
1536
1537 // Update the successor information.
1538 replaceSuccessor(Old, New);
1539}
1540
1541void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old,
1542 MachineBasicBlock *New) {
1543 for (MachineInstr &MI : phis())
1544 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
1545 MachineOperand &MO = MI.getOperand(i);
1546 if (MO.getMBB() == Old)
1547 MO.setMBB(New);
1548 }
1549}
1550
1551/// Find the next valid DebugLoc starting at MBBI, skipping any debug
1552/// instructions. Return UnknownLoc if there is none.
1555 // Skip debug declarations, we don't want a DebugLoc from them.
1557 if (MBBI != instr_end())
1558 return MBBI->getDebugLoc();
1559 return {};
1560}
1561
1563 if (MBBI == instr_rend())
1564 return findDebugLoc(instr_begin());
1565 // Skip debug declarations, we don't want a DebugLoc from them.
1567 if (!MBBI->isDebugInstr())
1568 return MBBI->getDebugLoc();
1569 return {};
1570}
1571
1572/// Find the previous valid DebugLoc preceding MBBI, skipping any debug
1573/// instructions. Return UnknownLoc if there is none.
1575 if (MBBI == instr_begin())
1576 return {};
1577 // Skip debug instructions, we don't want a DebugLoc from them.
1579 if (!MBBI->isDebugInstr())
1580 return MBBI->getDebugLoc();
1581 return {};
1582}
1583
1585 if (MBBI == instr_rend())
1586 return {};
1587 // Skip debug declarations, we don't want a DebugLoc from them.
1589 if (MBBI != instr_rend())
1590 return MBBI->getDebugLoc();
1591 return {};
1592}
1593
1594/// Find and return the merged DebugLoc of the branch instructions of the block.
1595/// Return UnknownLoc if there is none.
1598 DebugLoc DL;
1599 auto TI = getFirstTerminator();
1600 while (TI != end() && !TI->isBranch())
1601 ++TI;
1602
1603 if (TI != end()) {
1604 DL = TI->getDebugLoc();
1605 for (++TI ; TI != end() ; ++TI)
1606 if (TI->isBranch())
1607 DL = DebugLoc::getMergedLocation(DL, TI->getDebugLoc());
1608 }
1609 return DL;
1610}
1611
1612/// Return probability of the edge from this block to MBB.
1615 if (Probs.empty())
1616 return BranchProbability(1, succ_size());
1617
1618 const auto &Prob = *getProbabilityIterator(Succ);
1619 if (!Prob.isUnknown())
1620 return Prob;
1621 // For unknown probabilities, collect the sum of all known ones, and evenly
1622 // ditribute the complemental of the sum to each unknown probability.
1623 unsigned KnownProbNum = 0;
1624 auto Sum = BranchProbability::getZero();
1625 for (const auto &P : Probs) {
1626 if (!P.isUnknown()) {
1627 Sum += P;
1628 KnownProbNum++;
1629 }
1630 }
1631 return Sum.getCompl() / (Probs.size() - KnownProbNum);
1632}
1633
1635 if (succ_size() <= 1)
1636 return true;
1638 return true;
1639
1640 SmallVector<BranchProbability, 8> Normalized(Probs.begin(), Probs.end());
1642
1643 // Normalize assuming unknown probabilities. This will assign equal
1644 // probabilities to all successors.
1645 SmallVector<BranchProbability, 8> Equal(Normalized.size());
1647
1648 return llvm::equal(Normalized, Equal);
1649}
1650
1651/// Set successor probability of a given iterator.
1653 BranchProbability Prob) {
1654 assert(!Prob.isUnknown());
1655 if (Probs.empty())
1656 return;
1657 *getProbabilityIterator(I) = Prob;
1658}
1659
1660/// Return probability iterator corresonding to the I successor iterator
1661MachineBasicBlock::const_probability_iterator
1662MachineBasicBlock::getProbabilityIterator(
1664 assert(Probs.size() == Successors.size() && "Async probability list!");
1665 const size_t index = std::distance(Successors.begin(), I);
1666 assert(index < Probs.size() && "Not a current successor!");
1667 return Probs.begin() + index;
1668}
1669
1670/// Return probability iterator corresonding to the I successor iterator.
1671MachineBasicBlock::probability_iterator
1672MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1673 assert(Probs.size() == Successors.size() && "Async probability list!");
1674 const size_t index = std::distance(Successors.begin(), I);
1675 assert(index < Probs.size() && "Not a current successor!");
1676 return Probs.begin() + index;
1677}
1678
1679/// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1680/// as of just before "MI".
1681///
1682/// Search is localised to a neighborhood of
1683/// Neighborhood instructions before (searching for defs or kills) and N
1684/// instructions after (searching just for defs) MI.
1687 MCRegister Reg, const_iterator Before,
1688 unsigned Neighborhood) const {
1689 assert(Reg.isPhysical());
1690 unsigned N = Neighborhood;
1691
1692 // Try searching forwards from Before, looking for reads or defs.
1693 const_iterator I(Before);
1694 for (; I != end() && N > 0; ++I) {
1695 if (I->isDebugOrPseudoInstr())
1696 continue;
1697
1698 --N;
1699
1700 PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
1701
1702 // Register is live when we read it here.
1703 if (Info.Read)
1704 return LQR_Live;
1705 // Register is dead if we can fully overwrite or clobber it here.
1706 if (Info.FullyDefined || Info.Clobbered)
1707 return LQR_Dead;
1708 }
1709
1710 // If we reached the end, it is safe to clobber Reg at the end of a block of
1711 // no successor has it live in.
1712 if (I == end()) {
1713 for (MachineBasicBlock *S : successors()) {
1714 for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
1715 if (TRI->regsOverlap(LI.PhysReg, Reg))
1716 return LQR_Live;
1717 }
1718 }
1719
1720 return LQR_Dead;
1721 }
1722
1723
1724 N = Neighborhood;
1725
1726 // Start by searching backwards from Before, looking for kills, reads or defs.
1727 I = const_iterator(Before);
1728 // If this is the first insn in the block, don't search backwards.
1729 if (I != begin()) {
1730 do {
1731 --I;
1732
1733 if (I->isDebugOrPseudoInstr())
1734 continue;
1735
1736 --N;
1737
1738 PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
1739
1740 // Defs happen after uses so they take precedence if both are present.
1741
1742 // Register is dead after a dead def of the full register.
1743 if (Info.DeadDef)
1744 return LQR_Dead;
1745 // Register is (at least partially) live after a def.
1746 if (Info.Defined) {
1747 if (!Info.PartialDeadDef)
1748 return LQR_Live;
1749 // As soon as we saw a partial definition (dead or not),
1750 // we cannot tell if the value is partial live without
1751 // tracking the lanemasks. We are not going to do this,
1752 // so fall back on the remaining of the analysis.
1753 break;
1754 }
1755 // Register is dead after a full kill or clobber and no def.
1756 if (Info.Killed || Info.Clobbered)
1757 return LQR_Dead;
1758 // Register must be live if we read it.
1759 if (Info.Read)
1760 return LQR_Live;
1761
1762 } while (I != begin() && N > 0);
1763 }
1764
1765 // If all the instructions before this in the block are debug instructions,
1766 // skip over them.
1767 while (I != begin() && std::prev(I)->isDebugOrPseudoInstr())
1768 --I;
1769
1770 // Did we get to the start of the block?
1771 if (I == begin()) {
1772 // If so, the register's state is definitely defined by the live-in state.
1774 if (TRI->regsOverlap(LI.PhysReg, Reg))
1775 return LQR_Live;
1776
1777 return LQR_Dead;
1778 }
1779
1780 // At this point we have no idea of the liveness of the register.
1781 return LQR_Unknown;
1782}
1783
1784const uint32_t *
1786 // EH funclet entry does not preserve any registers.
1787 return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1788}
1789
1790const uint32_t *
1792 // If we see a return block with successors, this must be a funclet return,
1793 // which does not preserve any registers. If there are no successors, we don't
1794 // care what kind of return it is, putting a mask after it is a no-op.
1795 return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1796}
1797
1799 LiveIns.clear();
1800}
1801
1803 std::vector<RegisterMaskPair> &OldLiveIns) {
1804 assert(OldLiveIns.empty() && "Vector must be empty");
1805 std::swap(LiveIns, OldLiveIns);
1806}
1807
1809 assert(getParent()->getProperties().hasTracksLiveness() &&
1810 "Liveness information is accurate");
1811 return LiveIns.begin();
1812}
1813
1815 const MachineFunction &MF = *getParent();
1816 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1817 MCRegister ExceptionPointer, ExceptionSelector;
1818 if (MF.getFunction().hasPersonalityFn()) {
1819 auto PersonalityFn = MF.getFunction().getPersonalityFn();
1820 ExceptionPointer = TLI.getExceptionPointerRegister(PersonalityFn);
1821 ExceptionSelector = TLI.getExceptionSelectorRegister(PersonalityFn);
1822 }
1823
1824 return liveout_iterator(*this, ExceptionPointer, ExceptionSelector, false);
1825}
1826
1828 unsigned Cntr = 0;
1829 auto R = instructionsWithoutDebug(begin(), end());
1830 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1831 if (++Cntr > Limit)
1832 return true;
1833 }
1834 return false;
1835}
1836
1838 const MachineBasicBlock &PredMBB) {
1839 for (MachineInstr &Phi : phis())
1840 Phi.removePHIIncomingValueFor(PredMBB);
1841}
1842
1844const MBBSectionID
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:638
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define GET_RESULT(RESULT, GETTER, INFIX)
static bool jumpTableHasOtherUses(const MachineFunction &MF, const MachineBasicBlock &IgnoreMBB, int JumpTableIndex)
static void unbundleSingleMI(MachineInstr *MI)
Prepare MI to be removed from its bundle.
static int findJumpTableIndex(const MachineBasicBlock &MBB)
static cl::opt< bool > PrintSlotIndexes("print-slotindexes", cl::desc("When printing machine IR, annotate instructions and blocks with " "SlotIndexes when available"), cl::init(true), cl::Hidden)
Register const TargetRegisterInfo * TRI
uint64_t IntrinsicInst * II
#define P(N)
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg)
This file contains some templates that are useful if you are working with the STL at all.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:114
This file describes how to lower LLVM code to machine code.
SlotIndexUpdateDelegate(MachineFunction &MF, SlotIndexes *Indexes)
void MF_HandleRemoval(MachineInstr &MI) override
Callback before a removal. This should not modify the MI directly.
void MF_HandleInsertion(MachineInstr &MI) override
Callback after an insertion. This should not modify the MI directly.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static uint32_t getDenominator()
static BranchProbability getUnknown()
uint32_t getNumerator() const
static BranchProbability getZero()
static void normalizeProbabilities(ProbabilityIter Begin, ProbabilityIter End)
A debug info location.
Definition DebugLoc.h:123
LLVM_ABI unsigned getLine() const
Definition DebugLoc.cpp:52
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:179
LLVM_ABI unsigned getCol() const
Definition DebugLoc.cpp:57
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:903
Constant * getPersonalityFn() const
Get the personality function associated with this function.
void splitCriticalEdge(BasicBlockT *FromBB, BasicBlockT *ToBB, BasicBlockT *NewBB)
Apply updates that the critical edge (FromBB, ToBB) has been split with NewBB.
A helper class to return the specified delimiter string after the first invocation of operator String...
LiveInterval - This class represents the liveness of a register, or stack slot.
iterator_range< subrange_iterator > subranges()
void insertMBBInMaps(MachineBasicBlock *MBB)
A set of physical registers with utility functions to track liveness when walking backward/forward th...
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
bool liveAt(SlotIndex index) const
LLVM_ABI void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified interval from this live range.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Context object for machine code objects.
Definition MCContext.h:83
LLVM_ABI MCSymbol * createBlockSymbol(const Twine &Name, bool AlwaysEmit=false)
Get or create a symbol for a basic block.
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition MCRegister.h:72
Iterator that enumerates the sub-registers of a Reg and the associated sub-register indices.
bool isValid() const
Returns true if this iterator is not yet at the end.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
LLVM_ABI DebugLoc rfindPrevDebugLoc(reverse_instr_iterator MBBI)
Has exact same behavior as findPrevDebugLoc (it also searches towards the beginning of this MBB) exce...
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI bool hasEHPadSuccessor() const
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
livein_iterator livein_end() const
LLVM_ABI iterator getFirstTerminatorForward()
Finds the first terminator in a block by scanning forward.
bool isEHPad() const
Returns true if the block is a landing pad.
LLVM_ABI void replacePhiUsesWith(MachineBasicBlock *Old, MachineBasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI MachineInstr * remove_instr(MachineInstr *I)
Remove the possibly bundled instruction from the instruction list without deleting it.
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
LLVM_ABI void moveBefore(MachineBasicBlock *NewAfter)
Move 'this' block before or after the specified block.
LLVM_ABI void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
LLVM_ABI MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
LLVM_ABI void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
MachineBasicBlock * SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P, std::vector< SparseBitVector<> > *LiveInSets=nullptr, MachineDomTreeUpdater *MDTU=nullptr)
bool hasLabelMustBeEmitted() const
Test whether this block must have its label emitted.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI BranchProbability getSuccProbability(const_succ_iterator Succ) const
Return probability of the edge from this block to MBB.
iterator_range< livein_iterator > liveins() const
iterator_range< iterator > phis()
Returns a range that iterates over the phis in the basic block.
reverse_instr_iterator instr_rbegin()
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator SkipPHIsAndLabels(iterator I)
Return the first instruction in MBB after I that is not a PHI or a label.
LLVM_ABI void addSuccessorWithoutProb(MachineBasicBlock *Succ)
Add Succ as a successor of this MachineBasicBlock.
SmallVectorImpl< MachineBasicBlock * >::const_iterator const_succ_iterator
LLVM_ABI bool hasName() const
Check if there is a name of corresponding LLVM basic block.
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
std::optional< UniqueBBID > getBBID() const
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI MCSymbol * getEHContSymbol() const
Return the Windows EH Continuation Symbol for this basic block.
LLVM_ABI void splitSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New, bool NormalizeSuccProbs=false)
Split the old successor into old plus new and updates the probability info.
@ PrintNameIr
Add IR name where available.
@ PrintNameAttributes
Print attributes.
LLVM_ABI void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor)
Update the terminator instructions in block to account for changes to block layout which may have bee...
LLVM_ABI const MachineBasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor.
LLVM_ABI iterator SkipPHIsLabelsAndDebug(iterator I, Register Reg=Register(), bool SkipPseudoOp=true)
Return the first instruction in MBB after I that is not a PHI, label or debug.
LLVM_ABI bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
LLVM_ABI void setSuccProbability(succ_iterator I, BranchProbability Prob)
Set successor probability of a given iterator.
LLVM_ABI iterator getFirstNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the first non-debug instruction in the basic block, or end().
LLVM_ABI void removeLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Remove the specified register from the live in set.
LLVM_ABI void printAsOperand(raw_ostream &OS, bool PrintType=true) const
LLVM_ABI void validateSuccProbs() const
Validate successors' probabilities and check if the sum of them is approximate one.
bool isIRBlockAddressTaken() const
Test whether this block is the target of an IR BlockAddress.
LiveInVector::const_iterator livein_iterator
LLVM_ABI MCSymbol * getEndSymbol() const
Returns the MCSymbol marking the end of this basic block.
LLVM_ABI void clearLiveIns()
Clear live in list.
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
LLVM_ABI LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI, MCRegister Reg, const_iterator Before, unsigned Neighborhood=10) const
Return whether (physical) register Reg has been defined and not killed as of just before Before.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI livein_iterator livein_begin() const
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
LLVM_ABI const uint32_t * getBeginClobberMask(const TargetRegisterInfo *TRI) const
Get the clobber mask for the start of this basic block.
LLVM_ABI void removePHIsIncomingValuesForPredecessor(const MachineBasicBlock &PredMBB)
Iterate over block PHI instructions and remove all incoming values for PredMBB.
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
LLVM_ABI void dump() const
LLVM_ABI bool isEntryBlock() const
Returns true if this is the entry block of the function.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI void copySuccessor(const MachineBasicBlock *Orig, succ_iterator I)
Copy a successor (and any probability info) from original block to this block's.
SmallVectorImpl< MachineBasicBlock * >::iterator succ_iterator
BasicBlock * getAddressTakenIRBlock() const
Retrieves the BasicBlock which corresponds to this MachineBasicBlock.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
LLVM_ABI const MachineBasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI liveout_iterator liveout_begin() const
Iterator scanning successor basic blocks' liveins to determine the registers potentially live at the ...
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isPredecessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a predecessor of this block.
bool hasSuccessorProbabilities() const
Return true if any of the successors have probabilities attached to them.
LLVM_ABI DebugLoc rfindDebugLoc(reverse_instr_iterator MBBI)
Has exact same behavior as findDebugLoc (it also searches towards the end of this MBB) except that th...
LLVM_ABI void print(raw_ostream &OS, const SlotIndexes *=nullptr, bool IsStandalone=true) const
reverse_instr_iterator instr_rend()
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
Instructions::iterator instr_iterator
LLVM_ABI iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
LLVM_ABI void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New)
Given a machine basic block that branched to 'Old', change the code and CFG so that it branches to 'N...
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
LLVM_ABI DebugLoc findPrevDebugLoc(instr_iterator MBBI)
Find the previous valid DebugLoc preceding MBBI, skipping any debug instructions.
LLVM_ABI MachineBasicBlock * splitAt(MachineInstr &SplitInst, bool UpdateLiveIns=true, LiveIntervals *LIS=nullptr)
Split a basic block into 2 pieces at SplitPoint.
LLVM_ABI bool canSplitCriticalEdge(const MachineBasicBlock *Succ, const MachineLoopInfo *MLI=nullptr) const
Check if the edge between this block and the given successor Succ, can be split.
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
LLVM_ABI void removeLiveInOverlappedWith(MCRegister Reg)
Remove the specified register from any overlapped live in.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
LLVM_ABI std::string getFullName() const
Return a formatted string to identify this block and its parent function.
bool isBeginSection() const
Returns true if this block begins any section.
unsigned getCallFrameSize() const
Return the call frame size on entry to this basic block.
LLVM_ABI DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
iterator_range< succ_iterator > successors()
LLVM_ABI instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
reverse_iterator rbegin()
bool isMachineBlockAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
LLVM_ABI void printName(raw_ostream &os, unsigned printNameFlags=PrintNameIr, ModuleSlotTracker *moduleSlotTracker=nullptr) const
Print the basic block's name as:
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
iterator_range< pred_iterator > predecessors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
Align getAlignment() const
Return alignment of the basic block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool isLegalToHoistInto() const
Returns true if it is legal to hoist instructions into this block.
LLVM_ABI bool canPredictBranchProbabilities() const
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
LLVM_ABI bool mayHaveInlineAsmBr() const
Returns true if this block may have an INLINEASM_BR (overestimate, by checking if any of the successo...
LivenessQueryResult
Possible outcome of a register liveness query to computeRegisterLiveness()
@ LQR_Dead
Register is known to be fully dead.
@ LQR_Live
Register is known to be (at least partially) live.
@ LQR_Unknown
Register liveness not decidable from local neighborhood.
LLVM_ABI void moveAfter(MachineBasicBlock *NewBefore)
LLVM_ABI const uint32_t * getEndClobberMask(const TargetRegisterInfo *TRI) const
Get the clobber mask for the end of the basic block.
LLVM_ABI bool sizeWithoutDebugLargerThan(unsigned Limit) const
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
LLVM_ABI MachineBasicBlock * removeFromParent()
This method unlinks 'this' from the containing function, and returns it, but does not delete it.
Instructions::reverse_iterator reverse_instr_iterator
unsigned addToMBBNumbering(MachineBasicBlock *MBB)
Adds the MBB to the internal numbering.
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool hasBBSections() const
Returns true if this function has basic block sections enabled.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
void remove(iterator MBBI)
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
void splice(iterator InsertPt, iterator MBBI)
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void erase(iterator MBBI)
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
BasicBlockListType::const_iterator const_iterator
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
Representation of each machine instruction.
LLVM_ABI bool ReplaceMBBInJumpTable(unsigned Idx, MachineBasicBlock *Old, MachineBasicBlock *New)
ReplaceMBBInJumpTable - If Old is a target of the jump tables, update the jump table to branch to New...
const std::vector< MachineJumpTableEntry > & getJumpTables() const
MachineOperand class - Representation of each machine instruction operand.
MachineBasicBlock * getMBB() const
void setMBB(MachineBasicBlock *MBB)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Manage lifetime of a slot tracker for printing IR.
int getLocalSlot(const Value *V)
Return the slot number of the specified local value.
void incorporateFunction(const Function &F)
Incorporate the given function.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
Simple wrapper around std::function<void(raw_ostream&)>.
Definition Printable.h:38
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
SlotIndexes pass.
void insertMBBInMaps(MachineBasicBlock *mbb)
Add the given MachineBasicBlock into the maps.
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
bool hasIndex(const MachineInstr &instr) const
Returns true if the given machine instr is mapped to an index, otherwise returns false.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:133
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:175
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:183
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
TargetInstrInfo - Interface to description of machine instruction set.
virtual Register getExceptionPointerRegister(const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception address on entry to an ...
virtual Register getExceptionSelectorRegister(const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception typeid on entry to a la...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
bool requiresStructuredCFG() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
VNInfo - Value Number Information.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an SmallVector or SmallString.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Kill
The last use of a register.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1763
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI PhysRegInfo AnalyzePhysRegInBundle(const MachineInstr &MI, Register Reg, const TargetRegisterInfo *TRI)
AnalyzePhysRegInBundle - Analyze how the current instruction or bundle uses a physical register.
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
Definition LaneBitmask.h:92
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1634
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
IterT skipDebugInstructionsBackward(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It until it points to a non-debug instruction or to Begin and return the resulting iterator...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:129
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:105
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1770
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1945
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2136
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
void addLiveIns(MachineBasicBlock &MBB, const LivePhysRegs &LiveRegs)
Adds registers contained in LiveRegs to the block live-in list of MBB.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
This represents a simple continuous liveness interval for a value.
LLVM_ABI static const MBBSectionID ExceptionSectionID
LLVM_ABI static const MBBSectionID ColdSectionID
Pair of physical register and lane mask.
Split the critical edge from this block to the given successor block, and return the newly created bl...
MachineJumpTableEntry - One jump table in the jump table info.
std::vector< MachineBasicBlock * > MBBs
MBBs - The vector of basic blocks from which to create the jump table.
Information about how a physical register Reg is used by a set of operands.
static void deleteNode(NodeTy *V)
Definition ilist.h:42
void removeNodeFromList(NodeTy *)
Definition ilist.h:67
void addNodeToList(NodeTy *)
When an MBB is added to an MF, we need to update the parent pointer of the MBB, the MBB numbering,...
Definition ilist.h:66
void transferNodesFromList(ilist_callback_traits &OldList, Iterator, Iterator)
Callback before transferring nodes to this list.
Definition ilist.h:72
Template traits for intrusive list.
Definition ilist.h:90