1 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Collect the sequence of machine instructions for a basic block.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/MachineBasicBlock.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/LiveVariables.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SlotIndexes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/ModuleSlotTracker.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
40 #define DEBUG_TYPE "codegen"
42 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
43 : BB(bb), Number(-1), xParent(&mf) {
47 MachineBasicBlock::~MachineBasicBlock() {
50 /// Return the MCSymbol for this basic block.
51 MCSymbol *MachineBasicBlock::getSymbol() const {
52 if (!CachedMCSymbol) {
53 const MachineFunction *MF = getParent();
54 MCContext &Ctx = MF->getContext();
55 const char *Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
56 CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
57 Twine(MF->getFunctionNumber()) +
58 "_" + Twine(getNumber()));
61 return CachedMCSymbol;
65 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
70 /// When an MBB is added to an MF, we need to update the parent pointer of the
71 /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
72 /// operand list for registers.
74 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
75 /// gets the next available unique MBB number. If it is removed from a
76 /// MachineFunction, it goes back to being #-1.
77 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
78 MachineFunction &MF = *N->getParent();
79 N->Number = MF.addToMBBNumbering(N);
81 // Make sure the instructions have their operands in the reginfo lists.
82 MachineRegisterInfo &RegInfo = MF.getRegInfo();
83 for (MachineBasicBlock::instr_iterator
84 I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
85 I->AddRegOperandsToUseLists(RegInfo);
88 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
89 N->getParent()->removeFromMBBNumbering(N->Number);
93 /// When we add an instruction to a basic block list, we update its parent
94 /// pointer and add its operands from reg use/def lists if appropriate.
95 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
96 assert(!N->getParent() && "machine instruction already in a basic block");
99 // Add the instruction's register operands to their corresponding
101 MachineFunction *MF = Parent->getParent();
102 N->AddRegOperandsToUseLists(MF->getRegInfo());
105 /// When we remove an instruction from a basic block list, we update its parent
106 /// pointer and remove its operands from reg use/def lists if appropriate.
107 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
108 assert(N->getParent() && "machine instruction not in a basic block");
110 // Remove from the use/def lists.
111 if (MachineFunction *MF = N->getParent()->getParent())
112 N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
114 N->setParent(nullptr);
117 /// When moving a range of instructions from one MBB list to another, we need to
118 /// update the parent pointers and the use/def lists.
119 void ilist_traits<MachineInstr>::
120 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
121 ilist_iterator<MachineInstr> first,
122 ilist_iterator<MachineInstr> last) {
123 assert(Parent->getParent() == fromList.Parent->getParent() &&
124 "MachineInstr parent mismatch!");
126 // Splice within the same MBB -> no change.
127 if (Parent == fromList.Parent) return;
129 // If splicing between two blocks within the same function, just update the
131 for (; first != last; ++first)
132 first->setParent(Parent);
135 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
136 assert(!MI->getParent() && "MI is still in a block!");
137 Parent->getParent()->DeleteMachineInstr(MI);
140 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
141 instr_iterator I = instr_begin(), E = instr_end();
142 while (I != E && I->isPHI())
144 assert((I == E || !I->isInsideBundle()) &&
145 "First non-phi MI cannot be inside a bundle!");
149 MachineBasicBlock::iterator
150 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
152 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue()))
154 // FIXME: This needs to change if we wish to bundle labels / dbg_values
155 // inside the bundle.
156 assert((I == E || !I->isInsideBundle()) &&
157 "First non-phi / non-label instruction is inside a bundle!");
161 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
162 iterator B = begin(), E = end(), I = E;
163 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
165 while (I != E && !I->isTerminator())
170 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
171 instr_iterator B = instr_begin(), E = instr_end(), I = E;
172 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
174 while (I != E && !I->isTerminator())
179 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() {
180 // Skip over begin-of-block dbg_value instructions.
181 iterator I = begin(), E = end();
182 while (I != E && I->isDebugValue())
187 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
188 // Skip over end-of-block dbg_value instructions.
189 instr_iterator B = instr_begin(), I = instr_end();
192 // Return instruction that starts a bundle.
193 if (I->isDebugValue() || I->isInsideBundle())
197 // The block is all debug values.
201 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
202 // A block with a landing pad successor only has one other successor.
205 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
211 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
212 void MachineBasicBlock::dump() const {
217 StringRef MachineBasicBlock::getName() const {
218 if (const BasicBlock *LBB = getBasicBlock())
219 return LBB->getName();
224 /// Return a hopefully unique identifier for this block.
225 std::string MachineBasicBlock::getFullName() const {
228 Name = (getParent()->getName() + ":").str();
230 Name += getBasicBlock()->getName();
232 Name += ("BB" + Twine(getNumber())).str();
236 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
237 const MachineFunction *MF = getParent();
239 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
243 const Function *F = MF->getFunction();
244 const Module *M = F ? F->getParent() : nullptr;
245 ModuleSlotTracker MST(M);
246 print(OS, MST, Indexes);
249 void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
250 SlotIndexes *Indexes) const {
251 const MachineFunction *MF = getParent();
253 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
259 OS << Indexes->getMBBStartIdx(this) << '\t';
261 OS << "BB#" << getNumber() << ": ";
263 const char *Comma = "";
264 if (const BasicBlock *LBB = getBasicBlock()) {
265 OS << Comma << "derived from LLVM BB ";
266 LBB->printAsOperand(OS, /*PrintType=*/false, MST);
269 if (isEHPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
270 if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
272 OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
277 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
278 if (!livein_empty()) {
279 if (Indexes) OS << '\t';
281 for (const auto &LI : make_range(livein_begin(), livein_end())) {
282 OS << ' ' << PrintReg(LI.PhysReg, TRI);
283 if (LI.LaneMask != ~0u)
284 OS << format(":%08X", LI.LaneMask);
288 // Print the preds of this block according to the CFG.
290 if (Indexes) OS << '\t';
291 OS << " Predecessors according to CFG:";
292 for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
293 OS << " BB#" << (*PI)->getNumber();
297 for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
299 if (Indexes->hasIndex(I))
300 OS << Indexes->getInstructionIndex(I);
304 if (I->isInsideBundle())
309 // Print the successors of this block according to the CFG.
311 if (Indexes) OS << '\t';
312 OS << " Successors according to CFG:";
313 for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
314 OS << " BB#" << (*SI)->getNumber();
315 if (!Weights.empty())
316 OS << '(' << *getWeightIterator(SI) << ')';
322 void MachineBasicBlock::printAsOperand(raw_ostream &OS,
323 bool /*PrintType*/) const {
324 OS << "BB#" << getNumber();
327 void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, unsigned LaneMask) {
328 LiveInVector::iterator I = std::find_if(
329 LiveIns.begin(), LiveIns.end(),
330 [Reg] (const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
331 if (I == LiveIns.end())
334 I->LaneMask &= ~LaneMask;
335 if (I->LaneMask == 0)
339 bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, unsigned LaneMask) const {
340 livein_iterator I = std::find_if(
341 LiveIns.begin(), LiveIns.end(),
342 [Reg] (const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
343 return I != livein_end() && (I->LaneMask & LaneMask) != 0;
346 void MachineBasicBlock::sortUniqueLiveIns() {
347 std::sort(LiveIns.begin(), LiveIns.end(),
348 [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
349 return LI0.PhysReg < LI1.PhysReg;
351 // Liveins are sorted by physreg now we can merge their lanemasks.
352 LiveInVector::const_iterator I = LiveIns.begin();
353 LiveInVector::const_iterator J;
354 LiveInVector::iterator Out = LiveIns.begin();
355 for (; I != LiveIns.end(); ++Out, I = J) {
356 unsigned PhysReg = I->PhysReg;
357 unsigned LaneMask = I->LaneMask;
358 for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
359 LaneMask |= J->LaneMask;
360 Out->PhysReg = PhysReg;
361 Out->LaneMask = LaneMask;
363 LiveIns.erase(Out, LiveIns.end());
367 MachineBasicBlock::addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC) {
368 assert(getParent() && "MBB must be inserted in function");
369 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
370 assert(RC && "Register class is required");
371 assert((isEHPad() || this == &getParent()->front()) &&
372 "Only the entry block and landing pads can have physreg live ins");
374 bool LiveIn = isLiveIn(PhysReg);
375 iterator I = SkipPHIsAndLabels(begin()), E = end();
376 MachineRegisterInfo &MRI = getParent()->getRegInfo();
377 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
379 // Look for an existing copy.
381 for (;I != E && I->isCopy(); ++I)
382 if (I->getOperand(1).getReg() == PhysReg) {
383 unsigned VirtReg = I->getOperand(0).getReg();
384 if (!MRI.constrainRegClass(VirtReg, RC))
385 llvm_unreachable("Incompatible live-in register class.");
389 // No luck, create a virtual register.
390 unsigned VirtReg = MRI.createVirtualRegister(RC);
391 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
392 .addReg(PhysReg, RegState::Kill);
398 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
399 getParent()->splice(NewAfter, this);
402 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
403 MachineFunction::iterator BBI = NewBefore;
404 getParent()->splice(++BBI, this);
407 void MachineBasicBlock::updateTerminator() {
408 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
409 // A block with no successors has no concerns with fall-through edges.
410 if (this->succ_empty()) return;
412 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
413 SmallVector<MachineOperand, 4> Cond;
414 DebugLoc dl; // FIXME: this is nowhere
415 bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
417 assert(!B && "UpdateTerminators requires analyzable predecessors!");
420 // The block has an unconditional branch. If its successor is now
421 // its layout successor, delete the branch.
422 if (isLayoutSuccessor(TBB))
423 TII->RemoveBranch(*this);
425 // The block has an unconditional fallthrough. If its successor is not
426 // its layout successor, insert a branch. First we have to locate the
427 // only non-landing-pad successor, as that is the fallthrough block.
428 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
429 if ((*SI)->isEHPad())
431 assert(!TBB && "Found more than one non-landing-pad successor!");
435 // If there is no non-landing-pad successor, the block has no
436 // fall-through edges to be concerned with.
440 // Finally update the unconditional successor to be reached via a branch
441 // if it would not be reached by fallthrough.
442 if (!isLayoutSuccessor(TBB))
443 TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
447 // The block has a non-fallthrough conditional branch. If one of its
448 // successors is its layout successor, rewrite it to a fallthrough
449 // conditional branch.
450 if (isLayoutSuccessor(TBB)) {
451 if (TII->ReverseBranchCondition(Cond))
453 TII->RemoveBranch(*this);
454 TII->InsertBranch(*this, FBB, nullptr, Cond, dl);
455 } else if (isLayoutSuccessor(FBB)) {
456 TII->RemoveBranch(*this);
457 TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
460 // Walk through the successors and find the successor which is not
461 // a landing pad and is not the conditional branch destination (in TBB)
462 // as the fallthrough successor.
463 MachineBasicBlock *FallthroughBB = nullptr;
464 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
465 if ((*SI)->isEHPad() || *SI == TBB)
467 assert(!FallthroughBB && "Found more than one fallthrough successor.");
470 if (!FallthroughBB && canFallThrough()) {
471 // We fallthrough to the same basic block as the conditional jump
472 // targets. Remove the conditional jump, leaving unconditional
474 // FIXME: This does not seem like a reasonable pattern to support, but
475 // it has been seen in the wild coming out of degenerate ARM test cases.
476 TII->RemoveBranch(*this);
478 // Finally update the unconditional successor to be reached via a branch
479 // if it would not be reached by fallthrough.
480 if (!isLayoutSuccessor(TBB))
481 TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
485 // The block has a fallthrough conditional branch.
486 if (isLayoutSuccessor(TBB)) {
487 if (TII->ReverseBranchCondition(Cond)) {
488 // We can't reverse the condition, add an unconditional branch.
490 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
493 TII->RemoveBranch(*this);
494 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
495 } else if (!isLayoutSuccessor(FallthroughBB)) {
496 TII->RemoveBranch(*this);
497 TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
503 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
505 // If we see non-zero value for the first time it means we actually use Weight
506 // list, so we fill all Weights with 0's.
507 if (weight != 0 && Weights.empty())
508 Weights.resize(Successors.size());
510 if (weight != 0 || !Weights.empty())
511 Weights.push_back(weight);
513 Successors.push_back(succ);
514 succ->addPredecessor(this);
517 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
518 succ->removePredecessor(this);
519 succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
520 assert(I != Successors.end() && "Not a current successor!");
522 // If Weight list is empty it means we don't use it (disabled optimization).
523 if (!Weights.empty()) {
524 weight_iterator WI = getWeightIterator(I);
531 MachineBasicBlock::succ_iterator
532 MachineBasicBlock::removeSuccessor(succ_iterator I) {
533 assert(I != Successors.end() && "Not a current successor!");
535 // If Weight list is empty it means we don't use it (disabled optimization).
536 if (!Weights.empty()) {
537 weight_iterator WI = getWeightIterator(I);
541 (*I)->removePredecessor(this);
542 return Successors.erase(I);
545 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
546 MachineBasicBlock *New) {
550 succ_iterator E = succ_end();
551 succ_iterator NewI = E;
552 succ_iterator OldI = E;
553 for (succ_iterator I = succ_begin(); I != E; ++I) {
565 assert(OldI != E && "Old is not a successor of this block");
566 Old->removePredecessor(this);
568 // If New isn't already a successor, let it take Old's place.
570 New->addPredecessor(this);
575 // New is already a successor.
576 // Update its weight instead of adding a duplicate edge.
577 if (!Weights.empty()) {
578 weight_iterator OldWI = getWeightIterator(OldI);
579 *getWeightIterator(NewI) += *OldWI;
580 Weights.erase(OldWI);
582 Successors.erase(OldI);
585 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
586 Predecessors.push_back(pred);
589 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
590 pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
591 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
592 Predecessors.erase(I);
595 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
599 while (!fromMBB->succ_empty()) {
600 MachineBasicBlock *Succ = *fromMBB->succ_begin();
603 // If Weight list is empty it means we don't use it (disabled optimization).
604 if (!fromMBB->Weights.empty())
605 Weight = *fromMBB->Weights.begin();
607 addSuccessor(Succ, Weight);
608 fromMBB->removeSuccessor(Succ);
613 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
617 while (!fromMBB->succ_empty()) {
618 MachineBasicBlock *Succ = *fromMBB->succ_begin();
620 if (!fromMBB->Weights.empty())
621 Weight = *fromMBB->Weights.begin();
622 addSuccessor(Succ, Weight);
623 fromMBB->removeSuccessor(Succ);
625 // Fix up any PHI nodes in the successor.
626 for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
627 ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
628 for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
629 MachineOperand &MO = MI->getOperand(i);
630 if (MO.getMBB() == fromMBB)
636 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
637 return std::find(pred_begin(), pred_end(), MBB) != pred_end();
640 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
641 return std::find(succ_begin(), succ_end(), MBB) != succ_end();
644 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
645 MachineFunction::const_iterator I(this);
646 return std::next(I) == MachineFunction::const_iterator(MBB);
649 bool MachineBasicBlock::canFallThrough() {
650 MachineFunction::iterator Fallthrough = this;
652 // If FallthroughBlock is off the end of the function, it can't fall through.
653 if (Fallthrough == getParent()->end())
656 // If FallthroughBlock isn't a successor, no fallthrough is possible.
657 if (!isSuccessor(Fallthrough))
660 // Analyze the branches, if any, at the end of the block.
661 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
662 SmallVector<MachineOperand, 4> Cond;
663 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
664 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
665 // If we couldn't analyze the branch, examine the last instruction.
666 // If the block doesn't end in a known control barrier, assume fallthrough
667 // is possible. The isPredicated check is needed because this code can be
668 // called during IfConversion, where an instruction which is normally a
669 // Barrier is predicated and thus no longer an actual control barrier.
670 return empty() || !back().isBarrier() || TII->isPredicated(&back());
673 // If there is no branch, control always falls through.
674 if (!TBB) return true;
676 // If there is some explicit branch to the fallthrough block, it can obviously
677 // reach, even though the branch should get folded to fall through implicitly.
678 if (MachineFunction::iterator(TBB) == Fallthrough ||
679 MachineFunction::iterator(FBB) == Fallthrough)
682 // If it's an unconditional branch to some block not the fall through, it
683 // doesn't fall through.
684 if (Cond.empty()) return false;
686 // Otherwise, if it is conditional and has no explicit false block, it falls
688 return FBB == nullptr;
692 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
693 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
694 // it in this generic function.
698 MachineFunction *MF = getParent();
699 DebugLoc dl; // FIXME: this is nowhere
701 // Performance might be harmed on HW that implements branching using exec mask
702 // where both sides of the branches are always executed.
703 if (MF->getTarget().requiresStructuredCFG())
706 // We may need to update this's terminator, but we can't do that if
707 // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
708 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
709 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
710 SmallVector<MachineOperand, 4> Cond;
711 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
714 // Avoid bugpoint weirdness: A block may end with a conditional branch but
715 // jumps to the same MBB is either case. We have duplicate CFG edges in that
716 // case that we can't handle. Since this never happens in properly optimized
717 // code, just skip those edges.
718 if (TBB && TBB == FBB) {
719 DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
720 << getNumber() << '\n');
724 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
725 MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
726 DEBUG(dbgs() << "Splitting critical edge:"
727 " BB#" << getNumber()
728 << " -- BB#" << NMBB->getNumber()
729 << " -- BB#" << Succ->getNumber() << '\n');
731 LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
732 SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
734 LIS->insertMBBInMaps(NMBB);
736 Indexes->insertMBBInMaps(NMBB);
738 // On some targets like Mips, branches may kill virtual registers. Make sure
739 // that LiveVariables is properly updated after updateTerminator replaces the
741 LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
743 // Collect a list of virtual registers killed by the terminators.
744 SmallVector<unsigned, 4> KilledRegs;
746 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
748 MachineInstr *MI = I;
749 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
750 OE = MI->operands_end(); OI != OE; ++OI) {
751 if (!OI->isReg() || OI->getReg() == 0 ||
752 !OI->isUse() || !OI->isKill() || OI->isUndef())
754 unsigned Reg = OI->getReg();
755 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
756 LV->getVarInfo(Reg).removeKill(MI)) {
757 KilledRegs.push_back(Reg);
758 DEBUG(dbgs() << "Removing terminator kill: " << *MI);
759 OI->setIsKill(false);
764 SmallVector<unsigned, 4> UsedRegs;
766 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
768 MachineInstr *MI = I;
770 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
771 OE = MI->operands_end(); OI != OE; ++OI) {
772 if (!OI->isReg() || OI->getReg() == 0)
775 unsigned Reg = OI->getReg();
776 if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
777 UsedRegs.push_back(Reg);
782 ReplaceUsesOfBlockWith(Succ, NMBB);
784 // If updateTerminator() removes instructions, we need to remove them from
786 SmallVector<MachineInstr*, 4> Terminators;
788 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
790 Terminators.push_back(I);
796 SmallVector<MachineInstr*, 4> NewTerminators;
797 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
799 NewTerminators.push_back(I);
801 for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
802 E = Terminators.end(); I != E; ++I) {
803 if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
804 NewTerminators.end())
805 Indexes->removeMachineInstrFromMaps(*I);
809 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
810 NMBB->addSuccessor(Succ);
811 if (!NMBB->isLayoutSuccessor(Succ)) {
813 MF->getSubtarget().getInstrInfo()->InsertBranch(*NMBB, Succ, nullptr, Cond,
817 for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
819 // Some instructions may have been moved to NMBB by updateTerminator(),
820 // so we first remove any instruction that already has an index.
821 if (Indexes->hasIndex(I))
822 Indexes->removeMachineInstrFromMaps(I);
823 Indexes->insertMachineInstrInMaps(I);
828 // Fix PHI nodes in Succ so they refer to NMBB instead of this
829 for (MachineBasicBlock::instr_iterator
830 i = Succ->instr_begin(),e = Succ->instr_end();
831 i != e && i->isPHI(); ++i)
832 for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
833 if (i->getOperand(ni+1).getMBB() == this)
834 i->getOperand(ni+1).setMBB(NMBB);
836 // Inherit live-ins from the successor
837 for (const auto &LI : Succ->liveins())
840 // Update LiveVariables.
841 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
843 // Restore kills of virtual registers that were killed by the terminators.
844 while (!KilledRegs.empty()) {
845 unsigned Reg = KilledRegs.pop_back_val();
846 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
847 if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
849 if (TargetRegisterInfo::isVirtualRegister(Reg))
850 LV->getVarInfo(Reg).Kills.push_back(I);
851 DEBUG(dbgs() << "Restored terminator kill: " << *I);
855 // Update relevant live-through information.
856 LV->addNewBlock(NMBB, this, Succ);
860 // After splitting the edge and updating SlotIndexes, live intervals may be
861 // in one of two situations, depending on whether this block was the last in
862 // the function. If the original block was the last in the function, all
863 // live intervals will end prior to the beginning of the new split block. If
864 // the original block was not at the end of the function, all live intervals
865 // will extend to the end of the new split block.
868 std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
870 SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
871 SlotIndex PrevIndex = StartIndex.getPrevSlot();
872 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
874 // Find the registers used from NMBB in PHIs in Succ.
875 SmallSet<unsigned, 8> PHISrcRegs;
876 for (MachineBasicBlock::instr_iterator
877 I = Succ->instr_begin(), E = Succ->instr_end();
878 I != E && I->isPHI(); ++I) {
879 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
880 if (I->getOperand(ni+1).getMBB() == NMBB) {
881 MachineOperand &MO = I->getOperand(ni);
882 unsigned Reg = MO.getReg();
883 PHISrcRegs.insert(Reg);
887 LiveInterval &LI = LIS->getInterval(Reg);
888 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
890 "PHI sources should be live out of their predecessors.");
891 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
896 MachineRegisterInfo *MRI = &getParent()->getRegInfo();
897 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
898 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
899 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
902 LiveInterval &LI = LIS->getInterval(Reg);
903 if (!LI.liveAt(PrevIndex))
906 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
907 if (isLiveOut && isLastMBB) {
908 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
909 assert(VNI && "LiveInterval should have VNInfo where it is live.");
910 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
911 } else if (!isLiveOut && !isLastMBB) {
912 LI.removeSegment(StartIndex, EndIndex);
916 // Update all intervals for registers whose uses may have been modified by
917 // updateTerminator().
918 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
921 if (MachineDominatorTree *MDT =
922 P->getAnalysisIfAvailable<MachineDominatorTree>())
923 MDT->recordSplitCriticalEdge(this, Succ, NMBB);
925 if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
926 if (MachineLoop *TIL = MLI->getLoopFor(this)) {
927 // If one or the other blocks were not in a loop, the new block is not
928 // either, and thus LI doesn't need to be updated.
929 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
930 if (TIL == DestLoop) {
931 // Both in the same loop, the NMBB joins loop.
932 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
933 } else if (TIL->contains(DestLoop)) {
934 // Edge from an outer loop to an inner loop. Add to the outer loop.
935 TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
936 } else if (DestLoop->contains(TIL)) {
937 // Edge from an inner loop to an outer loop. Add to the outer loop.
938 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
940 // Edge from two loops with no containment relation. Because these
941 // are natural loops, we know that the destination block must be the
942 // header of its loop (adding a branch into a loop elsewhere would
943 // create an irreducible loop).
944 assert(DestLoop->getHeader() == Succ &&
945 "Should not create irreducible loops!");
946 if (MachineLoop *P = DestLoop->getParentLoop())
947 P->addBasicBlockToLoop(NMBB, MLI->getBase());
955 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
956 /// neighboring instructions so the bundle won't be broken by removing MI.
957 static void unbundleSingleMI(MachineInstr *MI) {
958 // Removing the first instruction in a bundle.
959 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
960 MI->unbundleFromSucc();
961 // Removing the last instruction in a bundle.
962 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
963 MI->unbundleFromPred();
964 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
968 MachineBasicBlock::instr_iterator
969 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
971 return Insts.erase(I);
974 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
975 unbundleSingleMI(MI);
976 MI->clearFlag(MachineInstr::BundledPred);
977 MI->clearFlag(MachineInstr::BundledSucc);
978 return Insts.remove(MI);
981 MachineBasicBlock::instr_iterator
982 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
983 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
984 "Cannot insert instruction with bundle flags");
985 // Set the bundle flags when inserting inside a bundle.
986 if (I != instr_end() && I->isBundledWithPred()) {
987 MI->setFlag(MachineInstr::BundledPred);
988 MI->setFlag(MachineInstr::BundledSucc);
990 return Insts.insert(I, MI);
993 /// This method unlinks 'this' from the containing function, and returns it, but
994 /// does not delete it.
995 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
996 assert(getParent() && "Not embedded in a function!");
997 getParent()->remove(this);
1001 /// This method unlinks 'this' from the containing function, and deletes it.
1002 void MachineBasicBlock::eraseFromParent() {
1003 assert(getParent() && "Not embedded in a function!");
1004 getParent()->erase(this);
1007 /// Given a machine basic block that branched to 'Old', change the code and CFG
1008 /// so that it branches to 'New' instead.
1009 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1010 MachineBasicBlock *New) {
1011 assert(Old != New && "Cannot replace self with self!");
1013 MachineBasicBlock::instr_iterator I = instr_end();
1014 while (I != instr_begin()) {
1016 if (!I->isTerminator()) break;
1018 // Scan the operands of this machine instruction, replacing any uses of Old
1020 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1021 if (I->getOperand(i).isMBB() &&
1022 I->getOperand(i).getMBB() == Old)
1023 I->getOperand(i).setMBB(New);
1026 // Update the successor information.
1027 replaceSuccessor(Old, New);
1030 /// Various pieces of code can cause excess edges in the CFG to be inserted. If
1031 /// we have proven that MBB can only branch to DestA and DestB, remove any other
1032 /// MBB successors from the CFG. DestA and DestB can be null.
1034 /// Besides DestA and DestB, retain other edges leading to LandingPads
1035 /// (currently there can be only one; we don't check or require that here).
1036 /// Note it is possible that DestA and/or DestB are LandingPads.
1037 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1038 MachineBasicBlock *DestB,
1040 // The values of DestA and DestB frequently come from a call to the
1041 // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1042 // values from there.
1044 // 1. If both DestA and DestB are null, then the block ends with no branches
1045 // (it falls through to its successor).
1046 // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
1047 // with only an unconditional branch.
1048 // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
1049 // with a conditional branch that falls through to a successor (DestB).
1050 // 4. If DestA and DestB is set and isCond is true, then the block ends with a
1051 // conditional branch followed by an unconditional branch. DestA is the
1052 // 'true' destination and DestB is the 'false' destination.
1054 bool Changed = false;
1056 MachineFunction::iterator FallThru =
1057 std::next(MachineFunction::iterator(this));
1059 if (!DestA && !DestB) {
1060 // Block falls through to successor.
1063 } else if (DestA && !DestB) {
1065 // Block ends in conditional jump that falls through to successor.
1068 assert(DestA && DestB && isCond &&
1069 "CFG in a bad state. Cannot correct CFG edges");
1072 // Remove superfluous edges. I.e., those which aren't destinations of this
1073 // basic block, duplicate edges, or landing pads.
1074 SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1075 MachineBasicBlock::succ_iterator SI = succ_begin();
1076 while (SI != succ_end()) {
1077 const MachineBasicBlock *MBB = *SI;
1078 if (!SeenMBBs.insert(MBB).second ||
1079 (MBB != DestA && MBB != DestB && !MBB->isEHPad())) {
1080 // This is a superfluous edge, remove it.
1081 SI = removeSuccessor(SI);
1091 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
1092 /// instructions. Return UnknownLoc if there is none.
1094 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1096 instr_iterator E = instr_end();
1100 // Skip debug declarations, we don't want a DebugLoc from them.
1101 while (MBBI != E && MBBI->isDebugValue())
1104 DL = MBBI->getDebugLoc();
1108 /// Return weight of the edge from this block to MBB.
1109 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
1110 if (Weights.empty())
1113 return *getWeightIterator(Succ);
1116 /// Set successor weight of a given iterator.
1117 void MachineBasicBlock::setSuccWeight(succ_iterator I, uint32_t weight) {
1118 if (Weights.empty())
1120 *getWeightIterator(I) = weight;
1123 /// Return wight iterator corresonding to the I successor iterator.
1124 MachineBasicBlock::weight_iterator MachineBasicBlock::
1125 getWeightIterator(MachineBasicBlock::succ_iterator I) {
1126 assert(Weights.size() == Successors.size() && "Async weight list!");
1127 size_t index = std::distance(Successors.begin(), I);
1128 assert(index < Weights.size() && "Not a current successor!");
1129 return Weights.begin() + index;
1132 /// Return wight iterator corresonding to the I successor iterator.
1133 MachineBasicBlock::const_weight_iterator MachineBasicBlock::
1134 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
1135 assert(Weights.size() == Successors.size() && "Async weight list!");
1136 const size_t index = std::distance(Successors.begin(), I);
1137 assert(index < Weights.size() && "Not a current successor!");
1138 return Weights.begin() + index;
1141 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1142 /// as of just before "MI".
1144 /// Search is localised to a neighborhood of
1145 /// Neighborhood instructions before (searching for defs or kills) and N
1146 /// instructions after (searching just for defs) MI.
1147 MachineBasicBlock::LivenessQueryResult
1148 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1149 unsigned Reg, const_iterator Before,
1150 unsigned Neighborhood) const {
1151 unsigned N = Neighborhood;
1153 // Start by searching backwards from Before, looking for kills, reads or defs.
1154 const_iterator I(Before);
1155 // If this is the first insn in the block, don't search backwards.
1160 MachineOperandIteratorBase::PhysRegInfo Analysis =
1161 ConstMIOperands(I).analyzePhysReg(Reg, TRI);
1163 if (Analysis.Defines)
1164 // Outputs happen after inputs so they take precedence if both are
1166 return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
1168 if (Analysis.Kills || Analysis.Clobbers)
1169 // Register killed, so isn't live.
1172 else if (Analysis.ReadsOverlap)
1173 // Defined or read without a previous kill - live.
1174 return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
1176 } while (I != begin() && --N > 0);
1179 // Did we get to the start of the block?
1181 // If so, the register's state is definitely defined by the live-in state.
1182 for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
1183 RAI.isValid(); ++RAI) {
1185 return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
1193 // Try searching forwards from Before, looking for reads or defs.
1194 I = const_iterator(Before);
1195 // If this is the last insn in the block, don't search forwards.
1197 for (++I; I != end() && N > 0; ++I, --N) {
1198 MachineOperandIteratorBase::PhysRegInfo Analysis =
1199 ConstMIOperands(I).analyzePhysReg(Reg, TRI);
1201 if (Analysis.ReadsOverlap)
1202 // Used, therefore must have been live.
1203 return (Analysis.Reads) ?
1204 LQR_Live : LQR_OverlappingLive;
1206 else if (Analysis.Clobbers || Analysis.Defines)
1207 // Defined (but not read) therefore cannot have been live.
1212 // At this point we have no idea of the liveness of the register.