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