LLVM 20.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"
32#include "llvm/Config/llvm-config.h"
33#include "llvm/IR/BasicBlock.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 (!CachedEHCatchretMCSymbol) {
97 const MachineFunction *MF = getParent();
98 SmallString<128> SymbolName;
99 raw_svector_ostream(SymbolName)
100 << "$ehgcr_" << MF->getFunctionNumber() << '_' << getNumber();
101 CachedEHCatchretMCSymbol = MF->getContext().getOrCreateSymbol(SymbolName);
102 }
103 return CachedEHCatchretMCSymbol;
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
138 // Make sure the instructions have their operands in the reginfo lists.
139 MachineRegisterInfo &RegInfo = MF.getRegInfo();
140 for (MachineInstr &MI : N->instrs())
141 MI.addRegOperandsToUseLists(RegInfo);
142}
143
146 N->getParent()->removeFromMBBNumbering(N->Number);
147 N->Number = -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)
302 print(dbgs());
303}
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 (getAlignment() != Align(1)) {
557 os << (hasAttributes ? ", " : " (");
558 os << "align " << getAlignment().value();
559 hasAttributes = true;
560 }
561 if (getSectionID() != MBBSectionID(0)) {
562 os << (hasAttributes ? ", " : " (");
563 os << "bbsections ";
564 switch (getSectionID().Type) {
566 os << "Exception";
567 break;
569 os << "Cold";
570 break;
571 default:
572 os << getSectionID().Number;
573 }
574 hasAttributes = true;
575 }
576 if (getBBID().has_value()) {
577 os << (hasAttributes ? ", " : " (");
578 os << "bb_id " << getBBID()->BaseID;
579 if (getBBID()->CloneID != 0)
580 os << " " << getBBID()->CloneID;
581 hasAttributes = true;
582 }
583 if (CallFrameSize != 0) {
584 os << (hasAttributes ? ", " : " (");
585 os << "call-frame-size " << CallFrameSize;
586 hasAttributes = true;
587 }
588 }
589
590 if (hasAttributes)
591 os << ')';
592}
593
595 bool /*PrintType*/) const {
596 OS << '%';
597 printName(OS, 0);
598}
599
601 LiveInVector::iterator I = find_if(
602 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
603 if (I == LiveIns.end())
604 return;
605
606 I->LaneMask &= ~LaneMask;
607 if (I->LaneMask.none())
608 LiveIns.erase(I);
609}
610
613 // Get non-const version of iterator.
614 LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
615 return LiveIns.erase(LI);
616}
617
620 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
621 return I != livein_end() && (I->LaneMask & LaneMask).any();
622}
623
625 llvm::sort(LiveIns,
626 [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
627 return LI0.PhysReg < LI1.PhysReg;
628 });
629 // Liveins are sorted by physreg now we can merge their lanemasks.
630 LiveInVector::const_iterator I = LiveIns.begin();
631 LiveInVector::const_iterator J;
632 LiveInVector::iterator Out = LiveIns.begin();
633 for (; I != LiveIns.end(); ++Out, I = J) {
634 MCRegister PhysReg = I->PhysReg;
635 LaneBitmask LaneMask = I->LaneMask;
636 for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
637 LaneMask |= J->LaneMask;
638 Out->PhysReg = PhysReg;
639 Out->LaneMask = LaneMask;
640 }
641 LiveIns.erase(Out, LiveIns.end());
642}
643
646 assert(getParent() && "MBB must be inserted in function");
647 assert(Register::isPhysicalRegister(PhysReg) && "Expected physreg");
648 assert(RC && "Register class is required");
649 assert((isEHPad() || this == &getParent()->front()) &&
650 "Only the entry block and landing pads can have physreg live ins");
651
652 bool LiveIn = isLiveIn(PhysReg);
656
657 // Look for an existing copy.
658 if (LiveIn)
659 for (;I != E && I->isCopy(); ++I)
660 if (I->getOperand(1).getReg() == PhysReg) {
661 Register VirtReg = I->getOperand(0).getReg();
662 if (!MRI.constrainRegClass(VirtReg, RC))
663 llvm_unreachable("Incompatible live-in register class.");
664 return VirtReg;
665 }
666
667 // No luck, create a virtual register.
668 Register VirtReg = MRI.createVirtualRegister(RC);
669 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
670 .addReg(PhysReg, RegState::Kill);
671 if (!LiveIn)
672 addLiveIn(PhysReg);
673 return VirtReg;
674}
675
677 getParent()->splice(NewAfter->getIterator(), getIterator());
678}
679
681 getParent()->splice(++NewBefore->getIterator(), getIterator());
682}
683
686 if (TerminatorI == MBB.end())
687 return -1;
688 const MachineInstr &Terminator = *TerminatorI;
690 return TII->getJumpTableIndex(Terminator);
691}
692
694 MachineBasicBlock *PreviousLayoutSuccessor) {
695 LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
696 << "\n");
697
699 // A block with no successors has no concerns with fall-through edges.
700 if (this->succ_empty())
701 return;
702
703 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
706 bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
707 (void) B;
708 assert(!B && "UpdateTerminators requires analyzable predecessors!");
709 if (Cond.empty()) {
710 if (TBB) {
711 // The block has an unconditional branch. If its successor is now its
712 // layout successor, delete the branch.
714 TII->removeBranch(*this);
715 } else {
716 // The block has an unconditional fallthrough, or the end of the block is
717 // unreachable.
718
719 // Unfortunately, whether the end of the block is unreachable is not
720 // immediately obvious; we must fall back to checking the successor list,
721 // and assuming that if the passed in block is in the succesor list and
722 // not an EHPad, it must be the intended target.
723 if (!PreviousLayoutSuccessor || !isSuccessor(PreviousLayoutSuccessor) ||
724 PreviousLayoutSuccessor->isEHPad())
725 return;
726
727 // If the unconditional successor block is not the current layout
728 // successor, insert a branch to jump to it.
729 if (!isLayoutSuccessor(PreviousLayoutSuccessor))
730 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
731 }
732 return;
733 }
734
735 if (FBB) {
736 // The block has a non-fallthrough conditional branch. If one of its
737 // successors is its layout successor, rewrite it to a fallthrough
738 // conditional branch.
739 if (isLayoutSuccessor(TBB)) {
741 return;
742 TII->removeBranch(*this);
743 TII->insertBranch(*this, FBB, nullptr, Cond, DL);
744 } else if (isLayoutSuccessor(FBB)) {
745 TII->removeBranch(*this);
746 TII->insertBranch(*this, TBB, nullptr, Cond, DL);
747 }
748 return;
749 }
750
751 // We now know we're going to fallthrough to PreviousLayoutSuccessor.
752 assert(PreviousLayoutSuccessor);
753 assert(!PreviousLayoutSuccessor->isEHPad());
754 assert(isSuccessor(PreviousLayoutSuccessor));
755
756 if (PreviousLayoutSuccessor == TBB) {
757 // We had a fallthrough to the same basic block as the conditional jump
758 // targets. Remove the conditional jump, leaving an unconditional
759 // fallthrough or an unconditional jump.
760 TII->removeBranch(*this);
761 if (!isLayoutSuccessor(TBB)) {
762 Cond.clear();
763 TII->insertBranch(*this, TBB, nullptr, Cond, DL);
764 }
765 return;
766 }
767
768 // The block has a fallthrough conditional branch.
769 if (isLayoutSuccessor(TBB)) {
771 // We can't reverse the condition, add an unconditional branch.
772 Cond.clear();
773 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
774 return;
775 }
776 TII->removeBranch(*this);
777 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
778 } else if (!isLayoutSuccessor(PreviousLayoutSuccessor)) {
779 TII->removeBranch(*this);
780 TII->insertBranch(*this, TBB, PreviousLayoutSuccessor, Cond, DL);
781 }
782}
783
785#ifndef NDEBUG
786 int64_t Sum = 0;
787 for (auto Prob : Probs)
788 Sum += Prob.getNumerator();
789 // Due to precision issue, we assume that the sum of probabilities is one if
790 // the difference between the sum of their numerators and the denominator is
791 // no greater than the number of successors.
793 Probs.size() &&
794 "The sum of successors's probabilities exceeds one.");
795#endif // NDEBUG
796}
797
799 BranchProbability Prob) {
800 // Probability list is either empty (if successor list isn't empty, this means
801 // disabled optimization) or has the same size as successor list.
802 if (!(Probs.empty() && !Successors.empty()))
803 Probs.push_back(Prob);
804 Successors.push_back(Succ);
805 Succ->addPredecessor(this);
806}
807
809 // We need to make sure probability list is either empty or has the same size
810 // of successor list. When this function is called, we can safely delete all
811 // probability in the list.
812 Probs.clear();
813 Successors.push_back(Succ);
814 Succ->addPredecessor(this);
815}
816
819 bool NormalizeSuccProbs) {
820 succ_iterator OldI = llvm::find(successors(), Old);
821 assert(OldI != succ_end() && "Old is not a successor of this block!");
823 "New is already a successor of this block!");
824
825 // Add a new successor with equal probability as the original one. Note
826 // that we directly copy the probability using the iterator rather than
827 // getting a potentially synthetic probability computed when unknown. This
828 // preserves the probabilities as-is and then we can renormalize them and
829 // query them effectively afterward.
830 addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
831 : *getProbabilityIterator(OldI));
832 if (NormalizeSuccProbs)
834}
835
837 bool NormalizeSuccProbs) {
838 succ_iterator I = find(Successors, Succ);
839 removeSuccessor(I, NormalizeSuccProbs);
840}
841
844 assert(I != Successors.end() && "Not a current successor!");
845
846 // If probability list is empty it means we don't use it (disabled
847 // optimization).
848 if (!Probs.empty()) {
849 probability_iterator WI = getProbabilityIterator(I);
850 Probs.erase(WI);
851 if (NormalizeSuccProbs)
853 }
854
855 (*I)->removePredecessor(this);
856 return Successors.erase(I);
857}
858
860 MachineBasicBlock *New) {
861 if (Old == New)
862 return;
863
865 succ_iterator NewI = E;
866 succ_iterator OldI = E;
867 for (succ_iterator I = succ_begin(); I != E; ++I) {
868 if (*I == Old) {
869 OldI = I;
870 if (NewI != E)
871 break;
872 }
873 if (*I == New) {
874 NewI = I;
875 if (OldI != E)
876 break;
877 }
878 }
879 assert(OldI != E && "Old is not a successor of this block");
880
881 // If New isn't already a successor, let it take Old's place.
882 if (NewI == E) {
883 Old->removePredecessor(this);
884 New->addPredecessor(this);
885 *OldI = New;
886 return;
887 }
888
889 // New is already a successor.
890 // Update its probability instead of adding a duplicate edge.
891 if (!Probs.empty()) {
892 auto ProbIter = getProbabilityIterator(NewI);
893 if (!ProbIter->isUnknown())
894 *ProbIter += *getProbabilityIterator(OldI);
895 }
896 removeSuccessor(OldI);
897}
898
901 if (!Orig->Probs.empty())
903 else
905}
906
907void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
908 Predecessors.push_back(Pred);
909}
910
911void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
912 pred_iterator I = find(Predecessors, Pred);
913 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
914 Predecessors.erase(I);
915}
916
918 if (this == FromMBB)
919 return;
920
921 while (!FromMBB->succ_empty()) {
922 MachineBasicBlock *Succ = *FromMBB->succ_begin();
923
924 // If probability list is empty it means we don't use it (disabled
925 // optimization).
926 if (!FromMBB->Probs.empty()) {
927 auto Prob = *FromMBB->Probs.begin();
928 addSuccessor(Succ, Prob);
929 } else
931
932 FromMBB->removeSuccessor(Succ);
933 }
934}
935
936void
938 if (this == FromMBB)
939 return;
940
941 while (!FromMBB->succ_empty()) {
942 MachineBasicBlock *Succ = *FromMBB->succ_begin();
943 if (!FromMBB->Probs.empty()) {
944 auto Prob = *FromMBB->Probs.begin();
945 addSuccessor(Succ, Prob);
946 } else
948 FromMBB->removeSuccessor(Succ);
949
950 // Fix up any PHI nodes in the successor.
951 Succ->replacePhiUsesWith(FromMBB, this);
952 }
954}
955
957 return is_contained(predecessors(), MBB);
958}
959
961 return is_contained(successors(), MBB);
962}
963
966 return std::next(I) == MachineFunction::const_iterator(MBB);
967}
968
970 return Successors.size() == 1 ? Successors[0] : nullptr;
971}
972
974 return Predecessors.size() == 1 ? Predecessors[0] : nullptr;
975}
976
979 ++Fallthrough;
980 // If FallthroughBlock is off the end of the function, it can't fall through.
981 if (Fallthrough == getParent()->end())
982 return nullptr;
983
984 // If FallthroughBlock isn't a successor, no fallthrough is possible.
985 if (!isSuccessor(&*Fallthrough))
986 return nullptr;
987
988 // Analyze the branches, if any, at the end of the block.
989 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
992 if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
993 // If we couldn't analyze the branch, examine the last instruction.
994 // If the block doesn't end in a known control barrier, assume fallthrough
995 // is possible. The isPredicated check is needed because this code can be
996 // called during IfConversion, where an instruction which is normally a
997 // Barrier is predicated and thus no longer an actual control barrier.
998 return (empty() || !back().isBarrier() || TII->isPredicated(back()))
999 ? &*Fallthrough
1000 : nullptr;
1001 }
1002
1003 // If there is no branch, control always falls through.
1004 if (!TBB) return &*Fallthrough;
1005
1006 // If there is some explicit branch to the fallthrough block, it can obviously
1007 // reach, even though the branch should get folded to fall through implicitly.
1008 if (JumpToFallThrough && (MachineFunction::iterator(TBB) == Fallthrough ||
1009 MachineFunction::iterator(FBB) == Fallthrough))
1010 return &*Fallthrough;
1011
1012 // If it's an unconditional branch to some block not the fall through, it
1013 // doesn't fall through.
1014 if (Cond.empty()) return nullptr;
1015
1016 // Otherwise, if it is conditional and has no explicit false block, it falls
1017 // through.
1018 return (FBB == nullptr) ? &*Fallthrough : nullptr;
1019}
1020
1022 return getFallThrough() != nullptr;
1023}
1024
1026 bool UpdateLiveIns,
1027 LiveIntervals *LIS) {
1028 MachineBasicBlock::iterator SplitPoint(&MI);
1029 ++SplitPoint;
1030
1031 if (SplitPoint == end()) {
1032 // Don't bother with a new block.
1033 return this;
1034 }
1035
1036 MachineFunction *MF = getParent();
1037
1038 LivePhysRegs LiveRegs;
1039 if (UpdateLiveIns) {
1040 // Make sure we add any physregs we define in the block as liveins to the
1041 // new block.
1043 LiveRegs.init(*MF->getSubtarget().getRegisterInfo());
1044 LiveRegs.addLiveOuts(*this);
1045 for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I)
1046 LiveRegs.stepBackward(*I);
1047 }
1048
1050
1051 MF->insert(++MachineFunction::iterator(this), SplitBB);
1052 SplitBB->splice(SplitBB->begin(), this, SplitPoint, end());
1053
1054 SplitBB->transferSuccessorsAndUpdatePHIs(this);
1055 addSuccessor(SplitBB);
1056
1057 if (UpdateLiveIns)
1058 addLiveIns(*SplitBB, LiveRegs);
1059
1060 if (LIS)
1061 LIS->insertMBBInMaps(SplitBB);
1062
1063 return SplitBB;
1064}
1065
1066// Returns `true` if there are possibly other users of the jump table at
1067// `JumpTableIndex` except for the ones in `IgnoreMBB`.
1069 const MachineBasicBlock &IgnoreMBB,
1070 int JumpTableIndex) {
1071 assert(JumpTableIndex >= 0 && "need valid index");
1072 const MachineJumpTableInfo &MJTI = *MF.getJumpTableInfo();
1073 const MachineJumpTableEntry &MJTE = MJTI.getJumpTables()[JumpTableIndex];
1074 // Take any basic block from the table; every user of the jump table must
1075 // show up in the predecessor list.
1076 const MachineBasicBlock *MBB = nullptr;
1077 for (MachineBasicBlock *B : MJTE.MBBs) {
1078 if (B != nullptr) {
1079 MBB = B;
1080 break;
1081 }
1082 }
1083 if (MBB == nullptr)
1084 return true; // can't rule out other users if there isn't any block.
1087 for (MachineBasicBlock *Pred : MBB->predecessors()) {
1088 if (Pred == &IgnoreMBB)
1089 continue;
1090 MachineBasicBlock *DummyT = nullptr;
1091 MachineBasicBlock *DummyF = nullptr;
1092 Cond.clear();
1093 if (!TII.analyzeBranch(*Pred, DummyT, DummyF, Cond,
1094 /*AllowModify=*/false)) {
1095 // analyzable direct jump
1096 continue;
1097 }
1098 int PredJTI = findJumpTableIndex(*Pred);
1099 if (PredJTI >= 0) {
1100 if (PredJTI == JumpTableIndex)
1101 return true;
1102 continue;
1103 }
1104 // Be conservative for unanalyzable jumps.
1105 return true;
1106 }
1107 return false;
1108}
1109
1111private:
1112 MachineFunction &MF;
1113 SlotIndexes *Indexes;
1115
1116public:
1118 : MF(MF), Indexes(Indexes) {
1119 MF.setDelegate(this);
1120 }
1121
1123 MF.resetDelegate(this);
1124 for (auto MI : Insertions)
1125 Indexes->insertMachineInstrInMaps(*MI);
1126 }
1127
1129 // This is called before MI is inserted into block so defer index update.
1130 if (Indexes)
1131 Insertions.insert(&MI);
1132 }
1133
1135 if (Indexes && !Insertions.remove(&MI))
1137 }
1138};
1139
1140#define GET_RESULT(RESULT, GETTER, INFIX) \
1141 [MF, P, MFAM]() { \
1142 if (P) { \
1143 auto *Wrapper = P->getAnalysisIfAvailable<RESULT##INFIX##WrapperPass>(); \
1144 return Wrapper ? &Wrapper->GETTER() : nullptr; \
1145 } \
1146 return MFAM->getCachedResult<RESULT##Analysis>(*MF); \
1147 }()
1148
1151 std::vector<SparseBitVector<>> *LiveInSets, MachineDomTreeUpdater *MDTU) {
1152 assert((P || MFAM) && "Need a way to get analysis results!");
1153 if (!canSplitCriticalEdge(Succ))
1154 return nullptr;
1155
1156 MachineFunction *MF = getParent();
1157 MachineBasicBlock *PrevFallthrough = getNextNode();
1158
1160 NMBB->setCallFrameSize(Succ->getCallFrameSize());
1161
1162 // Is there an indirect jump with jump table?
1163 bool ChangedIndirectJump = false;
1164 int JTI = findJumpTableIndex(*this);
1165 if (JTI >= 0) {
1167 MJTI.ReplaceMBBInJumpTable(JTI, Succ, NMBB);
1168 ChangedIndirectJump = true;
1169 }
1170
1171 MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
1172 LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
1173 << " -- " << printMBBReference(*NMBB) << " -- "
1174 << printMBBReference(*Succ) << '\n');
1175
1176 LiveIntervals *LIS = GET_RESULT(LiveIntervals, getLIS, );
1177 SlotIndexes *Indexes = GET_RESULT(SlotIndexes, getSI, );
1178 if (LIS)
1179 LIS->insertMBBInMaps(NMBB);
1180 else if (Indexes)
1181 Indexes->insertMBBInMaps(NMBB);
1182
1183 // On some targets like Mips, branches may kill virtual registers. Make sure
1184 // that LiveVariables is properly updated after updateTerminator replaces the
1185 // terminators.
1186 LiveVariables *LV = GET_RESULT(LiveVariables, getLV, );
1187
1188 // Collect a list of virtual registers killed by the terminators.
1189 SmallVector<Register, 4> KilledRegs;
1190 if (LV)
1191 for (MachineInstr &MI :
1193 for (MachineOperand &MO : MI.all_uses()) {
1194 if (MO.getReg() == 0 || !MO.isKill() || MO.isUndef())
1195 continue;
1196 Register Reg = MO.getReg();
1197 if (Reg.isPhysical() || LV->getVarInfo(Reg).removeKill(MI)) {
1198 KilledRegs.push_back(Reg);
1199 LLVM_DEBUG(dbgs() << "Removing terminator kill: " << MI);
1200 MO.setIsKill(false);
1201 }
1202 }
1203 }
1204
1205 SmallVector<Register, 4> UsedRegs;
1206 if (LIS) {
1207 for (MachineInstr &MI :
1209 for (const MachineOperand &MO : MI.operands()) {
1210 if (!MO.isReg() || MO.getReg() == 0)
1211 continue;
1212
1213 Register Reg = MO.getReg();
1214 if (!is_contained(UsedRegs, Reg))
1215 UsedRegs.push_back(Reg);
1216 }
1217 }
1218 }
1219
1220 ReplaceUsesOfBlockWith(Succ, NMBB);
1221
1222 // Since we replaced all uses of Succ with NMBB, that should also be treated
1223 // as the fallthrough successor
1224 if (Succ == PrevFallthrough)
1225 PrevFallthrough = NMBB;
1226
1227 if (!ChangedIndirectJump) {
1228 SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1229 updateTerminator(PrevFallthrough);
1230 }
1231
1232 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
1233 NMBB->addSuccessor(Succ);
1234 if (!NMBB->isLayoutSuccessor(Succ)) {
1235 SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1238
1239 // In original 'this' BB, there must be a branch instruction targeting at
1240 // Succ. We can not find it out since currently getBranchDestBlock was not
1241 // implemented for all targets. However, if the merged DL has column or line
1242 // number, the scope and non-zero column and line number is same with that
1243 // branch instruction so we can safely use it.
1244 DebugLoc DL, MergedDL = findBranchDebugLoc();
1245 if (MergedDL && (MergedDL.getLine() || MergedDL.getCol()))
1246 DL = MergedDL;
1247 TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
1248 }
1249
1250 // Fix PHI nodes in Succ so they refer to NMBB instead of this.
1251 Succ->replacePhiUsesWith(this, NMBB);
1252
1253 // Inherit live-ins from the successor
1254 for (const auto &LI : Succ->liveins())
1255 NMBB->addLiveIn(LI);
1256
1257 // Update LiveVariables.
1259 if (LV) {
1260 // Restore kills of virtual registers that were killed by the terminators.
1261 while (!KilledRegs.empty()) {
1262 Register Reg = KilledRegs.pop_back_val();
1263 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
1264 if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false))
1265 continue;
1266 if (Reg.isVirtual())
1267 LV->getVarInfo(Reg).Kills.push_back(&*I);
1268 LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
1269 break;
1270 }
1271 }
1272 // Update relevant live-through information.
1273 if (LiveInSets != nullptr)
1274 LV->addNewBlock(NMBB, this, Succ, *LiveInSets);
1275 else
1276 LV->addNewBlock(NMBB, this, Succ);
1277 }
1278
1279 if (LIS) {
1280 // After splitting the edge and updating SlotIndexes, live intervals may be
1281 // in one of two situations, depending on whether this block was the last in
1282 // the function. If the original block was the last in the function, all
1283 // live intervals will end prior to the beginning of the new split block. If
1284 // the original block was not at the end of the function, all live intervals
1285 // will extend to the end of the new split block.
1286
1287 bool isLastMBB =
1288 std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
1289
1290 SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
1291 SlotIndex PrevIndex = StartIndex.getPrevSlot();
1292 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
1293
1294 // Find the registers used from NMBB in PHIs in Succ.
1295 SmallSet<Register, 8> PHISrcRegs;
1297 I = Succ->instr_begin(), E = Succ->instr_end();
1298 I != E && I->isPHI(); ++I) {
1299 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
1300 if (I->getOperand(ni+1).getMBB() == NMBB) {
1301 MachineOperand &MO = I->getOperand(ni);
1302 Register Reg = MO.getReg();
1303 PHISrcRegs.insert(Reg);
1304 if (MO.isUndef())
1305 continue;
1306
1307 LiveInterval &LI = LIS->getInterval(Reg);
1308 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1309 assert(VNI &&
1310 "PHI sources should be live out of their predecessors.");
1311 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1312 for (auto &SR : LI.subranges())
1313 SR.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1314 }
1315 }
1316 }
1317
1319 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1321 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
1322 continue;
1323
1324 LiveInterval &LI = LIS->getInterval(Reg);
1325 if (!LI.liveAt(PrevIndex))
1326 continue;
1327
1328 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
1329 if (isLiveOut && isLastMBB) {
1330 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1331 assert(VNI && "LiveInterval should have VNInfo where it is live.");
1332 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1333 // Update subranges with live values
1334 for (auto &SR : LI.subranges()) {
1335 VNInfo *VNI = SR.getVNInfoAt(PrevIndex);
1336 if (VNI)
1337 SR.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1338 }
1339 } else if (!isLiveOut && !isLastMBB) {
1340 LI.removeSegment(StartIndex, EndIndex);
1341 for (auto &SR : LI.subranges())
1342 SR.removeSegment(StartIndex, EndIndex);
1343 }
1344 }
1345
1346 // Update all intervals for registers whose uses may have been modified by
1347 // updateTerminator().
1348 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
1349 }
1350
1351 if (MDTU)
1352 MDTU->splitCriticalEdge(this, Succ, NMBB);
1353
1354 if (MachineLoopInfo *MLI = GET_RESULT(MachineLoop, getLI, Info))
1355 if (MachineLoop *TIL = MLI->getLoopFor(this)) {
1356 // If one or the other blocks were not in a loop, the new block is not
1357 // either, and thus LI doesn't need to be updated.
1358 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
1359 if (TIL == DestLoop) {
1360 // Both in the same loop, the NMBB joins loop.
1361 DestLoop->addBasicBlockToLoop(NMBB, *MLI);
1362 } else if (TIL->contains(DestLoop)) {
1363 // Edge from an outer loop to an inner loop. Add to the outer loop.
1364 TIL->addBasicBlockToLoop(NMBB, *MLI);
1365 } else if (DestLoop->contains(TIL)) {
1366 // Edge from an inner loop to an outer loop. Add to the outer loop.
1367 DestLoop->addBasicBlockToLoop(NMBB, *MLI);
1368 } else {
1369 // Edge from two loops with no containment relation. Because these
1370 // are natural loops, we know that the destination block must be the
1371 // header of its loop (adding a branch into a loop elsewhere would
1372 // create an irreducible loop).
1373 assert(DestLoop->getHeader() == Succ &&
1374 "Should not create irreducible loops!");
1375 if (MachineLoop *P = DestLoop->getParentLoop())
1376 P->addBasicBlockToLoop(NMBB, *MLI);
1377 }
1378 }
1379 }
1380
1381 return NMBB;
1382}
1383
1385 const MachineBasicBlock *Succ) const {
1386 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1387 // it in this generic function.
1388 if (Succ->isEHPad())
1389 return false;
1390
1391 // Splitting the critical edge to a callbr's indirect block isn't advised.
1392 // Don't do it in this generic function.
1393 if (Succ->isInlineAsmBrIndirectTarget())
1394 return false;
1395
1396 const MachineFunction *MF = getParent();
1397 // Performance might be harmed on HW that implements branching using exec mask
1398 // where both sides of the branches are always executed.
1399 if (MF->getTarget().requiresStructuredCFG())
1400 return false;
1401
1402 // Do we have an Indirect jump with a jumptable that we can rewrite?
1403 int JTI = findJumpTableIndex(*this);
1404 if (JTI >= 0 && !jumpTableHasOtherUses(*MF, *this, JTI))
1405 return true;
1406
1407 // We may need to update this's terminator, but we can't do that if
1408 // analyzeBranch fails.
1410 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1412 // AnalyzeBanch should modify this, since we did not allow modification.
1413 if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
1414 /*AllowModify*/ false))
1415 return false;
1416
1417 // Avoid bugpoint weirdness: A block may end with a conditional branch but
1418 // jumps to the same MBB is either case. We have duplicate CFG edges in that
1419 // case that we can't handle. Since this never happens in properly optimized
1420 // code, just skip those edges.
1421 if (TBB && TBB == FBB) {
1422 LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
1423 << printMBBReference(*this) << '\n');
1424 return false;
1425 }
1426 return true;
1427}
1428
1429/// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1430/// neighboring instructions so the bundle won't be broken by removing MI.
1432 // Removing the first instruction in a bundle.
1433 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1434 MI->unbundleFromSucc();
1435 // Removing the last instruction in a bundle.
1436 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1437 MI->unbundleFromPred();
1438 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1439 // are already fine.
1440}
1441
1445 return Insts.erase(I);
1446}
1447
1450 MI->clearFlag(MachineInstr::BundledPred);
1451 MI->clearFlag(MachineInstr::BundledSucc);
1452 return Insts.remove(MI);
1453}
1454
1457 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1458 "Cannot insert instruction with bundle flags");
1459 // Set the bundle flags when inserting inside a bundle.
1460 if (I != instr_end() && I->isBundledWithPred()) {
1461 MI->setFlag(MachineInstr::BundledPred);
1462 MI->setFlag(MachineInstr::BundledSucc);
1463 }
1464 return Insts.insert(I, MI);
1465}
1466
1467/// This method unlinks 'this' from the containing function, and returns it, but
1468/// does not delete it.
1470 assert(getParent() && "Not embedded in a function!");
1471 getParent()->remove(this);
1472 return this;
1473}
1474
1475/// This method unlinks 'this' from the containing function, and deletes it.
1477 assert(getParent() && "Not embedded in a function!");
1478 getParent()->erase(this);
1479}
1480
1481/// Given a machine basic block that branched to 'Old', change the code and CFG
1482/// so that it branches to 'New' instead.
1484 MachineBasicBlock *New) {
1485 assert(Old != New && "Cannot replace self with self!");
1486
1488 while (I != instr_begin()) {
1489 --I;
1490 if (!I->isTerminator()) break;
1491
1492 // Scan the operands of this machine instruction, replacing any uses of Old
1493 // with New.
1494 for (MachineOperand &MO : I->operands())
1495 if (MO.isMBB() && MO.getMBB() == Old)
1496 MO.setMBB(New);
1497 }
1498
1499 // Update the successor information.
1500 replaceSuccessor(Old, New);
1501}
1502
1504 MachineBasicBlock *New) {
1505 for (MachineInstr &MI : phis())
1506 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
1507 MachineOperand &MO = MI.getOperand(i);
1508 if (MO.getMBB() == Old)
1509 MO.setMBB(New);
1510 }
1511}
1512
1513/// Find the next valid DebugLoc starting at MBBI, skipping any debug
1514/// instructions. Return UnknownLoc if there is none.
1517 // Skip debug declarations, we don't want a DebugLoc from them.
1519 if (MBBI != instr_end())
1520 return MBBI->getDebugLoc();
1521 return {};
1522}
1523
1525 if (MBBI == instr_rend())
1526 return findDebugLoc(instr_begin());
1527 // Skip debug declarations, we don't want a DebugLoc from them.
1529 if (!MBBI->isDebugInstr())
1530 return MBBI->getDebugLoc();
1531 return {};
1532}
1533
1534/// Find the previous valid DebugLoc preceding MBBI, skipping any debug
1535/// instructions. Return UnknownLoc if there is none.
1537 if (MBBI == instr_begin())
1538 return {};
1539 // Skip debug instructions, we don't want a DebugLoc from them.
1541 if (!MBBI->isDebugInstr())
1542 return MBBI->getDebugLoc();
1543 return {};
1544}
1545
1547 if (MBBI == instr_rend())
1548 return {};
1549 // Skip debug declarations, we don't want a DebugLoc from them.
1551 if (MBBI != instr_rend())
1552 return MBBI->getDebugLoc();
1553 return {};
1554}
1555
1556/// Find and return the merged DebugLoc of the branch instructions of the block.
1557/// Return UnknownLoc if there is none.
1560 DebugLoc DL;
1561 auto TI = getFirstTerminator();
1562 while (TI != end() && !TI->isBranch())
1563 ++TI;
1564
1565 if (TI != end()) {
1566 DL = TI->getDebugLoc();
1567 for (++TI ; TI != end() ; ++TI)
1568 if (TI->isBranch())
1569 DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
1570 }
1571 return DL;
1572}
1573
1574/// Return probability of the edge from this block to MBB.
1577 if (Probs.empty())
1578 return BranchProbability(1, succ_size());
1579
1580 const auto &Prob = *getProbabilityIterator(Succ);
1581 if (Prob.isUnknown()) {
1582 // For unknown probabilities, collect the sum of all known ones, and evenly
1583 // ditribute the complemental of the sum to each unknown probability.
1584 unsigned KnownProbNum = 0;
1585 auto Sum = BranchProbability::getZero();
1586 for (const auto &P : Probs) {
1587 if (!P.isUnknown()) {
1588 Sum += P;
1589 KnownProbNum++;
1590 }
1591 }
1592 return Sum.getCompl() / (Probs.size() - KnownProbNum);
1593 } else
1594 return Prob;
1595}
1596
1597/// Set successor probability of a given iterator.
1599 BranchProbability Prob) {
1600 assert(!Prob.isUnknown());
1601 if (Probs.empty())
1602 return;
1603 *getProbabilityIterator(I) = Prob;
1604}
1605
1606/// Return probability iterator corresonding to the I successor iterator
1607MachineBasicBlock::const_probability_iterator
1608MachineBasicBlock::getProbabilityIterator(
1610 assert(Probs.size() == Successors.size() && "Async probability list!");
1611 const size_t index = std::distance(Successors.begin(), I);
1612 assert(index < Probs.size() && "Not a current successor!");
1613 return Probs.begin() + index;
1614}
1615
1616/// Return probability iterator corresonding to the I successor iterator.
1617MachineBasicBlock::probability_iterator
1618MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1619 assert(Probs.size() == Successors.size() && "Async probability list!");
1620 const size_t index = std::distance(Successors.begin(), I);
1621 assert(index < Probs.size() && "Not a current successor!");
1622 return Probs.begin() + index;
1623}
1624
1625/// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1626/// as of just before "MI".
1627///
1628/// Search is localised to a neighborhood of
1629/// Neighborhood instructions before (searching for defs or kills) and N
1630/// instructions after (searching just for defs) MI.
1634 unsigned Neighborhood) const {
1635 unsigned N = Neighborhood;
1636
1637 // Try searching forwards from Before, looking for reads or defs.
1639 for (; I != end() && N > 0; ++I) {
1640 if (I->isDebugOrPseudoInstr())
1641 continue;
1642
1643 --N;
1644
1646
1647 // Register is live when we read it here.
1648 if (Info.Read)
1649 return LQR_Live;
1650 // Register is dead if we can fully overwrite or clobber it here.
1651 if (Info.FullyDefined || Info.Clobbered)
1652 return LQR_Dead;
1653 }
1654
1655 // If we reached the end, it is safe to clobber Reg at the end of a block of
1656 // no successor has it live in.
1657 if (I == end()) {
1658 for (MachineBasicBlock *S : successors()) {
1659 for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
1660 if (TRI->regsOverlap(LI.PhysReg, Reg))
1661 return LQR_Live;
1662 }
1663 }
1664
1665 return LQR_Dead;
1666 }
1667
1668
1669 N = Neighborhood;
1670
1671 // Start by searching backwards from Before, looking for kills, reads or defs.
1673 // If this is the first insn in the block, don't search backwards.
1674 if (I != begin()) {
1675 do {
1676 --I;
1677
1678 if (I->isDebugOrPseudoInstr())
1679 continue;
1680
1681 --N;
1682
1684
1685 // Defs happen after uses so they take precedence if both are present.
1686
1687 // Register is dead after a dead def of the full register.
1688 if (Info.DeadDef)
1689 return LQR_Dead;
1690 // Register is (at least partially) live after a def.
1691 if (Info.Defined) {
1692 if (!Info.PartialDeadDef)
1693 return LQR_Live;
1694 // As soon as we saw a partial definition (dead or not),
1695 // we cannot tell if the value is partial live without
1696 // tracking the lanemasks. We are not going to do this,
1697 // so fall back on the remaining of the analysis.
1698 break;
1699 }
1700 // Register is dead after a full kill or clobber and no def.
1701 if (Info.Killed || Info.Clobbered)
1702 return LQR_Dead;
1703 // Register must be live if we read it.
1704 if (Info.Read)
1705 return LQR_Live;
1706
1707 } while (I != begin() && N > 0);
1708 }
1709
1710 // If all the instructions before this in the block are debug instructions,
1711 // skip over them.
1712 while (I != begin() && std::prev(I)->isDebugOrPseudoInstr())
1713 --I;
1714
1715 // Did we get to the start of the block?
1716 if (I == begin()) {
1717 // If so, the register's state is definitely defined by the live-in state.
1719 if (TRI->regsOverlap(LI.PhysReg, Reg))
1720 return LQR_Live;
1721
1722 return LQR_Dead;
1723 }
1724
1725 // At this point we have no idea of the liveness of the register.
1726 return LQR_Unknown;
1727}
1728
1729const uint32_t *
1731 // EH funclet entry does not preserve any registers.
1732 return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1733}
1734
1735const uint32_t *
1737 // If we see a return block with successors, this must be a funclet return,
1738 // which does not preserve any registers. If there are no successors, we don't
1739 // care what kind of return it is, putting a mask after it is a no-op.
1740 return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1741}
1742
1744 LiveIns.clear();
1745}
1746
1748 std::vector<RegisterMaskPair> &OldLiveIns) {
1749 assert(OldLiveIns.empty() && "Vector must be empty");
1750 std::swap(LiveIns, OldLiveIns);
1751}
1752
1754 assert(getParent()->getProperties().hasProperty(
1756 "Liveness information is accurate");
1757 return LiveIns.begin();
1758}
1759
1761 const MachineFunction &MF = *getParent();
1764 "Liveness information is accurate");
1765
1766 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1767 MCPhysReg ExceptionPointer = 0, ExceptionSelector = 0;
1768 if (MF.getFunction().hasPersonalityFn()) {
1769 auto PersonalityFn = MF.getFunction().getPersonalityFn();
1770 ExceptionPointer = TLI.getExceptionPointerRegister(PersonalityFn);
1771 ExceptionSelector = TLI.getExceptionSelectorRegister(PersonalityFn);
1772 }
1773
1774 return liveout_iterator(*this, ExceptionPointer, ExceptionSelector, false);
1775}
1776
1778 unsigned Cntr = 0;
1779 auto R = instructionsWithoutDebug(begin(), end());
1780 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1781 if (++Cntr > Limit)
1782 return true;
1783 }
1784 return false;
1785}
1786
1788const MBBSectionID
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:622
#define LLVM_DEBUG(...)
Definition: Debug.h:106
std::string Name
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:55
#define I(x, y, z)
Definition: MD5.cpp:58
#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)
unsigned const TargetRegisterInfo * TRI
uint64_t IntrinsicInst * II
#define P(N)
uint32_t Number
Definition: Profile.cpp:47
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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.
raw_pwrite_stream & OS
This file contains some functions that are useful when dealing with strings.
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.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
static uint32_t getDenominator()
static BranchProbability getUnknown()
uint32_t getNumerator() const
static BranchProbability getZero()
static DILocation * getMergedLocation(DILocation *LocA, DILocation *LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
A debug info location.
Definition: DebugLoc.h:33
unsigned getLine() const
Definition: DebugLoc.cpp:24
unsigned getCol() const
Definition: DebugLoc.cpp:29
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.
Definition: Function.cpp:1048
void splitCriticalEdge(BasicBlockT *FromBB, BasicBlockT *ToBB, BasicBlockT *NewBB)
Apply updates that the critical edge (FromBB, ToBB) has been split with NewBB.
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
Remove the branching code at the end of the specific MBB.
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
Insert branch code into the end of the specified MachineBasicBlock.
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:687
iterator_range< subrange_iterator > subranges()
Definition: LiveInterval.h:782
void repairIntervalsInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, ArrayRef< Register > OrigRegs)
Update live intervals for instructions in a range of iterators.
bool hasInterval(Register Reg) const
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
void insertMBBInMaps(MachineBasicBlock *MBB)
LiveInterval & getInterval(Register Reg)
A set of physical registers with utility functions to track liveness when walking backward/forward th...
Definition: LivePhysRegs.h:52
void stepBackward(const MachineInstr &MI)
Simulates liveness when stepping backwards over an instruction(bundle).
void init(const TargetRegisterInfo &TRI)
(re-)initializes and clears the set.
Definition: LivePhysRegs.h:70
void addLiveOuts(const MachineBasicBlock &MBB)
Adds all live-out registers of basic block MBB.
iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
bool liveAt(SlotIndex index) const
Definition: LiveInterval.h:401
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.
Definition: LiveInterval.h:421
VarInfo & getVarInfo(Register Reg)
getVarInfo - Return the VarInfo structure for the specified VIRTUAL register.
void addNewBlock(MachineBasicBlock *BB, MachineBasicBlock *DomBB, MachineBasicBlock *SuccBB)
addNewBlock - Add a new basic block BB between DomBB and SuccBB.
Context object for machine code objects.
Definition: MCContext.h:83
MCSymbol * createBlockSymbol(const Twine &Name, bool AlwaysEmit=false)
Get or create a symbol for a basic block.
Definition: MCContext.cpp:324
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:212
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
DebugLoc rfindPrevDebugLoc(reverse_instr_iterator MBBI)
Has exact same behavior as findPrevDebugLoc (it also searches towards the beginning of this MBB) exce...
void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
livein_iterator livein_end() const
iterator getFirstTerminatorForward()
Finds the first terminator in a block by scanning forward.
bool isEHPad() const
Returns true if the block is a landing pad.
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.
MachineInstr * remove_instr(MachineInstr *I)
Remove the possibly bundled instruction from the instruction list without deleting it.
instr_iterator instr_begin()
MachineInstrBundleIterator< const MachineInstr > const_iterator
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
SmallVectorImpl< MachineBasicBlock * >::const_iterator const_succ_iterator
MCSymbol * getEHCatchretSymbol() const
Return the EHCatchret Symbol for this basic block.
void moveBefore(MachineBasicBlock *NewAfter)
Move 'this' block before or after the specified block.
void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
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)
Split the critical edge from this block to the given successor block, and return the newly created bl...
bool hasLabelMustBeEmitted() const
Test whether this block must have its label emitted.
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
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...
iterator SkipPHIsAndLabels(iterator I)
Return the first instruction in MBB after I that is not a PHI or a label.
void addSuccessorWithoutProb(MachineBasicBlock *Succ)
Add Succ as a successor of this MachineBasicBlock.
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.
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.
void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor)
Update the terminator instructions in block to account for changes to block layout which may have bee...
const MachineBasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor.
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.
bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
void setSuccProbability(succ_iterator I, BranchProbability Prob)
Set successor probability of a given iterator.
iterator getFirstNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the first non-debug instruction in the basic block, or end().
void removeLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Remove the specified register from the live in set.
void printAsOperand(raw_ostream &OS, bool PrintType=true) const
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
MCSymbol * getEndSymbol() const
Returns the MCSymbol marking the end of this basic block.
void clearLiveIns()
Clear live in list.
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
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.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
livein_iterator livein_begin() const
unsigned succ_size() const
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
const uint32_t * getBeginClobberMask(const TargetRegisterInfo *TRI) const
Get the clobber mask for the start of this basic block.
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
bool isEntryBlock() const
Returns true if this is the entry block of the function.
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
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.
void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
const MachineBasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
liveout_iterator liveout_begin() const
Iterator scanning successor basic blocks' liveins to determine the registers potentially live at the ...
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
bool isPredecessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a predecessor of this block.
DebugLoc rfindDebugLoc(reverse_instr_iterator MBBI)
Has exact same behavior as findDebugLoc (it also searches towards the end of this MBB) except that th...
void print(raw_ostream &OS, const SlotIndexes *=nullptr, bool IsStandalone=true) const
reverse_instr_iterator instr_rend()
DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
Instructions::iterator instr_iterator
iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
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...
bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
DebugLoc findPrevDebugLoc(instr_iterator MBBI)
Find the previous valid DebugLoc preceding MBBI, skipping any debug instructions.
MachineBasicBlock * splitAt(MachineInstr &SplitInst, bool UpdateLiveIns=true, LiveIntervals *LIS=nullptr)
Split a basic block into 2 pieces at SplitPoint.
void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
instr_iterator instr_end()
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.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
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.
DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
iterator_range< succ_iterator > successors()
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,...
void printName(raw_ostream &os, unsigned printNameFlags=PrintNameIr, ModuleSlotTracker *moduleSlotTracker=nullptr) const
Print the basic block's name as:
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.
bool canSplitCriticalEdge(const MachineBasicBlock *Succ) const
Check if the edge between this block and the given successor Succ, can be split.
bool isLegalToHoistInto() const
Returns true if it is legal to hoist instructions into this block.
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
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.
void moveAfter(MachineBasicBlock *NewBefore)
const uint32_t * getEndClobberMask(const TargetRegisterInfo *TRI) const
Get the clobber mask for the end of the basic block.
bool sizeWithoutDebugLargerThan(unsigned Limit) const
bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
MachineBasicBlock * removeFromParent()
This method unlinks 'this' from the containing function, and returns it, but does not delete it.
Instructions::reverse_iterator reverse_instr_iterator
bool hasProperty(Property P) const
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.
void resetDelegate(Delegate *delegate)
Reset the currently registered delegate - otherwise assert.
Function & getFunction()
Return the LLVM function that this machine code represents.
void remove(iterator MBBI)
const MachineFunctionProperties & getProperties() const
Get the function properties.
void setDelegate(Delegate *delegate)
Set the delegate.
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)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
void erase(iterator MBBI)
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
BasicBlockListType::const_iterator const_iterator
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
Representation of each machine instruction.
Definition: MachineInstr.h:69
bool ReplaceMBBInJumpTable(unsigned Idx, MachineBasicBlock *Old, MachineBasicBlock *New)
ReplaceMBBInJumpTable - If Old is a target of the jump tables, update the jump table to branch to New...
const std::vector< MachineJumpTableEntry > & getJumpTables() const
MachineOperand class - Representation of each machine instruction operand.
MachineBasicBlock * getMBB() const
void setMBB(MachineBasicBlock *MBB)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Manage lifetime of a slot tracker for printing IR.
int getLocalSlot(const Value *V)
Return the slot number of the specified local value.
Definition: AsmWriter.cpp:918
void incorporateFunction(const Function &F)
Incorporate the given function.
Definition: AsmWriter.cpp:904
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:94
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition: Pass.cpp:130
Simple wrapper around std::function<void(raw_ostream&)>.
Definition: Printable.h:38
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:84
static constexpr bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:65
bool remove(const value_type &X)
Remove an item from the set vector.
Definition: SetVector.h:188
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:65
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
Definition: SlotIndexes.h:272
SlotIndexes pass.
Definition: SlotIndexes.h:297
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
Definition: SlotIndexes.h:531
void removeMachineInstrFromMaps(MachineInstr &MI, bool AllowBundled=false)
Removes machine instruction (bundle) MI from the mapping.
void insertMBBInMaps(MachineBasicBlock *mbb)
Add the given MachineBasicBlock into the maps.
Definition: SlotIndexes.h:606
SlotIndex getMBBEndIdx(unsigned Num) const
Returns the last index in the given basic block number.
Definition: SlotIndexes.h:470
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
Definition: SlotIndexes.h:379
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
Definition: SlotIndexes.h:460
bool hasIndex(const MachineInstr &instr) const
Returns true if the given machine instr is mapped to an index, otherwise returns false.
Definition: SlotIndexes.h:374
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:132
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:175
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:181
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
bool empty() const
Definition: SmallVector.h:81
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
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 TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetLowering * getTargetLowering() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
VNInfo - Value Number Information.
Definition: LiveInterval.h:53
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
MachineBasicBlock * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:353
iterator erase(iterator where)
Definition: ilist.h:204
pointer remove(iterator &IT)
Definition: ilist.h:188
iterator insert(iterator where, pointer New)
Definition: ilist.h:165
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Kill
The last use of a register.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:1759
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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
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:1664
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
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:125
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:303
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:1766
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1903
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
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.
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:860
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
This represents a simple continuous liveness interval for a value.
Definition: LiveInterval.h:162
bool removeKill(MachineInstr &MI)
removeKill - Delete a kill corresponding to the specified machine instruction.
Definition: LiveVariables.h:93
std::vector< MachineInstr * > Kills
Kills - List of MachineInstruction's which are the last use of this virtual register (kill it) in the...
Definition: LiveVariables.h:88
static const MBBSectionID ExceptionSectionID
static const MBBSectionID ColdSectionID
enum llvm::MBBSectionID::SectionType Type
Pair of physical register and lane mask.
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 *)
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