LLVM 23.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 N->AnalysisNumber = MF.assignAnalysisNumber();
136
137 // Make sure the instructions have their operands in the reginfo lists.
139 for (MachineInstr &MI : N->instrs())
140 MI.addRegOperandsToUseLists(RegInfo);
141}
142
145 N->getParent()->removeFromMBBNumbering(N->Number);
146 N->Number = -1;
147 N->AnalysisNumber = -1;
148}
149
150/// When we add an instruction to a basic block list, we update its parent
151/// pointer and add its operands from reg use/def lists if appropriate.
153 assert(!N->getParent() && "machine instruction already in a basic block");
154 N->setParent(Parent);
155
156 // Add the instruction's register operands to their corresponding
157 // use/def lists.
158 MachineFunction *MF = Parent->getParent();
159 N->addRegOperandsToUseLists(MF->getRegInfo());
160 MF->handleInsertion(*N);
161}
162
163/// When we remove an instruction from a basic block list, we update its parent
164/// pointer and remove its operands from reg use/def lists if appropriate.
166 assert(N->getParent() && "machine instruction not in a basic block");
167
168 // Remove from the use/def lists.
169 if (MachineFunction *MF = N->getMF()) {
170 MF->handleRemoval(*N);
171 N->removeRegOperandsFromUseLists(MF->getRegInfo());
172 }
173
174 N->setParent(nullptr);
175}
176
177/// When moving a range of instructions from one MBB list to another, we need to
178/// update the parent pointers and the use/def lists.
180 instr_iterator First,
181 instr_iterator Last) {
182 assert(Parent->getParent() == FromList.Parent->getParent() &&
183 "cannot transfer MachineInstrs between MachineFunctions");
184
185 // If it's within the same BB, there's nothing to do.
186 if (this == &FromList)
187 return;
188
189 assert(Parent != FromList.Parent && "Two lists have the same parent?");
190
191 // If splicing between two blocks within the same function, just update the
192 // parent pointers.
193 for (; First != Last; ++First)
194 First->setParent(Parent);
195}
196
198 assert(!MI->getParent() && "MI is still in a block!");
199 Parent->getParent()->deleteMachineInstr(MI);
200}
201
204 while (I != E && I->isPHI())
205 ++I;
206 assert((I == E || !I->isInsideBundle()) &&
207 "First non-phi MI cannot be inside a bundle!");
208 return I;
209}
210
214
215 iterator E = end();
216 while (I != E && (I->isPHI() || I->isPosition() ||
217 TII->isBasicBlockPrologue(*I)))
218 ++I;
219 // FIXME: This needs to change if we wish to bundle labels
220 // inside the bundle.
221 assert((I == E || !I->isInsideBundle()) &&
222 "First non-phi / non-label instruction is inside a bundle!");
223 return I;
224}
225
228 Register Reg, bool SkipPseudoOp) {
230
231 iterator E = end();
232 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() ||
233 (SkipPseudoOp && I->isPseudoProbe()) ||
234 TII->isBasicBlockPrologue(*I, Reg)))
235 ++I;
236 // FIXME: This needs to change if we wish to bundle labels / dbg_values
237 // inside the bundle.
238 assert((I == E || !I->isInsideBundle()) &&
239 "First non-phi / non-label / non-debug "
240 "instruction is inside a bundle!");
241 return I;
242}
243
245 iterator B = begin(), E = end(), I = E;
246 while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
247 ; /*noop */
248 while (I != E && !I->isTerminator())
249 ++I;
250 return I;
251}
252
254 instr_iterator B = instr_begin(), E = instr_end(), I = E;
255 while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
256 ; /*noop */
257 while (I != E && !I->isTerminator())
258 ++I;
259 return I;
260}
261
263 return find_if(instrs(), [](auto &II) { return II.isTerminator(); });
264}
265
268 // Skip over begin-of-block dbg_value instructions.
269 return skipDebugInstructionsForward(begin(), end(), SkipPseudoOp);
270}
271
274 // Skip over end-of-block dbg_value instructions.
276 while (I != B) {
277 --I;
278 // Return instruction that starts a bundle.
279 if (I->isDebugInstr() || I->isInsideBundle())
280 continue;
281 if (SkipPseudoOp && I->isPseudoProbe())
282 continue;
283 return I;
284 }
285 // The block is all debug values.
286 return end();
287}
288
290 for (const MachineBasicBlock *Succ : successors())
291 if (Succ->isEHPad())
292 return true;
293 return false;
294}
295
297 return getParent()->begin() == getIterator();
298}
299
300#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
304#endif
305
307 for (const MachineBasicBlock *Succ : successors()) {
308 if (Succ->isInlineAsmBrIndirectTarget())
309 return true;
310 }
311 return false;
312}
313
316 return false;
317 return true;
318}
319
321 if (const BasicBlock *LBB = getBasicBlock())
322 return LBB->hasName();
323 return false;
324}
325
327 if (const BasicBlock *LBB = getBasicBlock())
328 return LBB->getName();
329 else
330 return StringRef("", 0);
331}
332
333/// Return a hopefully unique identifier for this block.
335 std::string Name;
336 if (getParent())
337 Name = (getParent()->getName() + ":").str();
338 if (getBasicBlock())
339 Name += getBasicBlock()->getName();
340 else
341 Name += ("BB" + Twine(getNumber())).str();
342 return Name;
343}
344
346 bool IsStandalone) const {
347 const MachineFunction *MF = getParent();
348 if (!MF) {
349 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
350 << " is null\n";
351 return;
352 }
353 const Function &F = MF->getFunction();
354 const Module *M = F.getParent();
355 ModuleSlotTracker MST(M);
357 print(OS, MST, Indexes, IsStandalone);
358}
359
361 const SlotIndexes *Indexes,
362 bool IsStandalone) const {
363 const MachineFunction *MF = getParent();
364 if (!MF) {
365 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
366 << " is null\n";
367 return;
368 }
369
370 if (Indexes && PrintSlotIndexes)
371 OS << Indexes->getMBBStartIdx(this) << '\t';
372
374 OS << ":\n";
375
377 const MachineRegisterInfo &MRI = MF->getRegInfo();
379 bool HasLineAttributes = false;
380
381 // Print the preds of this block according to the CFG.
382 if (!pred_empty() && IsStandalone) {
383 if (Indexes) OS << '\t';
384 // Don't indent(2), align with previous line attributes.
385 OS << "; predecessors: ";
386 ListSeparator LS;
387 for (auto *Pred : predecessors())
388 OS << LS << printMBBReference(*Pred);
389 OS << '\n';
390 HasLineAttributes = true;
391 }
392
393 if (!succ_empty()) {
394 if (Indexes) OS << '\t';
395 // Print the successors
396 OS.indent(2) << "successors: ";
397 ListSeparator LS;
398 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
399 OS << LS << printMBBReference(**I);
400 if (!Probs.empty())
401 OS << '('
402 << format("0x%08" PRIx32, getSuccProbability(I).getNumerator())
403 << ')';
404 }
405 if (!Probs.empty() && IsStandalone) {
406 // Print human readable probabilities as comments.
407 OS << "; ";
408 ListSeparator LS;
409 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
411 OS << LS << printMBBReference(**I) << '('
412 << format("%.2f%%",
413 rint(((double)BP.getNumerator() / BP.getDenominator()) *
414 100.0 * 100.0) /
415 100.0)
416 << ')';
417 }
418 }
419
420 OS << '\n';
421 HasLineAttributes = true;
422 }
423
424 if (!livein_empty() && MRI.tracksLiveness()) {
425 if (Indexes) OS << '\t';
426 OS.indent(2) << "liveins: ";
427
428 ListSeparator LS;
429 for (const auto &LI : liveins()) {
430 OS << LS << printReg(LI.PhysReg, TRI);
431 if (!LI.LaneMask.all())
432 OS << ":0x" << PrintLaneMask(LI.LaneMask);
433 }
434 HasLineAttributes = true;
435 }
436
437 if (HasLineAttributes)
438 OS << '\n';
439
440 bool IsInBundle = false;
441 for (const MachineInstr &MI : instrs()) {
442 if (Indexes && PrintSlotIndexes) {
443 if (Indexes->hasIndex(MI))
444 OS << Indexes->getInstructionIndex(MI);
445 OS << '\t';
446 }
447
448 if (IsInBundle && !MI.isInsideBundle()) {
449 OS.indent(2) << "}\n";
450 IsInBundle = false;
451 }
452
453 OS.indent(IsInBundle ? 4 : 2);
454 MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
455 /*AddNewLine=*/false, &TII);
456
457 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
458 OS << " {";
459 IsInBundle = true;
460 }
461 OS << '\n';
462 }
463
464 if (IsInBundle)
465 OS.indent(2) << "}\n";
466
467 if (IrrLoopHeaderWeight && IsStandalone) {
468 if (Indexes) OS << '\t';
469 OS.indent(2) << "; Irreducible loop header weight: " << *IrrLoopHeaderWeight
470 << '\n';
471 }
472}
473
474/// Print the basic block's name as:
475///
476/// bb.{number}[.{ir-name}] [(attributes...)]
477///
478/// The {ir-name} is only printed when the \ref PrintNameIr flag is passed
479/// (which is the default). If the IR block has no name, it is identified
480/// numerically using the attribute syntax as "(%ir-block.{ir-slot})".
481///
482/// When the \ref PrintNameAttributes flag is passed, additional attributes
483/// of the block are printed when set.
484///
485/// \param printNameFlags Combination of \ref PrintNameFlag flags indicating
486/// the parts to print.
487/// \param moduleSlotTracker Optional ModuleSlotTracker. This method will
488/// incorporate its own tracker when necessary to
489/// determine the block's IR name.
490void MachineBasicBlock::printName(raw_ostream &os, unsigned printNameFlags,
491 ModuleSlotTracker *moduleSlotTracker) const {
492 os << "bb." << getNumber();
493 bool hasAttributes = false;
494
495 auto PrintBBRef = [&](const BasicBlock *bb) {
496 os << "%ir-block.";
497 if (bb->hasName()) {
498 os << bb->getName();
499 } else {
500 int slot = -1;
501
502 if (moduleSlotTracker) {
503 slot = moduleSlotTracker->getLocalSlot(bb);
504 } else if (bb->getParent()) {
505 ModuleSlotTracker tmpTracker(bb->getModule(), false);
506 tmpTracker.incorporateFunction(*bb->getParent());
507 slot = tmpTracker.getLocalSlot(bb);
508 }
509
510 if (slot == -1)
511 os << "<ir-block badref>";
512 else
513 os << slot;
514 }
515 };
516
517 if (printNameFlags & PrintNameIr) {
518 if (const auto *bb = getBasicBlock()) {
519 if (bb->hasName()) {
520 os << '.' << bb->getName();
521 } else {
522 hasAttributes = true;
523 os << " (";
524 PrintBBRef(bb);
525 }
526 }
527 }
528
529 if (printNameFlags & PrintNameAttributes) {
531 os << (hasAttributes ? ", " : " (");
532 os << "machine-block-address-taken";
533 hasAttributes = true;
534 }
535 if (isIRBlockAddressTaken()) {
536 os << (hasAttributes ? ", " : " (");
537 os << "ir-block-address-taken ";
538 PrintBBRef(getAddressTakenIRBlock());
539 hasAttributes = true;
540 }
541 if (isEHPad()) {
542 os << (hasAttributes ? ", " : " (");
543 os << "landing-pad";
544 hasAttributes = true;
545 }
547 os << (hasAttributes ? ", " : " (");
548 os << "inlineasm-br-indirect-target";
549 hasAttributes = true;
550 }
551 if (isEHFuncletEntry()) {
552 os << (hasAttributes ? ", " : " (");
553 os << "ehfunclet-entry";
554 hasAttributes = true;
555 }
556 if (isEHScopeEntry()) {
557 os << (hasAttributes ? ", " : " (");
558 os << "ehscope-entry";
559 hasAttributes = true;
560 }
561 if (getAlignment() != Align(1)) {
562 os << (hasAttributes ? ", " : " (");
563 os << "align " << getAlignment().value();
564 hasAttributes = true;
565 }
566 if (getSectionID() != MBBSectionID(0)) {
567 os << (hasAttributes ? ", " : " (");
568 os << "bbsections ";
569 switch (getSectionID().Type) {
571 os << "Exception";
572 break;
574 os << "Cold";
575 break;
576 default:
577 os << getSectionID().Number;
578 }
579 hasAttributes = true;
580 }
581 if (getBBID().has_value()) {
582 os << (hasAttributes ? ", " : " (");
583 os << "bb_id " << getBBID()->BaseID;
584 if (getBBID()->CloneID != 0)
585 os << " " << getBBID()->CloneID;
586 hasAttributes = true;
587 }
588 if (CallFrameSize != 0) {
589 os << (hasAttributes ? ", " : " (");
590 os << "call-frame-size " << CallFrameSize;
591 hasAttributes = true;
592 }
593 }
594
595 if (hasAttributes)
596 os << ')';
597}
598
600 bool /*PrintType*/) const {
601 OS << '%';
602 printName(OS, 0);
603}
604
606 assert(Reg.isPhysical());
607 LiveInVector::iterator I = find_if(
608 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
609 if (I == LiveIns.end())
610 return;
611
612 I->LaneMask &= ~LaneMask;
613 if (I->LaneMask.none())
614 LiveIns.erase(I);
615}
616
618 const MachineFunction *MF = getParent();
620 // Remove Reg and its subregs from live in set.
621 for (MCPhysReg S : TRI->subregs_inclusive(Reg))
622 removeLiveIn(S);
623
624 // Remove live-in bitmask in super registers as well.
625 for (MCPhysReg Super : TRI->superregs(Reg)) {
626 for (MCSubRegIndexIterator SRI(Super, TRI); SRI.isValid(); ++SRI) {
627 if (Reg == SRI.getSubReg()) {
628 unsigned SubRegIndex = SRI.getSubRegIndex();
629 LaneBitmask SubRegLaneMask = TRI->getSubRegIndexLaneMask(SubRegIndex);
630 removeLiveIn(Super, SubRegLaneMask);
631 break;
632 }
633 }
634 }
635}
636
639 // Get non-const version of iterator.
640 LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
641 return LiveIns.erase(LI);
642}
643
645 assert(Reg.isPhysical());
647 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
648 return I != livein_end() && (I->LaneMask & LaneMask).any();
649}
650
652 llvm::sort(LiveIns,
653 [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
654 return LI0.PhysReg < LI1.PhysReg;
655 });
656 // Liveins are sorted by physreg now we can merge their lanemasks.
657 LiveInVector::const_iterator I = LiveIns.begin();
658 LiveInVector::const_iterator J;
659 LiveInVector::iterator Out = LiveIns.begin();
660 for (; I != LiveIns.end(); ++Out, I = J) {
661 MCRegister PhysReg = I->PhysReg;
662 LaneBitmask LaneMask = I->LaneMask;
663 for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
664 LaneMask |= J->LaneMask;
665 Out->PhysReg = PhysReg;
666 Out->LaneMask = LaneMask;
667 }
668 LiveIns.erase(Out, LiveIns.end());
669}
670
673 assert(getParent() && "MBB must be inserted in function");
674 assert(PhysReg.isPhysical() && "Expected physreg");
675 assert(RC && "Register class is required");
676 assert((isEHPad() || this == &getParent()->front()) &&
677 "Only the entry block and landing pads can have physreg live ins");
678
679 bool LiveIn = isLiveIn(PhysReg);
683
684 // Look for an existing copy.
685 if (LiveIn)
686 for (;I != E && I->isCopy(); ++I)
687 if (I->getOperand(1).getReg() == PhysReg) {
688 Register VirtReg = I->getOperand(0).getReg();
689 if (!MRI.constrainRegClass(VirtReg, RC))
690 llvm_unreachable("Incompatible live-in register class.");
691 return VirtReg;
692 }
693
694 // No luck, create a virtual register.
695 Register VirtReg = MRI.createVirtualRegister(RC);
696 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
697 .addReg(PhysReg, RegState::Kill);
698 if (!LiveIn)
699 addLiveIn(PhysReg);
700 return VirtReg;
701}
702
703void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
704 getParent()->splice(NewAfter->getIterator(), getIterator());
705}
706
707void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
708 getParent()->splice(++NewBefore->getIterator(), getIterator());
709}
710
712 MachineBasicBlock::const_iterator TerminatorI = MBB.getFirstTerminator();
713 if (TerminatorI == MBB.end())
714 return -1;
715 const MachineInstr &Terminator = *TerminatorI;
716 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
717 return TII->getJumpTableIndex(Terminator);
718}
719
721 MachineBasicBlock *PreviousLayoutSuccessor) {
722 LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
723 << "\n");
724
726 // A block with no successors has no concerns with fall-through edges.
727 if (this->succ_empty())
728 return;
729
730 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
733 bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
734 (void) B;
735 assert(!B && "UpdateTerminators requires analyzable predecessors!");
736 if (Cond.empty()) {
737 if (TBB) {
738 // The block has an unconditional branch. If its successor is now its
739 // layout successor, delete the branch.
741 TII->removeBranch(*this);
742 } else {
743 // The block has an unconditional fallthrough, or the end of the block is
744 // unreachable.
745
746 // Unfortunately, whether the end of the block is unreachable is not
747 // immediately obvious; we must fall back to checking the successor list,
748 // and assuming that if the passed in block is in the succesor list and
749 // not an EHPad, it must be the intended target.
750 if (!PreviousLayoutSuccessor || !isSuccessor(PreviousLayoutSuccessor) ||
751 PreviousLayoutSuccessor->isEHPad())
752 return;
753
754 // If the unconditional successor block is not the current layout
755 // successor, insert a branch to jump to it.
756 if (!isLayoutSuccessor(PreviousLayoutSuccessor))
757 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
758 }
759 return;
760 }
761
762 if (FBB) {
763 // The block has a non-fallthrough conditional branch. If one of its
764 // successors is its layout successor, rewrite it to a fallthrough
765 // conditional branch.
766 if (isLayoutSuccessor(TBB)) {
767 if (TII->reverseBranchCondition(Cond))
768 return;
769 TII->removeBranch(*this);
770 TII->insertBranch(*this, FBB, nullptr, Cond, DL);
771 } else if (isLayoutSuccessor(FBB)) {
772 TII->removeBranch(*this);
773 TII->insertBranch(*this, TBB, nullptr, Cond, DL);
774 }
775 return;
776 }
777
778 // We now know we're going to fallthrough to PreviousLayoutSuccessor.
779 assert(PreviousLayoutSuccessor);
780 assert(!PreviousLayoutSuccessor->isEHPad());
781 assert(isSuccessor(PreviousLayoutSuccessor));
782
783 if (PreviousLayoutSuccessor == TBB) {
784 // We had a fallthrough to the same basic block as the conditional jump
785 // targets. Remove the conditional jump, leaving an unconditional
786 // fallthrough or an unconditional jump.
787 TII->removeBranch(*this);
788 if (!isLayoutSuccessor(TBB)) {
789 Cond.clear();
790 TII->insertBranch(*this, TBB, nullptr, Cond, DL);
791 }
792 return;
793 }
794
795 // The block has a fallthrough conditional branch.
796 if (isLayoutSuccessor(TBB)) {
797 if (TII->reverseBranchCondition(Cond)) {
798 // We can't reverse the condition, add an unconditional branch.
799 Cond.clear();
800 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
801 return;
802 }
803 TII->removeBranch(*this);
804 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
805 } else if (!isLayoutSuccessor(PreviousLayoutSuccessor)) {
806 TII->removeBranch(*this);
807 TII->insertBranch(*this, TBB, PreviousLayoutSuccessor, Cond, DL);
808 }
809}
810
812#ifndef NDEBUG
813 int64_t Sum = 0;
814 for (auto Prob : Probs)
815 Sum += Prob.getNumerator();
816 // Due to precision issue, we assume that the sum of probabilities is one if
817 // the difference between the sum of their numerators and the denominator is
818 // no greater than the number of successors.
820 Probs.size() &&
821 "The sum of successors's probabilities exceeds one.");
822#endif // NDEBUG
823}
824
825void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
826 BranchProbability Prob) {
827 // Probability list is either empty (if successor list isn't empty, this means
828 // disabled optimization) or has the same size as successor list.
829 if (!(Probs.empty() && !Successors.empty()))
830 Probs.push_back(Prob);
831 Successors.push_back(Succ);
832 Succ->addPredecessor(this);
833}
834
835void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
836 // We need to make sure probability list is either empty or has the same size
837 // of successor list. When this function is called, we can safely delete all
838 // probability in the list.
839 Probs.clear();
840 Successors.push_back(Succ);
841 Succ->addPredecessor(this);
842}
843
844void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
845 MachineBasicBlock *New,
846 bool NormalizeSuccProbs) {
847 succ_iterator OldI = llvm::find(successors(), Old);
848 assert(OldI != succ_end() && "Old is not a successor of this block!");
850 "New is already a successor of this block!");
851
852 // Add a new successor with equal probability as the original one. Note
853 // that we directly copy the probability using the iterator rather than
854 // getting a potentially synthetic probability computed when unknown. This
855 // preserves the probabilities as-is and then we can renormalize them and
856 // query them effectively afterward.
857 addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
858 : *getProbabilityIterator(OldI));
859 if (NormalizeSuccProbs)
861}
862
863void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
864 bool NormalizeSuccProbs) {
865 succ_iterator I = find(Successors, Succ);
866 removeSuccessor(I, NormalizeSuccProbs);
867}
868
871 assert(I != Successors.end() && "Not a current successor!");
872
873 // If probability list is empty it means we don't use it (disabled
874 // optimization).
875 if (!Probs.empty()) {
876 probability_iterator WI = getProbabilityIterator(I);
877 Probs.erase(WI);
878 if (NormalizeSuccProbs)
880 }
881
882 (*I)->removePredecessor(this);
883 return Successors.erase(I);
884}
885
886void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
887 MachineBasicBlock *New) {
888 if (Old == New)
889 return;
890
892 succ_iterator NewI = E;
893 succ_iterator OldI = E;
894 for (succ_iterator I = succ_begin(); I != E; ++I) {
895 if (*I == Old) {
896 OldI = I;
897 if (NewI != E)
898 break;
899 }
900 if (*I == New) {
901 NewI = I;
902 if (OldI != E)
903 break;
904 }
905 }
906 assert(OldI != E && "Old is not a successor of this block");
907
908 // If New isn't already a successor, let it take Old's place.
909 if (NewI == E) {
910 Old->removePredecessor(this);
911 New->addPredecessor(this);
912 *OldI = New;
913 return;
914 }
915
916 // New is already a successor.
917 // Update its probability instead of adding a duplicate edge.
918 if (!Probs.empty()) {
919 auto ProbIter = getProbabilityIterator(NewI);
920 if (!ProbIter->isUnknown())
921 *ProbIter += *getProbabilityIterator(OldI);
922 }
923 removeSuccessor(OldI);
924}
925
926void MachineBasicBlock::copySuccessor(const MachineBasicBlock *Orig,
928 if (!Orig->Probs.empty())
930 else
932}
933
934void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
935 Predecessors.push_back(Pred);
936}
937
938void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
939 pred_iterator I = find(Predecessors, Pred);
940 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
941 Predecessors.erase(I);
942}
943
944void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
945 if (this == FromMBB)
946 return;
947
948 while (!FromMBB->succ_empty()) {
949 MachineBasicBlock *Succ = *FromMBB->succ_begin();
950
951 // If probability list is empty it means we don't use it (disabled
952 // optimization).
953 if (!FromMBB->Probs.empty()) {
954 auto Prob = *FromMBB->Probs.begin();
955 addSuccessor(Succ, Prob);
956 } else
958
959 FromMBB->removeSuccessor(Succ);
960 }
961}
962
963void
965 if (this == FromMBB)
966 return;
967
968 while (!FromMBB->succ_empty()) {
969 MachineBasicBlock *Succ = *FromMBB->succ_begin();
970 if (!FromMBB->Probs.empty()) {
971 auto Prob = *FromMBB->Probs.begin();
972 addSuccessor(Succ, Prob);
973 } else
975 FromMBB->removeSuccessor(Succ);
976
977 // Fix up any PHI nodes in the successor.
978 Succ->replacePhiUsesWith(FromMBB, this);
979 }
981}
982
983bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
984 return is_contained(predecessors(), MBB);
985}
986
987bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
988 return is_contained(successors(), MBB);
989}
990
991bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
993 return std::next(I) == MachineFunction::const_iterator(MBB);
994}
995
996const MachineBasicBlock *MachineBasicBlock::getSingleSuccessor() const {
997 return Successors.size() == 1 ? Successors[0] : nullptr;
998}
999
1000const MachineBasicBlock *MachineBasicBlock::getSinglePredecessor() const {
1001 return Predecessors.size() == 1 ? Predecessors[0] : nullptr;
1002}
1003
1004MachineBasicBlock *MachineBasicBlock::getFallThrough(bool JumpToFallThrough) {
1005 MachineFunction::iterator Fallthrough = getIterator();
1006 ++Fallthrough;
1007 // If FallthroughBlock is off the end of the function, it can't fall through.
1008 if (Fallthrough == getParent()->end())
1009 return nullptr;
1010
1011 // If FallthroughBlock isn't a successor, no fallthrough is possible.
1012 if (!isSuccessor(&*Fallthrough))
1013 return nullptr;
1014
1015 // Analyze the branches, if any, at the end of the block.
1016 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1019 if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
1020 // If we couldn't analyze the branch, examine the last instruction.
1021 // If the block doesn't end in a known control barrier, assume fallthrough
1022 // is possible. The isPredicated check is needed because this code can be
1023 // called during IfConversion, where an instruction which is normally a
1024 // Barrier is predicated and thus no longer an actual control barrier.
1025 return (empty() || !back().isBarrier() || TII->isPredicated(back()))
1026 ? &*Fallthrough
1027 : nullptr;
1028 }
1029
1030 // If there is no branch, control always falls through.
1031 if (!TBB) return &*Fallthrough;
1032
1033 // If there is some explicit branch to the fallthrough block, it can obviously
1034 // reach, even though the branch should get folded to fall through implicitly.
1035 if (JumpToFallThrough && (MachineFunction::iterator(TBB) == Fallthrough ||
1036 MachineFunction::iterator(FBB) == Fallthrough))
1037 return &*Fallthrough;
1038
1039 // If it's an unconditional branch to some block not the fall through, it
1040 // doesn't fall through.
1041 if (Cond.empty()) return nullptr;
1042
1043 // Otherwise, if it is conditional and has no explicit false block, it falls
1044 // through.
1045 return (FBB == nullptr) ? &*Fallthrough : nullptr;
1046}
1047
1049 return getFallThrough() != nullptr;
1050}
1051
1053 bool UpdateLiveIns,
1054 LiveIntervals *LIS) {
1055 MachineBasicBlock::iterator SplitPoint(&MI);
1056 ++SplitPoint;
1057
1058 if (SplitPoint == end()) {
1059 // Don't bother with a new block.
1060 return this;
1061 }
1062
1063 MachineFunction *MF = getParent();
1064
1066 if (UpdateLiveIns) {
1067 // Make sure we add any physregs we define in the block as liveins to the
1068 // new block.
1070 LiveRegs.init(*MF->getSubtarget().getRegisterInfo());
1071 LiveRegs.addLiveOuts(*this);
1072 for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I)
1073 LiveRegs.stepBackward(*I);
1074 }
1075
1076 MachineBasicBlock *SplitBB = MF->CreateMachineBasicBlock(getBasicBlock());
1077
1078 MF->insert(++MachineFunction::iterator(this), SplitBB);
1079 SplitBB->splice(SplitBB->begin(), this, SplitPoint, end());
1080
1081 SplitBB->transferSuccessorsAndUpdatePHIs(this);
1082 addSuccessor(SplitBB);
1083
1084 if (UpdateLiveIns)
1085 addLiveIns(*SplitBB, LiveRegs);
1086
1087 if (LIS)
1088 LIS->insertMBBInMaps(SplitBB);
1089
1090 return SplitBB;
1091}
1092
1093// Returns `true` if there are possibly other users of the jump table at
1094// `JumpTableIndex` except for the ones in `IgnoreMBB`.
1096 const MachineBasicBlock &IgnoreMBB,
1097 int JumpTableIndex) {
1098 assert(JumpTableIndex >= 0 && "need valid index");
1099 const MachineJumpTableInfo &MJTI = *MF.getJumpTableInfo();
1100 const MachineJumpTableEntry &MJTE = MJTI.getJumpTables()[JumpTableIndex];
1101 // Take any basic block from the table; every user of the jump table must
1102 // show up in the predecessor list.
1103 const MachineBasicBlock *MBB = nullptr;
1104 for (MachineBasicBlock *B : MJTE.MBBs) {
1105 if (B != nullptr) {
1106 MBB = B;
1107 break;
1108 }
1109 }
1110 if (MBB == nullptr)
1111 return true; // can't rule out other users if there isn't any block.
1114 for (MachineBasicBlock *Pred : MBB->predecessors()) {
1115 if (Pred == &IgnoreMBB)
1116 continue;
1117 MachineBasicBlock *DummyT = nullptr;
1118 MachineBasicBlock *DummyF = nullptr;
1119 Cond.clear();
1120 if (!TII.analyzeBranch(*Pred, DummyT, DummyF, Cond,
1121 /*AllowModify=*/false)) {
1122 // analyzable direct jump
1123 continue;
1124 }
1125 int PredJTI = findJumpTableIndex(*Pred);
1126 if (PredJTI >= 0) {
1127 if (PredJTI == JumpTableIndex)
1128 return true;
1129 continue;
1130 }
1131 // Be conservative for unanalyzable jumps.
1132 return true;
1133 }
1134 return false;
1135}
1136
1138private:
1139 MachineFunction &MF;
1140 SlotIndexes *Indexes;
1142
1143public:
1145 : MF(MF), Indexes(Indexes) {
1146 MF.setDelegate(this);
1147 }
1148
1150 MF.resetDelegate(this);
1151 for (auto MI : Insertions)
1152 Indexes->insertMachineInstrInMaps(*MI);
1153 }
1154
1156 // This is called before MI is inserted into block so defer index update.
1157 if (Indexes)
1158 Insertions.insert(&MI);
1159 }
1160
1162 if (Indexes && !Insertions.remove(&MI))
1163 Indexes->removeMachineInstrFromMaps(MI);
1164 }
1165};
1166
1168 MachineBasicBlock *Succ, Pass *P, MachineFunctionAnalysisManager *MFAM,
1169 std::vector<SparseBitVector<>> *LiveInSets, MachineDomTreeUpdater *MDTU) {
1170#define GET_RESULT(RESULT, GETTER, INFIX) \
1171 [MF, P, MFAM]() { \
1172 if (P) { \
1173 auto *Wrapper = P->getAnalysisIfAvailable<RESULT##INFIX##WrapperPass>(); \
1174 return Wrapper ? &Wrapper->GETTER() : nullptr; \
1175 } \
1176 return MFAM->getCachedResult<RESULT##Analysis>(*MF); \
1177 }()
1178
1179 assert((P || MFAM) && "Need a way to get analysis results!");
1180 MachineFunction *MF = getParent();
1181 LiveIntervals *LIS = GET_RESULT(LiveIntervals, getLIS, );
1182 SlotIndexes *Indexes = GET_RESULT(SlotIndexes, getSI, );
1183 LiveVariables *LV = GET_RESULT(LiveVariables, getLV, );
1184 MachineLoopInfo *MLI = GET_RESULT(MachineLoop, getLI, Info);
1185 return SplitCriticalEdge(Succ, {LIS, Indexes, LV, MLI}, LiveInSets, MDTU);
1186#undef GET_RESULT
1187}
1188
1190 MachineBasicBlock *Succ, const SplitCriticalEdgeAnalyses &Analyses,
1191 std::vector<SparseBitVector<>> *LiveInSets, MachineDomTreeUpdater *MDTU) {
1192 if (!canSplitCriticalEdge(Succ, Analyses.MLI))
1193 return nullptr;
1194
1195 MachineFunction *MF = getParent();
1196 MachineBasicBlock *PrevFallthrough = getNextNode();
1197
1198 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
1199 NMBB->setCallFrameSize(Succ->getCallFrameSize());
1200
1201 // Is there an indirect jump with jump table?
1202 bool ChangedIndirectJump = false;
1203 int JTI = findJumpTableIndex(*this);
1204 if (JTI >= 0) {
1206 MJTI.ReplaceMBBInJumpTable(JTI, Succ, NMBB);
1207 ChangedIndirectJump = true;
1208 }
1209
1210 MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
1211 LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
1212 << " -- " << printMBBReference(*NMBB) << " -- "
1213 << printMBBReference(*Succ) << '\n');
1214 auto *LIS = Analyses.LIS;
1215 if (LIS)
1216 LIS->insertMBBInMaps(NMBB);
1217 else if (Analyses.SI)
1218 Analyses.SI->insertMBBInMaps(NMBB);
1219
1220 // On some targets like Mips, branches may kill virtual registers. Make sure
1221 // that LiveVariables is properly updated after updateTerminator replaces the
1222 // terminators.
1223 auto *LV = Analyses.LV;
1224 // Collect a list of virtual registers killed by the terminators.
1225 SmallVector<Register, 4> KilledRegs;
1226 if (LV)
1227 for (MachineInstr &MI :
1229 for (MachineOperand &MO : MI.all_uses()) {
1230 if (MO.getReg() == 0 || !MO.isKill() || MO.isUndef())
1231 continue;
1232 Register Reg = MO.getReg();
1233 if (Reg.isPhysical() || LV->getVarInfo(Reg).removeKill(MI)) {
1234 KilledRegs.push_back(Reg);
1235 LLVM_DEBUG(dbgs() << "Removing terminator kill: " << MI);
1236 MO.setIsKill(false);
1237 }
1238 }
1239 }
1240
1241 SmallVector<Register, 4> UsedRegs;
1242 if (LIS) {
1243 for (MachineInstr &MI :
1245 for (const MachineOperand &MO : MI.operands()) {
1246 if (!MO.isReg() || MO.getReg() == 0)
1247 continue;
1248
1249 Register Reg = MO.getReg();
1250 if (!is_contained(UsedRegs, Reg))
1251 UsedRegs.push_back(Reg);
1252 }
1253 }
1254 }
1255
1256 ReplaceUsesOfBlockWith(Succ, NMBB);
1257
1258 // Since we replaced all uses of Succ with NMBB, that should also be treated
1259 // as the fallthrough successor
1260 if (Succ == PrevFallthrough)
1261 PrevFallthrough = NMBB;
1262 auto *Indexes = Analyses.SI;
1263 if (!ChangedIndirectJump) {
1264 SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1265 updateTerminator(PrevFallthrough);
1266 }
1267
1268 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
1269 NMBB->addSuccessor(Succ);
1270 if (!NMBB->isLayoutSuccessor(Succ)) {
1271 SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1274
1275 // In original 'this' BB, there must be a branch instruction targeting at
1276 // Succ. We can not find it out since currently getBranchDestBlock was not
1277 // implemented for all targets. However, if the merged DL has column or line
1278 // number, the scope and non-zero column and line number is same with that
1279 // branch instruction so we can safely use it.
1280 DebugLoc DL, MergedDL = findBranchDebugLoc();
1281 if (MergedDL && (MergedDL.getLine() || MergedDL.getCol()))
1282 DL = MergedDL;
1283 TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
1284 }
1285
1286 // Fix PHI nodes in Succ so they refer to NMBB instead of this.
1287 Succ->replacePhiUsesWith(this, NMBB);
1288
1289 // Inherit live-ins from the successor
1290 for (const auto &LI : Succ->liveins())
1291 NMBB->addLiveIn(LI);
1292
1293 // Update LiveVariables.
1295 if (LV) {
1296 // Restore kills of virtual registers that were killed by the terminators.
1297 while (!KilledRegs.empty()) {
1298 Register Reg = KilledRegs.pop_back_val();
1299 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
1300 if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false))
1301 continue;
1302 if (Reg.isVirtual())
1303 LV->getVarInfo(Reg).Kills.push_back(&*I);
1304 LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
1305 break;
1306 }
1307 }
1308 // Update relevant live-through information.
1309 if (LiveInSets != nullptr)
1310 LV->addNewBlock(NMBB, this, Succ, *LiveInSets);
1311 else
1312 LV->addNewBlock(NMBB, this, Succ);
1313 }
1314
1315 if (LIS) {
1316 // After splitting the edge and updating SlotIndexes, live intervals may be
1317 // in one of two situations, depending on whether this block was the last in
1318 // the function. If the original block was the last in the function, all
1319 // live intervals will end prior to the beginning of the new split block. If
1320 // the original block was not at the end of the function, all live intervals
1321 // will extend to the end of the new split block.
1322
1323 bool isLastMBB =
1324 std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
1325
1326 SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
1327 SlotIndex PrevIndex = StartIndex.getPrevSlot();
1328 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
1329
1330 // Find the registers used from NMBB in PHIs in Succ.
1331 SmallSet<Register, 8> PHISrcRegs;
1333 I = Succ->instr_begin(), E = Succ->instr_end();
1334 I != E && I->isPHI(); ++I) {
1335 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
1336 if (I->getOperand(ni+1).getMBB() == NMBB) {
1337 MachineOperand &MO = I->getOperand(ni);
1338 Register Reg = MO.getReg();
1339 PHISrcRegs.insert(Reg);
1340 if (MO.isUndef())
1341 continue;
1342
1343 LiveInterval &LI = LIS->getInterval(Reg);
1344 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1345 assert(VNI &&
1346 "PHI sources should be live out of their predecessors.");
1347 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1348 for (auto &SR : LI.subranges())
1349 SR.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1350 }
1351 }
1352 }
1353
1355 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1357 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
1358 continue;
1359
1360 LiveInterval &LI = LIS->getInterval(Reg);
1361 if (!LI.liveAt(PrevIndex))
1362 continue;
1363
1364 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
1365 if (isLiveOut && isLastMBB) {
1366 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1367 assert(VNI && "LiveInterval should have VNInfo where it is live.");
1368 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1369 // Update subranges with live values
1370 for (auto &SR : LI.subranges()) {
1371 VNInfo *VNI = SR.getVNInfoAt(PrevIndex);
1372 if (VNI)
1373 SR.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1374 }
1375 } else if (!isLiveOut && !isLastMBB) {
1376 LI.removeSegment(StartIndex, EndIndex);
1377 for (auto &SR : LI.subranges())
1378 SR.removeSegment(StartIndex, EndIndex);
1379 }
1380 }
1381
1382 // Update all intervals for registers whose uses may have been modified by
1383 // updateTerminator().
1384 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
1385 }
1386
1387 if (MDTU)
1388 MDTU->splitCriticalEdge(this, Succ, NMBB);
1389
1390 if (MachineLoopInfo *MLI = Analyses.MLI)
1391 if (MachineLoop *TIL = MLI->getLoopFor(this)) {
1392 // If one or the other blocks were not in a loop, the new block is not
1393 // either, and thus LI doesn't need to be updated.
1394 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
1395 if (TIL == DestLoop) {
1396 // Both in the same loop, the NMBB joins loop.
1397 DestLoop->addBasicBlockToLoop(NMBB, *MLI);
1398 } else if (TIL->contains(DestLoop)) {
1399 // Edge from an outer loop to an inner loop. Add to the outer loop.
1400 TIL->addBasicBlockToLoop(NMBB, *MLI);
1401 } else if (DestLoop->contains(TIL)) {
1402 // Edge from an inner loop to an outer loop. Add to the outer loop.
1403 DestLoop->addBasicBlockToLoop(NMBB, *MLI);
1404 } else {
1405 // Edge from two loops with no containment relation. Because these
1406 // are natural loops, we know that the destination block must be the
1407 // header of its loop (adding a branch into a loop elsewhere would
1408 // create an irreducible loop).
1409 assert(DestLoop->getHeader() == Succ &&
1410 "Should not create irreducible loops!");
1411 if (MachineLoop *P = DestLoop->getParentLoop())
1412 P->addBasicBlockToLoop(NMBB, *MLI);
1413 }
1414 }
1415 }
1416
1417 return NMBB;
1418}
1419
1420bool MachineBasicBlock::canSplitCriticalEdge(const MachineBasicBlock *Succ,
1421 const MachineLoopInfo *MLI) const {
1422 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1423 // it in this generic function.
1424 if (Succ->isEHPad())
1425 return false;
1426
1427 // Splitting the critical edge to a callbr's indirect block isn't advised.
1428 // Don't do it in this generic function.
1429 if (Succ->isInlineAsmBrIndirectTarget())
1430 return false;
1431
1432 const MachineFunction *MF = getParent();
1433 // Performance might be harmed on HW that implements branching using exec mask
1434 // where both sides of the branches are always executed.
1435
1436 if (MF->getTarget().requiresStructuredCFG()) {
1437 if (!MLI)
1438 return false;
1439 const MachineLoop *L = MLI->getLoopFor(Succ);
1440 // Only if `Succ` is a loop header, splitting the critical edge will not
1441 // break structured CFG. And fallthrough to check if this's terminator is
1442 // analyzable.
1443 if (!L || L->getHeader() != Succ)
1444 return false;
1445 }
1446
1447 // Do we have an Indirect jump with a jumptable that we can rewrite?
1448 int JTI = findJumpTableIndex(*this);
1449 if (JTI >= 0 && !jumpTableHasOtherUses(*MF, *this, JTI))
1450 return true;
1451
1452 // We may need to update this's terminator, but we can't do that if
1453 // analyzeBranch fails.
1455 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1457 // AnalyzeBanch should modify this, since we did not allow modification.
1458 if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
1459 /*AllowModify*/ false))
1460 return false;
1461
1462 // Avoid bugpoint weirdness: A block may end with a conditional branch but
1463 // jumps to the same MBB is either case. We have duplicate CFG edges in that
1464 // case that we can't handle. Since this never happens in properly optimized
1465 // code, just skip those edges.
1466 if (TBB && TBB == FBB) {
1467 LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
1468 << printMBBReference(*this) << '\n');
1469 return false;
1470 }
1471 return true;
1472}
1473
1474/// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1475/// neighboring instructions so the bundle won't be broken by removing MI.
1477 // Removing the first instruction in a bundle.
1478 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1479 MI->unbundleFromSucc();
1480 // Removing the last instruction in a bundle.
1481 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1482 MI->unbundleFromPred();
1483 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1484 // are already fine.
1485}
1486
1492
1495 MI->clearFlag(MachineInstr::BundledPred);
1496 MI->clearFlag(MachineInstr::BundledSucc);
1497 return Insts.remove(MI);
1498}
1499
1502 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1503 "Cannot insert instruction with bundle flags");
1504 // Set the bundle flags when inserting inside a bundle.
1505 if (I != instr_end() && I->isBundledWithPred()) {
1506 MI->setFlag(MachineInstr::BundledPred);
1507 MI->setFlag(MachineInstr::BundledSucc);
1508 }
1509 return Insts.insert(I, MI);
1510}
1511
1512/// This method unlinks 'this' from the containing function, and returns it, but
1513/// does not delete it.
1515 assert(getParent() && "Not embedded in a function!");
1516 getParent()->remove(this);
1517 return this;
1518}
1519
1520/// This method unlinks 'this' from the containing function, and deletes it.
1522 assert(getParent() && "Not embedded in a function!");
1523 getParent()->erase(this);
1524}
1525
1526/// Given a machine basic block that branched to 'Old', change the code and CFG
1527/// so that it branches to 'New' instead.
1529 MachineBasicBlock *New) {
1530 assert(Old != New && "Cannot replace self with self!");
1531
1533 while (I != instr_begin()) {
1534 --I;
1535 if (!I->isTerminator()) break;
1536
1537 // Scan the operands of this machine instruction, replacing any uses of Old
1538 // with New.
1539 for (MachineOperand &MO : I->operands())
1540 if (MO.isMBB() && MO.getMBB() == Old)
1541 MO.setMBB(New);
1542 }
1543
1544 // Update the successor information.
1545 replaceSuccessor(Old, New);
1546}
1547
1548void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old,
1549 MachineBasicBlock *New) {
1550 for (MachineInstr &MI : phis())
1551 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
1552 MachineOperand &MO = MI.getOperand(i);
1553 if (MO.getMBB() == Old)
1554 MO.setMBB(New);
1555 }
1556}
1557
1558/// Find the next valid DebugLoc starting at MBBI, skipping any debug
1559/// instructions. Return UnknownLoc if there is none.
1562 // Skip debug declarations, we don't want a DebugLoc from them.
1564 if (MBBI != instr_end())
1565 return MBBI->getDebugLoc();
1566 return {};
1567}
1568
1570 if (MBBI == instr_rend())
1571 return findDebugLoc(instr_begin());
1572 // Skip debug declarations, we don't want a DebugLoc from them.
1574 if (!MBBI->isDebugInstr())
1575 return MBBI->getDebugLoc();
1576 return {};
1577}
1578
1579/// Find the previous valid DebugLoc preceding MBBI, skipping any debug
1580/// instructions. Return UnknownLoc if there is none.
1582 if (MBBI == instr_begin())
1583 return {};
1584 // Skip debug instructions, we don't want a DebugLoc from them.
1586 if (!MBBI->isDebugInstr())
1587 return MBBI->getDebugLoc();
1588 return {};
1589}
1590
1592 if (MBBI == instr_rend())
1593 return {};
1594 // Skip debug declarations, we don't want a DebugLoc from them.
1596 if (MBBI != instr_rend())
1597 return MBBI->getDebugLoc();
1598 return {};
1599}
1600
1601/// Find and return the merged DebugLoc of the branch instructions of the block.
1602/// Return UnknownLoc if there is none.
1605 DebugLoc DL;
1606 auto TI = getFirstTerminator();
1607 while (TI != end() && !TI->isBranch())
1608 ++TI;
1609
1610 if (TI != end()) {
1611 DL = TI->getDebugLoc();
1612 for (++TI ; TI != end() ; ++TI)
1613 if (TI->isBranch())
1614 DL = DebugLoc::getMergedLocation(DL, TI->getDebugLoc());
1615 }
1616 return DL;
1617}
1618
1619/// Return probability of the edge from this block to MBB.
1622 if (Probs.empty())
1623 return BranchProbability(1, succ_size());
1624
1625 const auto &Prob = *getProbabilityIterator(Succ);
1626 if (!Prob.isUnknown())
1627 return Prob;
1628 // For unknown probabilities, collect the sum of all known ones, and evenly
1629 // ditribute the complemental of the sum to each unknown probability.
1630 unsigned KnownProbNum = 0;
1631 auto Sum = BranchProbability::getZero();
1632 for (const auto &P : Probs) {
1633 if (!P.isUnknown()) {
1634 Sum += P;
1635 KnownProbNum++;
1636 }
1637 }
1638 return Sum.getCompl() / (Probs.size() - KnownProbNum);
1639}
1640
1642 if (succ_size() <= 1)
1643 return true;
1645 return true;
1646
1647 SmallVector<BranchProbability, 8> Normalized(Probs.begin(), Probs.end());
1649
1650 // Normalize assuming unknown probabilities. This will assign equal
1651 // probabilities to all successors.
1652 SmallVector<BranchProbability, 8> Equal(Normalized.size());
1654
1655 return llvm::equal(Normalized, Equal);
1656}
1657
1658/// Set successor probability of a given iterator.
1660 BranchProbability Prob) {
1661 assert(!Prob.isUnknown());
1662 if (Probs.empty())
1663 return;
1664 *getProbabilityIterator(I) = Prob;
1665}
1666
1667/// Return probability iterator corresonding to the I successor iterator
1668MachineBasicBlock::const_probability_iterator
1669MachineBasicBlock::getProbabilityIterator(
1671 assert(Probs.size() == Successors.size() && "Async probability list!");
1672 const size_t index = std::distance(Successors.begin(), I);
1673 assert(index < Probs.size() && "Not a current successor!");
1674 return Probs.begin() + index;
1675}
1676
1677/// Return probability iterator corresonding to the I successor iterator.
1678MachineBasicBlock::probability_iterator
1679MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1680 assert(Probs.size() == Successors.size() && "Async probability list!");
1681 const size_t index = std::distance(Successors.begin(), I);
1682 assert(index < Probs.size() && "Not a current successor!");
1683 return Probs.begin() + index;
1684}
1685
1686/// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1687/// as of just before "MI".
1688///
1689/// Search is localised to a neighborhood of
1690/// Neighborhood instructions before (searching for defs or kills) and N
1691/// instructions after (searching just for defs) MI.
1694 MCRegister Reg, const_iterator Before,
1695 unsigned Neighborhood) const {
1696 assert(Reg.isPhysical());
1697 unsigned N = Neighborhood;
1698
1699 // Try searching forwards from Before, looking for reads or defs.
1700 const_iterator I(Before);
1701 for (; I != end() && N > 0; ++I) {
1702 if (I->isDebugOrPseudoInstr())
1703 continue;
1704
1705 --N;
1706
1707 PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
1708
1709 // Register is live when we read it here.
1710 if (Info.Read)
1711 return LQR_Live;
1712 // Register is dead if we can fully overwrite or clobber it here.
1713 if (Info.FullyDefined || Info.Clobbered)
1714 return LQR_Dead;
1715 }
1716
1717 // If we reached the end, it is safe to clobber Reg at the end of a block of
1718 // no successor has it live in.
1719 if (I == end()) {
1720 for (MachineBasicBlock *S : successors()) {
1721 for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
1722 if (TRI->regsOverlap(LI.PhysReg, Reg))
1723 return LQR_Live;
1724 }
1725 }
1726
1727 return LQR_Dead;
1728 }
1729
1730
1731 N = Neighborhood;
1732
1733 // Start by searching backwards from Before, looking for kills, reads or defs.
1734 I = const_iterator(Before);
1735 // If this is the first insn in the block, don't search backwards.
1736 if (I != begin()) {
1737 do {
1738 --I;
1739
1740 if (I->isDebugOrPseudoInstr())
1741 continue;
1742
1743 --N;
1744
1745 PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
1746
1747 // Defs happen after uses so they take precedence if both are present.
1748
1749 // Register is dead after a dead def of the full register.
1750 if (Info.DeadDef)
1751 return LQR_Dead;
1752 // Register is (at least partially) live after a def.
1753 if (Info.Defined) {
1754 if (!Info.PartialDeadDef)
1755 return LQR_Live;
1756 // As soon as we saw a partial definition (dead or not),
1757 // we cannot tell if the value is partial live without
1758 // tracking the lanemasks. We are not going to do this,
1759 // so fall back on the remaining of the analysis.
1760 break;
1761 }
1762 // Register is dead after a full kill or clobber and no def.
1763 if (Info.Killed || Info.Clobbered)
1764 return LQR_Dead;
1765 // Register must be live if we read it.
1766 if (Info.Read)
1767 return LQR_Live;
1768
1769 } while (I != begin() && N > 0);
1770 }
1771
1772 // If all the instructions before this in the block are debug instructions,
1773 // skip over them.
1774 while (I != begin() && std::prev(I)->isDebugOrPseudoInstr())
1775 --I;
1776
1777 // Did we get to the start of the block?
1778 if (I == begin()) {
1779 // If so, the register's state is definitely defined by the live-in state.
1781 if (TRI->regsOverlap(LI.PhysReg, Reg))
1782 return LQR_Live;
1783
1784 return LQR_Dead;
1785 }
1786
1787 // At this point we have no idea of the liveness of the register.
1788 return LQR_Unknown;
1789}
1790
1791const uint32_t *
1793 // EH funclet entry does not preserve any registers.
1794 return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1795}
1796
1797const uint32_t *
1799 // If we see a return block with successors, this must be a funclet return,
1800 // which does not preserve any registers. If there are no successors, we don't
1801 // care what kind of return it is, putting a mask after it is a no-op.
1802 return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1803}
1804
1806 LiveIns.clear();
1807}
1808
1810 std::vector<RegisterMaskPair> &OldLiveIns) {
1811 assert(OldLiveIns.empty() && "Vector must be empty");
1812 std::swap(LiveIns, OldLiveIns);
1813}
1814
1816 assert(getParent()->getProperties().hasTracksLiveness() &&
1817 "Liveness information is accurate");
1818 return LiveIns.begin();
1819}
1820
1822 const MachineFunction &MF = *getParent();
1823 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1824 MCRegister ExceptionPointer, ExceptionSelector;
1825 if (MF.getFunction().hasPersonalityFn()) {
1826 auto PersonalityFn = MF.getFunction().getPersonalityFn();
1827 ExceptionPointer = TLI.getExceptionPointerRegister(PersonalityFn);
1828 ExceptionSelector = TLI.getExceptionSelectorRegister(PersonalityFn);
1829 }
1830
1831 return liveout_iterator(*this, ExceptionPointer, ExceptionSelector, false);
1832}
1833
1835 unsigned Cntr = 0;
1836 auto R = instructionsWithoutDebug(begin(), end());
1837 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1838 if (++Cntr > Limit)
1839 return true;
1840 }
1841 return false;
1842}
1843
1845 const MachineBasicBlock &PredMBB) {
1846 for (MachineInstr &Phi : phis())
1847 Phi.removePHIIncomingValueFor(PredMBB);
1848}
1849
1851const MBBSectionID
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:661
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:905
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
bool isEHScopeEntry() const
Returns true if this is the entry block of an EH scope, i.e., the block that used to have a catchpad ...
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, RegState Flags={}, 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,...
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
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:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
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:184
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:46
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.
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:1765
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Kill
The last use of a register.
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:1636
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:1772
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
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:2146
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