LLVM 17.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"
29#include "llvm/Config/llvm-config.h"
30#include "llvm/IR/BasicBlock.h"
33#include "llvm/MC/MCAsmInfo.h"
34#include "llvm/MC/MCContext.h"
35#include "llvm/Support/Debug.h"
38#include <algorithm>
39#include <cmath>
40using namespace llvm;
41
42#define DEBUG_TYPE "codegen"
43
45 "print-slotindexes",
46 cl::desc("When printing machine IR, annotate instructions and blocks with "
47 "SlotIndexes when available"),
48 cl::init(true), cl::Hidden);
49
50MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
51 : BB(B), Number(-1), xParent(&MF) {
52 Insts.Parent = this;
53 if (B)
54 IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight();
55}
56
57MachineBasicBlock::~MachineBasicBlock() = default;
58
59/// Return the MCSymbol for this basic block.
61 if (!CachedMCSymbol) {
62 const MachineFunction *MF = getParent();
63 MCContext &Ctx = MF->getContext();
64
65 // We emit a non-temporary symbol -- with a descriptive name -- if it begins
66 // a section (with basic block sections). Otherwise we fall back to use temp
67 // label.
68 if (MF->hasBBSections() && isBeginSection()) {
69 SmallString<5> Suffix;
70 if (SectionID == MBBSectionID::ColdSectionID) {
71 Suffix += ".cold";
72 } else if (SectionID == MBBSectionID::ExceptionSectionID) {
73 Suffix += ".eh";
74 } else {
75 // For symbols that represent basic block sections, we add ".__part." to
76 // allow tools like symbolizers to know that this represents a part of
77 // the original function.
78 Suffix = (Suffix + Twine(".__part.") + Twine(SectionID.Number)).str();
79 }
80 CachedMCSymbol = Ctx.getOrCreateSymbol(MF->getName() + Suffix);
81 } else {
82 const StringRef Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
83 CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
85 "_" + Twine(getNumber()));
86 }
87 }
88 return CachedMCSymbol;
89}
90
92 if (!CachedEHCatchretMCSymbol) {
93 const MachineFunction *MF = getParent();
94 SmallString<128> SymbolName;
95 raw_svector_ostream(SymbolName)
96 << "$ehgcr_" << MF->getFunctionNumber() << '_' << getNumber();
97 CachedEHCatchretMCSymbol = MF->getContext().getOrCreateSymbol(SymbolName);
98 }
99 return CachedEHCatchretMCSymbol;
100}
101
103 if (!CachedEndMCSymbol) {
104 const MachineFunction *MF = getParent();
105 MCContext &Ctx = MF->getContext();
106 auto Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
107 CachedEndMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB_END" +
108 Twine(MF->getFunctionNumber()) +
109 "_" + Twine(getNumber()));
110 }
111 return CachedEndMCSymbol;
112}
113
115 MBB.print(OS);
116 return OS;
117}
118
120 return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); });
121}
122
123/// When an MBB is added to an MF, we need to update the parent pointer of the
124/// MBB, the MBB numbering, and any instructions in the MBB to be on the right
125/// operand list for registers.
126///
127/// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
128/// gets the next available unique MBB number. If it is removed from a
129/// MachineFunction, it goes back to being #-1.
132 MachineFunction &MF = *N->getParent();
133 N->Number = MF.addToMBBNumbering(N);
134
135 // Make sure the instructions have their operands in the reginfo lists.
136 MachineRegisterInfo &RegInfo = MF.getRegInfo();
137 for (MachineInstr &MI : N->instrs())
138 MI.addRegOperandsToUseLists(RegInfo);
139}
140
143 N->getParent()->removeFromMBBNumbering(N->Number);
144 N->Number = -1;
145}
146
147/// When we add an instruction to a basic block list, we update its parent
148/// pointer and add its operands from reg use/def lists if appropriate.
150 assert(!N->getParent() && "machine instruction already in a basic block");
151 N->setParent(Parent);
152
153 // Add the instruction's register operands to their corresponding
154 // use/def lists.
155 MachineFunction *MF = Parent->getParent();
156 N->addRegOperandsToUseLists(MF->getRegInfo());
157 MF->handleInsertion(*N);
158}
159
160/// When we remove an instruction from a basic block list, we update its parent
161/// pointer and remove its operands from reg use/def lists if appropriate.
163 assert(N->getParent() && "machine instruction not in a basic block");
164
165 // Remove from the use/def lists.
166 if (MachineFunction *MF = N->getMF()) {
167 MF->handleRemoval(*N);
168 N->removeRegOperandsFromUseLists(MF->getRegInfo());
169 }
170
171 N->setParent(nullptr);
172}
173
174/// When moving a range of instructions from one MBB list to another, we need to
175/// update the parent pointers and the use/def lists.
177 instr_iterator First,
178 instr_iterator Last) {
179 assert(Parent->getParent() == FromList.Parent->getParent() &&
180 "cannot transfer MachineInstrs between MachineFunctions");
181
182 // If it's within the same BB, there's nothing to do.
183 if (this == &FromList)
184 return;
185
186 assert(Parent != FromList.Parent && "Two lists have the same parent?");
187
188 // If splicing between two blocks within the same function, just update the
189 // parent pointers.
190 for (; First != Last; ++First)
191 First->setParent(Parent);
192}
193
195 assert(!MI->getParent() && "MI is still in a block!");
196 Parent->getParent()->deleteMachineInstr(MI);
197}
198
201 while (I != E && I->isPHI())
202 ++I;
203 assert((I == E || !I->isInsideBundle()) &&
204 "First non-phi MI cannot be inside a bundle!");
205 return I;
206}
207
211
212 iterator E = end();
213 while (I != E && (I->isPHI() || I->isPosition() ||
214 TII->isBasicBlockPrologue(*I)))
215 ++I;
216 // FIXME: This needs to change if we wish to bundle labels
217 // inside the bundle.
218 assert((I == E || !I->isInsideBundle()) &&
219 "First non-phi / non-label instruction is inside a bundle!");
220 return I;
221}
222
225 bool SkipPseudoOp) {
227
228 iterator E = end();
229 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() ||
230 (SkipPseudoOp && I->isPseudoProbe()) ||
231 TII->isBasicBlockPrologue(*I)))
232 ++I;
233 // FIXME: This needs to change if we wish to bundle labels / dbg_values
234 // inside the bundle.
235 assert((I == E || !I->isInsideBundle()) &&
236 "First non-phi / non-label / non-debug "
237 "instruction is inside a bundle!");
238 return I;
239}
240
242 iterator B = begin(), E = end(), I = E;
243 while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
244 ; /*noop */
245 while (I != E && !I->isTerminator())
246 ++I;
247 return I;
248}
249
252 while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
253 ; /*noop */
254 while (I != E && !I->isTerminator())
255 ++I;
256 return I;
257}
258
260 return find_if(instrs(), [](auto &II) { return II.isTerminator(); });
261}
262
265 // Skip over begin-of-block dbg_value instructions.
266 return skipDebugInstructionsForward(begin(), end(), SkipPseudoOp);
267}
268
271 // Skip over end-of-block dbg_value instructions.
273 while (I != B) {
274 --I;
275 // Return instruction that starts a bundle.
276 if (I->isDebugInstr() || I->isInsideBundle())
277 continue;
278 if (SkipPseudoOp && I->isPseudoProbe())
279 continue;
280 return I;
281 }
282 // The block is all debug values.
283 return end();
284}
285
287 for (const MachineBasicBlock *Succ : successors())
288 if (Succ->isEHPad())
289 return true;
290 return false;
291}
292
294 return getParent()->begin() == getIterator();
295}
296
297#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
299 print(dbgs());
300}
301#endif
302
304 for (const MachineBasicBlock *Succ : successors()) {
305 if (Succ->isInlineAsmBrIndirectTarget())
306 return true;
307 }
308 return false;
309}
310
313 return false;
314 return true;
315}
316
318 if (const BasicBlock *LBB = getBasicBlock())
319 return LBB->getName();
320 else
321 return StringRef("", 0);
322}
323
324/// Return a hopefully unique identifier for this block.
326 std::string Name;
327 if (getParent())
328 Name = (getParent()->getName() + ":").str();
329 if (getBasicBlock())
330 Name += getBasicBlock()->getName();
331 else
332 Name += ("BB" + Twine(getNumber())).str();
333 return Name;
334}
335
337 bool IsStandalone) const {
338 const MachineFunction *MF = getParent();
339 if (!MF) {
340 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
341 << " is null\n";
342 return;
343 }
344 const Function &F = MF->getFunction();
345 const Module *M = F.getParent();
346 ModuleSlotTracker MST(M);
348 print(OS, MST, Indexes, IsStandalone);
349}
350
352 const SlotIndexes *Indexes,
353 bool IsStandalone) const {
354 const MachineFunction *MF = getParent();
355 if (!MF) {
356 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
357 << " is null\n";
358 return;
359 }
360
361 if (Indexes && PrintSlotIndexes)
362 OS << Indexes->getMBBStartIdx(this) << '\t';
363
365 OS << ":\n";
366
368 const MachineRegisterInfo &MRI = MF->getRegInfo();
370 bool HasLineAttributes = false;
371
372 // Print the preds of this block according to the CFG.
373 if (!pred_empty() && IsStandalone) {
374 if (Indexes) OS << '\t';
375 // Don't indent(2), align with previous line attributes.
376 OS << "; predecessors: ";
377 ListSeparator LS;
378 for (auto *Pred : predecessors())
379 OS << LS << printMBBReference(*Pred);
380 OS << '\n';
381 HasLineAttributes = true;
382 }
383
384 if (!succ_empty()) {
385 if (Indexes) OS << '\t';
386 // Print the successors
387 OS.indent(2) << "successors: ";
388 ListSeparator LS;
389 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
390 OS << LS << printMBBReference(**I);
391 if (!Probs.empty())
392 OS << '('
393 << format("0x%08" PRIx32, getSuccProbability(I).getNumerator())
394 << ')';
395 }
396 if (!Probs.empty() && IsStandalone) {
397 // Print human readable probabilities as comments.
398 OS << "; ";
399 ListSeparator LS;
400 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
402 OS << LS << printMBBReference(**I) << '('
403 << format("%.2f%%",
404 rint(((double)BP.getNumerator() / BP.getDenominator()) *
405 100.0 * 100.0) /
406 100.0)
407 << ')';
408 }
409 }
410
411 OS << '\n';
412 HasLineAttributes = true;
413 }
414
415 if (!livein_empty() && MRI.tracksLiveness()) {
416 if (Indexes) OS << '\t';
417 OS.indent(2) << "liveins: ";
418
419 ListSeparator LS;
420 for (const auto &LI : liveins()) {
421 OS << LS << printReg(LI.PhysReg, TRI);
422 if (!LI.LaneMask.all())
423 OS << ":0x" << PrintLaneMask(LI.LaneMask);
424 }
425 HasLineAttributes = true;
426 }
427
428 if (HasLineAttributes)
429 OS << '\n';
430
431 bool IsInBundle = false;
432 for (const MachineInstr &MI : instrs()) {
433 if (Indexes && PrintSlotIndexes) {
434 if (Indexes->hasIndex(MI))
435 OS << Indexes->getInstructionIndex(MI);
436 OS << '\t';
437 }
438
439 if (IsInBundle && !MI.isInsideBundle()) {
440 OS.indent(2) << "}\n";
441 IsInBundle = false;
442 }
443
444 OS.indent(IsInBundle ? 4 : 2);
445 MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
446 /*AddNewLine=*/false, &TII);
447
448 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
449 OS << " {";
450 IsInBundle = true;
451 }
452 OS << '\n';
453 }
454
455 if (IsInBundle)
456 OS.indent(2) << "}\n";
457
458 if (IrrLoopHeaderWeight && IsStandalone) {
459 if (Indexes) OS << '\t';
460 OS.indent(2) << "; Irreducible loop header weight: " << *IrrLoopHeaderWeight
461 << '\n';
462 }
463}
464
465/// Print the basic block's name as:
466///
467/// bb.{number}[.{ir-name}] [(attributes...)]
468///
469/// The {ir-name} is only printed when the \ref PrintNameIr flag is passed
470/// (which is the default). If the IR block has no name, it is identified
471/// numerically using the attribute syntax as "(%ir-block.{ir-slot})".
472///
473/// When the \ref PrintNameAttributes flag is passed, additional attributes
474/// of the block are printed when set.
475///
476/// \param printNameFlags Combination of \ref PrintNameFlag flags indicating
477/// the parts to print.
478/// \param moduleSlotTracker Optional ModuleSlotTracker. This method will
479/// incorporate its own tracker when necessary to
480/// determine the block's IR name.
481void MachineBasicBlock::printName(raw_ostream &os, unsigned printNameFlags,
482 ModuleSlotTracker *moduleSlotTracker) const {
483 os << "bb." << getNumber();
484 bool hasAttributes = false;
485
486 auto PrintBBRef = [&](const BasicBlock *bb) {
487 os << "%ir-block.";
488 if (bb->hasName()) {
489 os << bb->getName();
490 } else {
491 int slot = -1;
492
493 if (moduleSlotTracker) {
494 slot = moduleSlotTracker->getLocalSlot(bb);
495 } else if (bb->getParent()) {
496 ModuleSlotTracker tmpTracker(bb->getModule(), false);
497 tmpTracker.incorporateFunction(*bb->getParent());
498 slot = tmpTracker.getLocalSlot(bb);
499 }
500
501 if (slot == -1)
502 os << "<ir-block badref>";
503 else
504 os << slot;
505 }
506 };
507
508 if (printNameFlags & PrintNameIr) {
509 if (const auto *bb = getBasicBlock()) {
510 if (bb->hasName()) {
511 os << '.' << bb->getName();
512 } else {
513 hasAttributes = true;
514 os << " (";
515 PrintBBRef(bb);
516 }
517 }
518 }
519
520 if (printNameFlags & PrintNameAttributes) {
522 os << (hasAttributes ? ", " : " (");
523 os << "machine-block-address-taken";
524 hasAttributes = true;
525 }
526 if (isIRBlockAddressTaken()) {
527 os << (hasAttributes ? ", " : " (");
528 os << "ir-block-address-taken ";
529 PrintBBRef(getAddressTakenIRBlock());
530 hasAttributes = true;
531 }
532 if (isEHPad()) {
533 os << (hasAttributes ? ", " : " (");
534 os << "landing-pad";
535 hasAttributes = true;
536 }
538 os << (hasAttributes ? ", " : " (");
539 os << "inlineasm-br-indirect-target";
540 hasAttributes = true;
541 }
542 if (isEHFuncletEntry()) {
543 os << (hasAttributes ? ", " : " (");
544 os << "ehfunclet-entry";
545 hasAttributes = true;
546 }
547 if (getAlignment() != Align(1)) {
548 os << (hasAttributes ? ", " : " (");
549 os << "align " << getAlignment().value();
550 hasAttributes = true;
551 }
552 if (getSectionID() != MBBSectionID(0)) {
553 os << (hasAttributes ? ", " : " (");
554 os << "bbsections ";
555 switch (getSectionID().Type) {
557 os << "Exception";
558 break;
560 os << "Cold";
561 break;
562 default:
563 os << getSectionID().Number;
564 }
565 hasAttributes = true;
566 }
567 if (getBBID().has_value()) {
568 os << (hasAttributes ? ", " : " (");
569 os << "bb_id " << *getBBID();
570 hasAttributes = true;
571 }
572 }
573
574 if (hasAttributes)
575 os << ')';
576}
577
579 bool /*PrintType*/) const {
580 OS << '%';
581 printName(OS, 0);
582}
583
585 LiveInVector::iterator I = find_if(
586 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
587 if (I == LiveIns.end())
588 return;
589
590 I->LaneMask &= ~LaneMask;
591 if (I->LaneMask.none())
592 LiveIns.erase(I);
593}
594
597 // Get non-const version of iterator.
598 LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
599 return LiveIns.erase(LI);
600}
601
604 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
605 return I != livein_end() && (I->LaneMask & LaneMask).any();
606}
607
609 llvm::sort(LiveIns,
610 [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
611 return LI0.PhysReg < LI1.PhysReg;
612 });
613 // Liveins are sorted by physreg now we can merge their lanemasks.
614 LiveInVector::const_iterator I = LiveIns.begin();
615 LiveInVector::const_iterator J;
616 LiveInVector::iterator Out = LiveIns.begin();
617 for (; I != LiveIns.end(); ++Out, I = J) {
618 MCRegister PhysReg = I->PhysReg;
619 LaneBitmask LaneMask = I->LaneMask;
620 for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
621 LaneMask |= J->LaneMask;
622 Out->PhysReg = PhysReg;
623 Out->LaneMask = LaneMask;
624 }
625 LiveIns.erase(Out, LiveIns.end());
626}
627
630 assert(getParent() && "MBB must be inserted in function");
631 assert(Register::isPhysicalRegister(PhysReg) && "Expected physreg");
632 assert(RC && "Register class is required");
633 assert((isEHPad() || this == &getParent()->front()) &&
634 "Only the entry block and landing pads can have physreg live ins");
635
636 bool LiveIn = isLiveIn(PhysReg);
640
641 // Look for an existing copy.
642 if (LiveIn)
643 for (;I != E && I->isCopy(); ++I)
644 if (I->getOperand(1).getReg() == PhysReg) {
645 Register VirtReg = I->getOperand(0).getReg();
646 if (!MRI.constrainRegClass(VirtReg, RC))
647 llvm_unreachable("Incompatible live-in register class.");
648 return VirtReg;
649 }
650
651 // No luck, create a virtual register.
652 Register VirtReg = MRI.createVirtualRegister(RC);
653 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
654 .addReg(PhysReg, RegState::Kill);
655 if (!LiveIn)
656 addLiveIn(PhysReg);
657 return VirtReg;
658}
659
661 getParent()->splice(NewAfter->getIterator(), getIterator());
662}
663
665 getParent()->splice(++NewBefore->getIterator(), getIterator());
666}
667
670 if (TerminatorI == MBB.end())
671 return -1;
672 const MachineInstr &Terminator = *TerminatorI;
674 return TII->getJumpTableIndex(Terminator);
675}
676
678 MachineBasicBlock *PreviousLayoutSuccessor) {
679 LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
680 << "\n");
681
683 // A block with no successors has no concerns with fall-through edges.
684 if (this->succ_empty())
685 return;
686
687 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
690 bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
691 (void) B;
692 assert(!B && "UpdateTerminators requires analyzable predecessors!");
693 if (Cond.empty()) {
694 if (TBB) {
695 // The block has an unconditional branch. If its successor is now its
696 // layout successor, delete the branch.
698 TII->removeBranch(*this);
699 } else {
700 // The block has an unconditional fallthrough, or the end of the block is
701 // unreachable.
702
703 // Unfortunately, whether the end of the block is unreachable is not
704 // immediately obvious; we must fall back to checking the successor list,
705 // and assuming that if the passed in block is in the succesor list and
706 // not an EHPad, it must be the intended target.
707 if (!PreviousLayoutSuccessor || !isSuccessor(PreviousLayoutSuccessor) ||
708 PreviousLayoutSuccessor->isEHPad())
709 return;
710
711 // If the unconditional successor block is not the current layout
712 // successor, insert a branch to jump to it.
713 if (!isLayoutSuccessor(PreviousLayoutSuccessor))
714 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
715 }
716 return;
717 }
718
719 if (FBB) {
720 // The block has a non-fallthrough conditional branch. If one of its
721 // successors is its layout successor, rewrite it to a fallthrough
722 // conditional branch.
723 if (isLayoutSuccessor(TBB)) {
725 return;
726 TII->removeBranch(*this);
727 TII->insertBranch(*this, FBB, nullptr, Cond, DL);
728 } else if (isLayoutSuccessor(FBB)) {
729 TII->removeBranch(*this);
730 TII->insertBranch(*this, TBB, nullptr, Cond, DL);
731 }
732 return;
733 }
734
735 // We now know we're going to fallthrough to PreviousLayoutSuccessor.
736 assert(PreviousLayoutSuccessor);
737 assert(!PreviousLayoutSuccessor->isEHPad());
738 assert(isSuccessor(PreviousLayoutSuccessor));
739
740 if (PreviousLayoutSuccessor == TBB) {
741 // We had a fallthrough to the same basic block as the conditional jump
742 // targets. Remove the conditional jump, leaving an unconditional
743 // fallthrough or an unconditional jump.
744 TII->removeBranch(*this);
745 if (!isLayoutSuccessor(TBB)) {
746 Cond.clear();
747 TII->insertBranch(*this, TBB, nullptr, Cond, DL);
748 }
749 return;
750 }
751
752 // The block has a fallthrough conditional branch.
753 if (isLayoutSuccessor(TBB)) {
755 // We can't reverse the condition, add an unconditional branch.
756 Cond.clear();
757 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
758 return;
759 }
760 TII->removeBranch(*this);
761 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
762 } else if (!isLayoutSuccessor(PreviousLayoutSuccessor)) {
763 TII->removeBranch(*this);
764 TII->insertBranch(*this, TBB, PreviousLayoutSuccessor, Cond, DL);
765 }
766}
767
769#ifndef NDEBUG
770 int64_t Sum = 0;
771 for (auto Prob : Probs)
772 Sum += Prob.getNumerator();
773 // Due to precision issue, we assume that the sum of probabilities is one if
774 // the difference between the sum of their numerators and the denominator is
775 // no greater than the number of successors.
777 Probs.size() &&
778 "The sum of successors's probabilities exceeds one.");
779#endif // NDEBUG
780}
781
783 BranchProbability Prob) {
784 // Probability list is either empty (if successor list isn't empty, this means
785 // disabled optimization) or has the same size as successor list.
786 if (!(Probs.empty() && !Successors.empty()))
787 Probs.push_back(Prob);
788 Successors.push_back(Succ);
789 Succ->addPredecessor(this);
790}
791
793 // We need to make sure probability list is either empty or has the same size
794 // of successor list. When this function is called, we can safely delete all
795 // probability in the list.
796 Probs.clear();
797 Successors.push_back(Succ);
798 Succ->addPredecessor(this);
799}
800
803 bool NormalizeSuccProbs) {
804 succ_iterator OldI = llvm::find(successors(), Old);
805 assert(OldI != succ_end() && "Old is not a successor of this block!");
807 "New is already a successor of this block!");
808
809 // Add a new successor with equal probability as the original one. Note
810 // that we directly copy the probability using the iterator rather than
811 // getting a potentially synthetic probability computed when unknown. This
812 // preserves the probabilities as-is and then we can renormalize them and
813 // query them effectively afterward.
814 addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
815 : *getProbabilityIterator(OldI));
816 if (NormalizeSuccProbs)
818}
819
821 bool NormalizeSuccProbs) {
822 succ_iterator I = find(Successors, Succ);
823 removeSuccessor(I, NormalizeSuccProbs);
824}
825
828 assert(I != Successors.end() && "Not a current successor!");
829
830 // If probability list is empty it means we don't use it (disabled
831 // optimization).
832 if (!Probs.empty()) {
833 probability_iterator WI = getProbabilityIterator(I);
834 Probs.erase(WI);
835 if (NormalizeSuccProbs)
837 }
838
839 (*I)->removePredecessor(this);
840 return Successors.erase(I);
841}
842
844 MachineBasicBlock *New) {
845 if (Old == New)
846 return;
847
849 succ_iterator NewI = E;
850 succ_iterator OldI = E;
851 for (succ_iterator I = succ_begin(); I != E; ++I) {
852 if (*I == Old) {
853 OldI = I;
854 if (NewI != E)
855 break;
856 }
857 if (*I == New) {
858 NewI = I;
859 if (OldI != E)
860 break;
861 }
862 }
863 assert(OldI != E && "Old is not a successor of this block");
864
865 // If New isn't already a successor, let it take Old's place.
866 if (NewI == E) {
867 Old->removePredecessor(this);
868 New->addPredecessor(this);
869 *OldI = New;
870 return;
871 }
872
873 // New is already a successor.
874 // Update its probability instead of adding a duplicate edge.
875 if (!Probs.empty()) {
876 auto ProbIter = getProbabilityIterator(NewI);
877 if (!ProbIter->isUnknown())
878 *ProbIter += *getProbabilityIterator(OldI);
879 }
880 removeSuccessor(OldI);
881}
882
885 if (!Orig->Probs.empty())
887 else
889}
890
891void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
892 Predecessors.push_back(Pred);
893}
894
895void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
896 pred_iterator I = find(Predecessors, Pred);
897 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
898 Predecessors.erase(I);
899}
900
902 if (this == FromMBB)
903 return;
904
905 while (!FromMBB->succ_empty()) {
906 MachineBasicBlock *Succ = *FromMBB->succ_begin();
907
908 // If probability list is empty it means we don't use it (disabled
909 // optimization).
910 if (!FromMBB->Probs.empty()) {
911 auto Prob = *FromMBB->Probs.begin();
912 addSuccessor(Succ, Prob);
913 } else
915
916 FromMBB->removeSuccessor(Succ);
917 }
918}
919
920void
922 if (this == FromMBB)
923 return;
924
925 while (!FromMBB->succ_empty()) {
926 MachineBasicBlock *Succ = *FromMBB->succ_begin();
927 if (!FromMBB->Probs.empty()) {
928 auto Prob = *FromMBB->Probs.begin();
929 addSuccessor(Succ, Prob);
930 } else
932 FromMBB->removeSuccessor(Succ);
933
934 // Fix up any PHI nodes in the successor.
935 Succ->replacePhiUsesWith(FromMBB, this);
936 }
938}
939
941 return is_contained(predecessors(), MBB);
942}
943
945 return is_contained(successors(), MBB);
946}
947
950 return std::next(I) == MachineFunction::const_iterator(MBB);
951}
952
954 return Successors.size() == 1 ? Successors[0] : nullptr;
955}
956
959 ++Fallthrough;
960 // If FallthroughBlock is off the end of the function, it can't fall through.
961 if (Fallthrough == getParent()->end())
962 return nullptr;
963
964 // If FallthroughBlock isn't a successor, no fallthrough is possible.
965 if (!isSuccessor(&*Fallthrough))
966 return nullptr;
967
968 // Analyze the branches, if any, at the end of the block.
969 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
972 if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
973 // If we couldn't analyze the branch, examine the last instruction.
974 // If the block doesn't end in a known control barrier, assume fallthrough
975 // is possible. The isPredicated check is needed because this code can be
976 // called during IfConversion, where an instruction which is normally a
977 // Barrier is predicated and thus no longer an actual control barrier.
978 return (empty() || !back().isBarrier() || TII->isPredicated(back()))
979 ? &*Fallthrough
980 : nullptr;
981 }
982
983 // If there is no branch, control always falls through.
984 if (!TBB) return &*Fallthrough;
985
986 // If there is some explicit branch to the fallthrough block, it can obviously
987 // reach, even though the branch should get folded to fall through implicitly.
988 if (JumpToFallThrough && (MachineFunction::iterator(TBB) == Fallthrough ||
989 MachineFunction::iterator(FBB) == Fallthrough))
990 return &*Fallthrough;
991
992 // If it's an unconditional branch to some block not the fall through, it
993 // doesn't fall through.
994 if (Cond.empty()) return nullptr;
995
996 // Otherwise, if it is conditional and has no explicit false block, it falls
997 // through.
998 return (FBB == nullptr) ? &*Fallthrough : nullptr;
999}
1000
1002 return getFallThrough() != nullptr;
1003}
1004
1006 bool UpdateLiveIns,
1007 LiveIntervals *LIS) {
1008 MachineBasicBlock::iterator SplitPoint(&MI);
1009 ++SplitPoint;
1010
1011 if (SplitPoint == end()) {
1012 // Don't bother with a new block.
1013 return this;
1014 }
1015
1016 MachineFunction *MF = getParent();
1017
1018 LivePhysRegs LiveRegs;
1019 if (UpdateLiveIns) {
1020 // Make sure we add any physregs we define in the block as liveins to the
1021 // new block.
1023 LiveRegs.init(*MF->getSubtarget().getRegisterInfo());
1024 LiveRegs.addLiveOuts(*this);
1025 for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I)
1026 LiveRegs.stepBackward(*I);
1027 }
1028
1030
1031 MF->insert(++MachineFunction::iterator(this), SplitBB);
1032 SplitBB->splice(SplitBB->begin(), this, SplitPoint, end());
1033
1034 SplitBB->transferSuccessorsAndUpdatePHIs(this);
1035 addSuccessor(SplitBB);
1036
1037 if (UpdateLiveIns)
1038 addLiveIns(*SplitBB, LiveRegs);
1039
1040 if (LIS)
1041 LIS->insertMBBInMaps(SplitBB);
1042
1043 return SplitBB;
1044}
1045
1046// Returns `true` if there are possibly other users of the jump table at
1047// `JumpTableIndex` except for the ones in `IgnoreMBB`.
1049 const MachineBasicBlock &IgnoreMBB,
1050 int JumpTableIndex) {
1051 assert(JumpTableIndex >= 0 && "need valid index");
1052 const MachineJumpTableInfo &MJTI = *MF.getJumpTableInfo();
1053 const MachineJumpTableEntry &MJTE = MJTI.getJumpTables()[JumpTableIndex];
1054 // Take any basic block from the table; every user of the jump table must
1055 // show up in the predecessor list.
1056 const MachineBasicBlock *MBB = nullptr;
1057 for (MachineBasicBlock *B : MJTE.MBBs) {
1058 if (B != nullptr) {
1059 MBB = B;
1060 break;
1061 }
1062 }
1063 if (MBB == nullptr)
1064 return true; // can't rule out other users if there isn't any block.
1067 for (MachineBasicBlock *Pred : MBB->predecessors()) {
1068 if (Pred == &IgnoreMBB)
1069 continue;
1070 MachineBasicBlock *DummyT = nullptr;
1071 MachineBasicBlock *DummyF = nullptr;
1072 Cond.clear();
1073 if (!TII.analyzeBranch(*Pred, DummyT, DummyF, Cond,
1074 /*AllowModify=*/false)) {
1075 // analyzable direct jump
1076 continue;
1077 }
1078 int PredJTI = findJumpTableIndex(*Pred);
1079 if (PredJTI >= 0) {
1080 if (PredJTI == JumpTableIndex)
1081 return true;
1082 continue;
1083 }
1084 // Be conservative for unanalyzable jumps.
1085 return true;
1086 }
1087 return false;
1088}
1089
1091 MachineBasicBlock *Succ, Pass &P,
1092 std::vector<SparseBitVector<>> *LiveInSets) {
1093 if (!canSplitCriticalEdge(Succ))
1094 return nullptr;
1095
1096 MachineFunction *MF = getParent();
1097 MachineBasicBlock *PrevFallthrough = getNextNode();
1098 DebugLoc DL; // FIXME: this is nowhere
1099
1101
1102 // Is there an indirect jump with jump table?
1103 bool ChangedIndirectJump = false;
1104 int JTI = findJumpTableIndex(*this);
1105 if (JTI >= 0) {
1107 MJTI.ReplaceMBBInJumpTable(JTI, Succ, NMBB);
1108 ChangedIndirectJump = true;
1109 }
1110
1111 MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
1112 LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
1113 << " -- " << printMBBReference(*NMBB) << " -- "
1114 << printMBBReference(*Succ) << '\n');
1115
1116 LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
1117 SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
1118 if (LIS)
1119 LIS->insertMBBInMaps(NMBB);
1120 else if (Indexes)
1121 Indexes->insertMBBInMaps(NMBB);
1122
1123 // On some targets like Mips, branches may kill virtual registers. Make sure
1124 // that LiveVariables is properly updated after updateTerminator replaces the
1125 // terminators.
1126 LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
1127
1128 // Collect a list of virtual registers killed by the terminators.
1129 SmallVector<Register, 4> KilledRegs;
1130 if (LV)
1131 for (MachineInstr &MI :
1133 for (MachineOperand &MO : MI.all_uses()) {
1134 if (MO.getReg() == 0 || !MO.isKill() || MO.isUndef())
1135 continue;
1136 Register Reg = MO.getReg();
1137 if (Reg.isPhysical() || LV->getVarInfo(Reg).removeKill(MI)) {
1138 KilledRegs.push_back(Reg);
1139 LLVM_DEBUG(dbgs() << "Removing terminator kill: " << MI);
1140 MO.setIsKill(false);
1141 }
1142 }
1143 }
1144
1145 SmallVector<Register, 4> UsedRegs;
1146 if (LIS) {
1147 for (MachineInstr &MI :
1149 for (const MachineOperand &MO : MI.operands()) {
1150 if (!MO.isReg() || MO.getReg() == 0)
1151 continue;
1152
1153 Register Reg = MO.getReg();
1154 if (!is_contained(UsedRegs, Reg))
1155 UsedRegs.push_back(Reg);
1156 }
1157 }
1158 }
1159
1160 ReplaceUsesOfBlockWith(Succ, NMBB);
1161
1162 // If updateTerminator() removes instructions, we need to remove them from
1163 // SlotIndexes.
1165 if (Indexes) {
1166 for (MachineInstr &MI :
1168 Terminators.push_back(&MI);
1169 }
1170
1171 // Since we replaced all uses of Succ with NMBB, that should also be treated
1172 // as the fallthrough successor
1173 if (Succ == PrevFallthrough)
1174 PrevFallthrough = NMBB;
1175
1176 if (!ChangedIndirectJump)
1177 updateTerminator(PrevFallthrough);
1178
1179 if (Indexes) {
1180 SmallVector<MachineInstr*, 4> NewTerminators;
1181 for (MachineInstr &MI :
1183 NewTerminators.push_back(&MI);
1184
1185 for (MachineInstr *Terminator : Terminators) {
1186 if (!is_contained(NewTerminators, Terminator))
1187 Indexes->removeMachineInstrFromMaps(*Terminator);
1188 }
1189 }
1190
1191 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
1192 NMBB->addSuccessor(Succ);
1193 if (!NMBB->isLayoutSuccessor(Succ)) {
1196 TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
1197
1198 if (Indexes) {
1199 for (MachineInstr &MI : NMBB->instrs()) {
1200 // Some instructions may have been moved to NMBB by updateTerminator(),
1201 // so we first remove any instruction that already has an index.
1202 if (Indexes->hasIndex(MI))
1203 Indexes->removeMachineInstrFromMaps(MI);
1204 Indexes->insertMachineInstrInMaps(MI);
1205 }
1206 }
1207 }
1208
1209 // Fix PHI nodes in Succ so they refer to NMBB instead of this.
1210 Succ->replacePhiUsesWith(this, NMBB);
1211
1212 // Inherit live-ins from the successor
1213 for (const auto &LI : Succ->liveins())
1214 NMBB->addLiveIn(LI);
1215
1216 // Update LiveVariables.
1218 if (LV) {
1219 // Restore kills of virtual registers that were killed by the terminators.
1220 while (!KilledRegs.empty()) {
1221 Register Reg = KilledRegs.pop_back_val();
1222 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
1223 if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false))
1224 continue;
1225 if (Reg.isVirtual())
1226 LV->getVarInfo(Reg).Kills.push_back(&*I);
1227 LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
1228 break;
1229 }
1230 }
1231 // Update relevant live-through information.
1232 if (LiveInSets != nullptr)
1233 LV->addNewBlock(NMBB, this, Succ, *LiveInSets);
1234 else
1235 LV->addNewBlock(NMBB, this, Succ);
1236 }
1237
1238 if (LIS) {
1239 // After splitting the edge and updating SlotIndexes, live intervals may be
1240 // in one of two situations, depending on whether this block was the last in
1241 // the function. If the original block was the last in the function, all
1242 // live intervals will end prior to the beginning of the new split block. If
1243 // the original block was not at the end of the function, all live intervals
1244 // will extend to the end of the new split block.
1245
1246 bool isLastMBB =
1247 std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
1248
1249 SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
1250 SlotIndex PrevIndex = StartIndex.getPrevSlot();
1251 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
1252
1253 // Find the registers used from NMBB in PHIs in Succ.
1254 SmallSet<Register, 8> PHISrcRegs;
1256 I = Succ->instr_begin(), E = Succ->instr_end();
1257 I != E && I->isPHI(); ++I) {
1258 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
1259 if (I->getOperand(ni+1).getMBB() == NMBB) {
1260 MachineOperand &MO = I->getOperand(ni);
1261 Register Reg = MO.getReg();
1262 PHISrcRegs.insert(Reg);
1263 if (MO.isUndef())
1264 continue;
1265
1266 LiveInterval &LI = LIS->getInterval(Reg);
1267 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1268 assert(VNI &&
1269 "PHI sources should be live out of their predecessors.");
1270 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1271 }
1272 }
1273 }
1274
1276 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1278 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
1279 continue;
1280
1281 LiveInterval &LI = LIS->getInterval(Reg);
1282 if (!LI.liveAt(PrevIndex))
1283 continue;
1284
1285 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
1286 if (isLiveOut && isLastMBB) {
1287 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1288 assert(VNI && "LiveInterval should have VNInfo where it is live.");
1289 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1290 } else if (!isLiveOut && !isLastMBB) {
1291 LI.removeSegment(StartIndex, EndIndex);
1292 }
1293 }
1294
1295 // Update all intervals for registers whose uses may have been modified by
1296 // updateTerminator().
1297 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
1298 }
1299
1300 if (MachineDominatorTree *MDT =
1301 P.getAnalysisIfAvailable<MachineDominatorTree>())
1302 MDT->recordSplitCriticalEdge(this, Succ, NMBB);
1303
1304 if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
1305 if (MachineLoop *TIL = MLI->getLoopFor(this)) {
1306 // If one or the other blocks were not in a loop, the new block is not
1307 // either, and thus LI doesn't need to be updated.
1308 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
1309 if (TIL == DestLoop) {
1310 // Both in the same loop, the NMBB joins loop.
1311 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1312 } else if (TIL->contains(DestLoop)) {
1313 // Edge from an outer loop to an inner loop. Add to the outer loop.
1314 TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
1315 } else if (DestLoop->contains(TIL)) {
1316 // Edge from an inner loop to an outer loop. Add to the outer loop.
1317 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1318 } else {
1319 // Edge from two loops with no containment relation. Because these
1320 // are natural loops, we know that the destination block must be the
1321 // header of its loop (adding a branch into a loop elsewhere would
1322 // create an irreducible loop).
1323 assert(DestLoop->getHeader() == Succ &&
1324 "Should not create irreducible loops!");
1325 if (MachineLoop *P = DestLoop->getParentLoop())
1326 P->addBasicBlockToLoop(NMBB, MLI->getBase());
1327 }
1328 }
1329 }
1330
1331 return NMBB;
1332}
1333
1335 const MachineBasicBlock *Succ) const {
1336 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1337 // it in this generic function.
1338 if (Succ->isEHPad())
1339 return false;
1340
1341 // Splitting the critical edge to a callbr's indirect block isn't advised.
1342 // Don't do it in this generic function.
1343 if (Succ->isInlineAsmBrIndirectTarget())
1344 return false;
1345
1346 const MachineFunction *MF = getParent();
1347 // Performance might be harmed on HW that implements branching using exec mask
1348 // where both sides of the branches are always executed.
1349 if (MF->getTarget().requiresStructuredCFG())
1350 return false;
1351
1352 // Do we have an Indirect jump with a jumptable that we can rewrite?
1353 int JTI = findJumpTableIndex(*this);
1354 if (JTI >= 0 && !jumpTableHasOtherUses(*MF, *this, JTI))
1355 return true;
1356
1357 // We may need to update this's terminator, but we can't do that if
1358 // analyzeBranch fails.
1360 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1362 // AnalyzeBanch should modify this, since we did not allow modification.
1363 if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
1364 /*AllowModify*/ false))
1365 return false;
1366
1367 // Avoid bugpoint weirdness: A block may end with a conditional branch but
1368 // jumps to the same MBB is either case. We have duplicate CFG edges in that
1369 // case that we can't handle. Since this never happens in properly optimized
1370 // code, just skip those edges.
1371 if (TBB && TBB == FBB) {
1372 LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
1373 << printMBBReference(*this) << '\n');
1374 return false;
1375 }
1376 return true;
1377}
1378
1379/// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1380/// neighboring instructions so the bundle won't be broken by removing MI.
1382 // Removing the first instruction in a bundle.
1383 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1384 MI->unbundleFromSucc();
1385 // Removing the last instruction in a bundle.
1386 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1387 MI->unbundleFromPred();
1388 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1389 // are already fine.
1390}
1391
1395 return Insts.erase(I);
1396}
1397
1400 MI->clearFlag(MachineInstr::BundledPred);
1401 MI->clearFlag(MachineInstr::BundledSucc);
1402 return Insts.remove(MI);
1403}
1404
1407 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1408 "Cannot insert instruction with bundle flags");
1409 // Set the bundle flags when inserting inside a bundle.
1410 if (I != instr_end() && I->isBundledWithPred()) {
1411 MI->setFlag(MachineInstr::BundledPred);
1412 MI->setFlag(MachineInstr::BundledSucc);
1413 }
1414 return Insts.insert(I, MI);
1415}
1416
1417/// This method unlinks 'this' from the containing function, and returns it, but
1418/// does not delete it.
1420 assert(getParent() && "Not embedded in a function!");
1421 getParent()->remove(this);
1422 return this;
1423}
1424
1425/// This method unlinks 'this' from the containing function, and deletes it.
1427 assert(getParent() && "Not embedded in a function!");
1428 getParent()->erase(this);
1429}
1430
1431/// Given a machine basic block that branched to 'Old', change the code and CFG
1432/// so that it branches to 'New' instead.
1434 MachineBasicBlock *New) {
1435 assert(Old != New && "Cannot replace self with self!");
1436
1438 while (I != instr_begin()) {
1439 --I;
1440 if (!I->isTerminator()) break;
1441
1442 // Scan the operands of this machine instruction, replacing any uses of Old
1443 // with New.
1444 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1445 if (I->getOperand(i).isMBB() &&
1446 I->getOperand(i).getMBB() == Old)
1447 I->getOperand(i).setMBB(New);
1448 }
1449
1450 // Update the successor information.
1451 replaceSuccessor(Old, New);
1452}
1453
1455 MachineBasicBlock *New) {
1456 for (MachineInstr &MI : phis())
1457 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
1458 MachineOperand &MO = MI.getOperand(i);
1459 if (MO.getMBB() == Old)
1460 MO.setMBB(New);
1461 }
1462}
1463
1464/// Find the next valid DebugLoc starting at MBBI, skipping any debug
1465/// instructions. Return UnknownLoc if there is none.
1468 // Skip debug declarations, we don't want a DebugLoc from them.
1470 if (MBBI != instr_end())
1471 return MBBI->getDebugLoc();
1472 return {};
1473}
1474
1476 if (MBBI == instr_rend())
1477 return findDebugLoc(instr_begin());
1478 // Skip debug declarations, we don't want a DebugLoc from them.
1480 if (!MBBI->isDebugInstr())
1481 return MBBI->getDebugLoc();
1482 return {};
1483}
1484
1485/// Find the previous valid DebugLoc preceding MBBI, skipping any debug
1486/// instructions. Return UnknownLoc if there is none.
1488 if (MBBI == instr_begin())
1489 return {};
1490 // Skip debug instructions, we don't want a DebugLoc from them.
1492 if (!MBBI->isDebugInstr())
1493 return MBBI->getDebugLoc();
1494 return {};
1495}
1496
1498 if (MBBI == instr_rend())
1499 return {};
1500 // Skip debug declarations, we don't want a DebugLoc from them.
1502 if (MBBI != instr_rend())
1503 return MBBI->getDebugLoc();
1504 return {};
1505}
1506
1507/// Find and return the merged DebugLoc of the branch instructions of the block.
1508/// Return UnknownLoc if there is none.
1511 DebugLoc DL;
1512 auto TI = getFirstTerminator();
1513 while (TI != end() && !TI->isBranch())
1514 ++TI;
1515
1516 if (TI != end()) {
1517 DL = TI->getDebugLoc();
1518 for (++TI ; TI != end() ; ++TI)
1519 if (TI->isBranch())
1520 DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
1521 }
1522 return DL;
1523}
1524
1525/// Return probability of the edge from this block to MBB.
1528 if (Probs.empty())
1529 return BranchProbability(1, succ_size());
1530
1531 const auto &Prob = *getProbabilityIterator(Succ);
1532 if (Prob.isUnknown()) {
1533 // For unknown probabilities, collect the sum of all known ones, and evenly
1534 // ditribute the complemental of the sum to each unknown probability.
1535 unsigned KnownProbNum = 0;
1536 auto Sum = BranchProbability::getZero();
1537 for (const auto &P : Probs) {
1538 if (!P.isUnknown()) {
1539 Sum += P;
1540 KnownProbNum++;
1541 }
1542 }
1543 return Sum.getCompl() / (Probs.size() - KnownProbNum);
1544 } else
1545 return Prob;
1546}
1547
1548/// Set successor probability of a given iterator.
1550 BranchProbability Prob) {
1551 assert(!Prob.isUnknown());
1552 if (Probs.empty())
1553 return;
1554 *getProbabilityIterator(I) = Prob;
1555}
1556
1557/// Return probability iterator corresonding to the I successor iterator
1558MachineBasicBlock::const_probability_iterator
1559MachineBasicBlock::getProbabilityIterator(
1561 assert(Probs.size() == Successors.size() && "Async probability list!");
1562 const size_t index = std::distance(Successors.begin(), I);
1563 assert(index < Probs.size() && "Not a current successor!");
1564 return Probs.begin() + index;
1565}
1566
1567/// Return probability iterator corresonding to the I successor iterator.
1568MachineBasicBlock::probability_iterator
1569MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1570 assert(Probs.size() == Successors.size() && "Async probability list!");
1571 const size_t index = std::distance(Successors.begin(), I);
1572 assert(index < Probs.size() && "Not a current successor!");
1573 return Probs.begin() + index;
1574}
1575
1576/// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1577/// as of just before "MI".
1578///
1579/// Search is localised to a neighborhood of
1580/// Neighborhood instructions before (searching for defs or kills) and N
1581/// instructions after (searching just for defs) MI.
1584 MCRegister Reg, const_iterator Before,
1585 unsigned Neighborhood) const {
1586 unsigned N = Neighborhood;
1587
1588 // Try searching forwards from Before, looking for reads or defs.
1589 const_iterator I(Before);
1590 for (; I != end() && N > 0; ++I) {
1591 if (I->isDebugOrPseudoInstr())
1592 continue;
1593
1594 --N;
1595
1597
1598 // Register is live when we read it here.
1599 if (Info.Read)
1600 return LQR_Live;
1601 // Register is dead if we can fully overwrite or clobber it here.
1602 if (Info.FullyDefined || Info.Clobbered)
1603 return LQR_Dead;
1604 }
1605
1606 // If we reached the end, it is safe to clobber Reg at the end of a block of
1607 // no successor has it live in.
1608 if (I == end()) {
1609 for (MachineBasicBlock *S : successors()) {
1610 for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
1611 if (TRI->regsOverlap(LI.PhysReg, Reg))
1612 return LQR_Live;
1613 }
1614 }
1615
1616 return LQR_Dead;
1617 }
1618
1619
1620 N = Neighborhood;
1621
1622 // Start by searching backwards from Before, looking for kills, reads or defs.
1623 I = const_iterator(Before);
1624 // If this is the first insn in the block, don't search backwards.
1625 if (I != begin()) {
1626 do {
1627 --I;
1628
1629 if (I->isDebugOrPseudoInstr())
1630 continue;
1631
1632 --N;
1633
1635
1636 // Defs happen after uses so they take precedence if both are present.
1637
1638 // Register is dead after a dead def of the full register.
1639 if (Info.DeadDef)
1640 return LQR_Dead;
1641 // Register is (at least partially) live after a def.
1642 if (Info.Defined) {
1643 if (!Info.PartialDeadDef)
1644 return LQR_Live;
1645 // As soon as we saw a partial definition (dead or not),
1646 // we cannot tell if the value is partial live without
1647 // tracking the lanemasks. We are not going to do this,
1648 // so fall back on the remaining of the analysis.
1649 break;
1650 }
1651 // Register is dead after a full kill or clobber and no def.
1652 if (Info.Killed || Info.Clobbered)
1653 return LQR_Dead;
1654 // Register must be live if we read it.
1655 if (Info.Read)
1656 return LQR_Live;
1657
1658 } while (I != begin() && N > 0);
1659 }
1660
1661 // If all the instructions before this in the block are debug instructions,
1662 // skip over them.
1663 while (I != begin() && std::prev(I)->isDebugOrPseudoInstr())
1664 --I;
1665
1666 // Did we get to the start of the block?
1667 if (I == begin()) {
1668 // If so, the register's state is definitely defined by the live-in state.
1670 if (TRI->regsOverlap(LI.PhysReg, Reg))
1671 return LQR_Live;
1672
1673 return LQR_Dead;
1674 }
1675
1676 // At this point we have no idea of the liveness of the register.
1677 return LQR_Unknown;
1678}
1679
1680const uint32_t *
1682 // EH funclet entry does not preserve any registers.
1683 return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1684}
1685
1686const uint32_t *
1688 // If we see a return block with successors, this must be a funclet return,
1689 // which does not preserve any registers. If there are no successors, we don't
1690 // care what kind of return it is, putting a mask after it is a no-op.
1691 return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1692}
1693
1695 LiveIns.clear();
1696}
1697
1699 assert(getParent()->getProperties().hasProperty(
1701 "Liveness information is accurate");
1702 return LiveIns.begin();
1703}
1704
1706 const MachineFunction &MF = *getParent();
1709 "Liveness information is accurate");
1710
1711 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1712 MCPhysReg ExceptionPointer = 0, ExceptionSelector = 0;
1713 if (MF.getFunction().hasPersonalityFn()) {
1714 auto PersonalityFn = MF.getFunction().getPersonalityFn();
1715 ExceptionPointer = TLI.getExceptionPointerRegister(PersonalityFn);
1716 ExceptionSelector = TLI.getExceptionSelectorRegister(PersonalityFn);
1717 }
1718
1719 return liveout_iterator(*this, ExceptionPointer, ExceptionSelector, false);
1720}
1721
1723 unsigned Cntr = 0;
1724 auto R = instructionsWithoutDebug(begin(), end());
1725 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1726 if (++Cntr > Limit)
1727 return true;
1728 }
1729 return false;
1730}
1731
1733 uint8_t BBAddrMapVersion = getParent()->getContext().getBBAddrMapVersion();
1734 return BBAddrMapVersion < 2 ? getNumber() : *getBBID();
1735}
1736
1738const MBBSectionID
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
SmallVector< MachineOperand, 4 > Cond
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-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:492
#define LLVM_DEBUG(X)
Definition: Debug.h:101
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
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
#define P(N)
uint32_t Number
Definition: Profile.cpp:47
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
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 describes how to lower LLVM code to machine code.
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
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
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:813
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1961
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:686
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:50
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:68
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 segment from this 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.
StringRef getPrivateLabelPrefix() const
Definition: MCAsmInfo.h:669
Context object for machine code objects.
Definition: MCContext.h:76
uint8_t getBBAddrMapVersion() const
Definition: MCContext.h:684
const MCAsmInfo * getAsmInfo() const
Definition: MCContext.h:446
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:201
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:24
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...
iterator SkipPHIsLabelsAndDebug(iterator I, bool SkipPseudoOp=true)
Return the first instruction in MBB after I that is not a PHI, label or debug.
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.
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...
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.
std::vector< MachineBasicBlock * >::const_iterator const_succ_iterator
void addSuccessorWithoutProb(MachineBasicBlock *Succ)
Add Succ as a successor of this MachineBasicBlock.
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...
bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
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().
std::optional< unsigned > getBBID() const
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.
unsigned getBBIDOrNumber() const
Returns the BBID of the block when BBAddrMapVersion >= 2, otherwise returns MachineBasicBlock::Number...
std::vector< MachineBasicBlock * >::iterator succ_iterator
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.
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...
MachineBasicBlock * SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P, std::vector< SparseBitVector<> > *LiveInSets=nullptr)
Split the critical edge from this block to the given successor block, and return the newly created bl...
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.
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.
void copySuccessor(MachineBasicBlock *Orig, succ_iterator I)
Copy a successor (and any probability info) from original block to this block's.
bool mayHaveInlineAsmBr() const
Returns true if this block may have an INLINEASM_BR (overestimate, by checking if any of the successo...
void removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Remove the specified register from the live in set.
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
MachineBasicBlock * removeFromParent()
This method unlinks 'this' from the containing function, and returns it, but does not delete it.
Instructions::reverse_iterator reverse_instr_iterator
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool hasProperty(Property P) const
unsigned addToMBBNumbering(MachineBasicBlock *MBB)
Adds the MBB to the internal numbering.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
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.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
void remove(iterator MBBI)
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
void splice(iterator InsertPt, iterator MBBI)
void erase(iterator MBBI)
void insert(iterator MBBI, MachineBasicBlock *MBB)
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:68
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:888
void incorporateFunction(const Function &F)
Incorporate the given function.
Definition: AsmWriter.cpp:874
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
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:82
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
Definition: SlotIndexes.h:294
SlotIndexes pass.
Definition: SlotIndexes.h:319
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
Definition: SlotIndexes.h:390
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
Definition: SlotIndexes.h:471
bool hasIndex(const MachineInstr &instr) const
Returns true if the given machine instr is mapped to an index, otherwise returns false.
Definition: SlotIndexes.h:385
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:166
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:179
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
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
Iterator for intrusive lists based on ilist_node.
MachineBasicBlock * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:289
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:672
#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:445
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:1839
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:1744
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:124
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:292
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:1846
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1976
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.
#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:95
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:90
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