1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
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 // This pass forwards branches to unconditional branches to make them branch
11 // directly to the target block. This pass often results in dead MBB's, which
14 // Note that this pass must be run after register allocation, it cannot handle
15 // SSA form. It also must handle virtual registers for targets that emit virtual
18 //===----------------------------------------------------------------------===//
20 #include "BranchFolding.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
26 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/CodeGen/TargetPassConfig.h"
35 #include "llvm/IR/DebugInfoMetadata.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
47 #define DEBUG_TYPE "branch-folder"
49 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
50 STATISTIC(NumBranchOpts, "Number of branches optimized");
51 STATISTIC(NumTailMerge , "Number of block tails merged");
52 STATISTIC(NumHoist , "Number of times common instructions are hoisted");
53 STATISTIC(NumTailCalls, "Number of tail calls optimized");
55 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
56 cl::init(cl::BOU_UNSET), cl::Hidden);
58 // Throttle for huge numbers of predecessors (compile speed problems)
59 static cl::opt<unsigned>
60 TailMergeThreshold("tail-merge-threshold",
61 cl::desc("Max number of predecessors to consider tail merging"),
62 cl::init(150), cl::Hidden);
64 // Heuristic for tail merging (and, inversely, tail duplication).
65 // TODO: This should be replaced with a target query.
66 static cl::opt<unsigned>
67 TailMergeSize("tail-merge-size",
68 cl::desc("Min number of instructions to consider tail merging"),
69 cl::init(3), cl::Hidden);
72 /// BranchFolderPass - Wrap branch folder in a machine function pass.
73 class BranchFolderPass : public MachineFunctionPass {
76 explicit BranchFolderPass(): MachineFunctionPass(ID) {}
78 bool runOnMachineFunction(MachineFunction &MF) override;
80 void getAnalysisUsage(AnalysisUsage &AU) const override {
81 AU.addRequired<MachineBlockFrequencyInfo>();
82 AU.addRequired<MachineBranchProbabilityInfo>();
83 AU.addRequired<TargetPassConfig>();
84 MachineFunctionPass::getAnalysisUsage(AU);
89 char BranchFolderPass::ID = 0;
90 char &llvm::BranchFolderPassID = BranchFolderPass::ID;
92 INITIALIZE_PASS(BranchFolderPass, DEBUG_TYPE,
93 "Control Flow Optimizer", false, false)
95 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
96 if (skipFunction(*MF.getFunction()))
99 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
100 // TailMerge can create jump into if branches that make CFG irreducible for
101 // HW that requires structurized CFG.
102 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
103 PassConfig->getEnableTailMerge();
104 BranchFolder::MBFIWrapper MBBFreqInfo(
105 getAnalysis<MachineBlockFrequencyInfo>());
106 BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo,
107 getAnalysis<MachineBranchProbabilityInfo>());
108 return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
109 MF.getSubtarget().getRegisterInfo(),
110 getAnalysisIfAvailable<MachineModuleInfo>());
113 BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist,
114 MBFIWrapper &FreqInfo,
115 const MachineBranchProbabilityInfo &ProbInfo,
116 unsigned MinTailLength)
117 : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength),
118 MBBFreqInfo(FreqInfo), MBPI(ProbInfo) {
119 if (MinCommonTailLength == 0)
120 MinCommonTailLength = TailMergeSize;
121 switch (FlagEnableTailMerge) {
122 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
123 case cl::BOU_TRUE: EnableTailMerge = true; break;
124 case cl::BOU_FALSE: EnableTailMerge = false; break;
128 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
129 assert(MBB->pred_empty() && "MBB must be dead!");
130 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
132 MachineFunction *MF = MBB->getParent();
133 // drop all successors.
134 while (!MBB->succ_empty())
135 MBB->removeSuccessor(MBB->succ_end()-1);
137 // Avoid matching if this pointer gets reused.
138 TriedMerging.erase(MBB);
142 FuncletMembership.erase(MBB);
144 MLI->removeBlock(MBB);
147 bool BranchFolder::OptimizeFunction(MachineFunction &MF,
148 const TargetInstrInfo *tii,
149 const TargetRegisterInfo *tri,
150 MachineModuleInfo *mmi,
151 MachineLoopInfo *mli, bool AfterPlacement) {
152 if (!tii) return false;
154 TriedMerging.clear();
156 MachineRegisterInfo &MRI = MF.getRegInfo();
157 AfterBlockPlacement = AfterPlacement;
164 UpdateLiveIns = MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF);
166 MRI.invalidateLiveness();
168 // Fix CFG. The later algorithms expect it to be right.
169 bool MadeChange = false;
170 for (MachineBasicBlock &MBB : MF) {
171 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
172 SmallVector<MachineOperand, 4> Cond;
173 if (!TII->analyzeBranch(MBB, TBB, FBB, Cond, true))
174 MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
177 // Recalculate funclet membership.
178 FuncletMembership = getFuncletMembership(MF);
180 bool MadeChangeThisIteration = true;
181 while (MadeChangeThisIteration) {
182 MadeChangeThisIteration = TailMergeBlocks(MF);
183 // No need to clean up if tail merging does not change anything after the
185 if (!AfterBlockPlacement || MadeChangeThisIteration)
186 MadeChangeThisIteration |= OptimizeBranches(MF);
187 if (EnableHoistCommonCode)
188 MadeChangeThisIteration |= HoistCommonCode(MF);
189 MadeChange |= MadeChangeThisIteration;
192 // See if any jump tables have become dead as the code generator
194 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
198 // Walk the function to find jump tables that are live.
199 BitVector JTIsLive(JTI->getJumpTables().size());
200 for (const MachineBasicBlock &BB : MF) {
201 for (const MachineInstr &I : BB)
202 for (const MachineOperand &Op : I.operands()) {
203 if (!Op.isJTI()) continue;
205 // Remember that this JT is live.
206 JTIsLive.set(Op.getIndex());
210 // Finally, remove dead jump tables. This happens when the
211 // indirect jump was unreachable (and thus deleted).
212 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
213 if (!JTIsLive.test(i)) {
214 JTI->RemoveJumpTable(i);
221 //===----------------------------------------------------------------------===//
222 // Tail Merging of Blocks
223 //===----------------------------------------------------------------------===//
225 /// HashMachineInstr - Compute a hash value for MI and its operands.
226 static unsigned HashMachineInstr(const MachineInstr &MI) {
227 unsigned Hash = MI.getOpcode();
228 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
229 const MachineOperand &Op = MI.getOperand(i);
231 // Merge in bits from the operand if easy. We can't use MachineOperand's
232 // hash_code here because it's not deterministic and we sort by hash value
234 unsigned OperandHash = 0;
235 switch (Op.getType()) {
236 case MachineOperand::MO_Register:
237 OperandHash = Op.getReg();
239 case MachineOperand::MO_Immediate:
240 OperandHash = Op.getImm();
242 case MachineOperand::MO_MachineBasicBlock:
243 OperandHash = Op.getMBB()->getNumber();
245 case MachineOperand::MO_FrameIndex:
246 case MachineOperand::MO_ConstantPoolIndex:
247 case MachineOperand::MO_JumpTableIndex:
248 OperandHash = Op.getIndex();
250 case MachineOperand::MO_GlobalAddress:
251 case MachineOperand::MO_ExternalSymbol:
252 // Global address / external symbol are too hard, don't bother, but do
253 // pull in the offset.
254 OperandHash = Op.getOffset();
260 Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);
265 /// HashEndOfMBB - Hash the last instruction in the MBB.
266 static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) {
267 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
271 return HashMachineInstr(*I);
274 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
275 /// of instructions they actually have in common together at their end. Return
276 /// iterators for the first shared instruction in each block.
277 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
278 MachineBasicBlock *MBB2,
279 MachineBasicBlock::iterator &I1,
280 MachineBasicBlock::iterator &I2) {
284 unsigned TailLen = 0;
285 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
287 // Skip debugging pseudos; necessary to avoid changing the code.
288 while (I1->isDebugValue()) {
289 if (I1==MBB1->begin()) {
290 while (I2->isDebugValue()) {
291 if (I2==MBB2->begin())
292 // I1==DBG at begin; I2==DBG at begin
297 // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
302 // I1==first (untested) non-DBG preceding known match
303 while (I2->isDebugValue()) {
304 if (I2==MBB2->begin()) {
306 // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
311 // I1, I2==first (untested) non-DBGs preceding known match
312 if (!I1->isIdenticalTo(*I2) ||
313 // FIXME: This check is dubious. It's used to get around a problem where
314 // people incorrectly expect inline asm directives to remain in the same
315 // relative order. This is untenable because normal compiler
316 // optimizations (like this one) may reorder and/or merge these
324 // Back past possible debugging pseudos at beginning of block. This matters
325 // when one block differs from the other only by whether debugging pseudos
326 // are present at the beginning. (This way, the various checks later for
327 // I1==MBB1->begin() work as expected.)
328 if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
330 while (I2->isDebugValue()) {
331 if (I2 == MBB2->begin())
337 if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
339 while (I1->isDebugValue()) {
340 if (I1 == MBB1->begin())
349 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
350 MachineBasicBlock *NewDest) {
351 TII->ReplaceTailWithBranchTo(OldInst, NewDest);
354 NewDest->clearLiveIns();
355 computeLiveIns(LiveRegs, *MRI, *NewDest);
361 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
362 MachineBasicBlock::iterator BBI1,
363 const BasicBlock *BB) {
364 if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
367 MachineFunction &MF = *CurMBB.getParent();
369 // Create the fall-through block.
370 MachineFunction::iterator MBBI = CurMBB.getIterator();
371 MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB);
372 CurMBB.getParent()->insert(++MBBI, NewMBB);
374 // Move all the successors of this block to the specified block.
375 NewMBB->transferSuccessors(&CurMBB);
377 // Add an edge from CurMBB to NewMBB for the fall-through.
378 CurMBB.addSuccessor(NewMBB);
380 // Splice the code over.
381 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
383 // NewMBB belongs to the same loop as CurMBB.
385 if (MachineLoop *ML = MLI->getLoopFor(&CurMBB))
386 ML->addBasicBlockToLoop(NewMBB, MLI->getBase());
388 // NewMBB inherits CurMBB's block frequency.
389 MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
392 computeLiveIns(LiveRegs, *MRI, *NewMBB);
394 // Add the new block to the funclet.
395 const auto &FuncletI = FuncletMembership.find(&CurMBB);
396 if (FuncletI != FuncletMembership.end()) {
397 auto n = FuncletI->second;
398 FuncletMembership[NewMBB] = n;
404 /// EstimateRuntime - Make a rough estimate for how long it will take to run
405 /// the specified code.
406 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
407 MachineBasicBlock::iterator E) {
409 for (; I != E; ++I) {
410 if (I->isDebugValue())
414 else if (I->mayLoad() || I->mayStore())
422 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
423 // branches temporarily for tail merging). In the case where CurMBB ends
424 // with a conditional branch to the next block, optimize by reversing the
425 // test and conditionally branching to SuccMBB instead.
426 static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
427 const TargetInstrInfo *TII) {
428 MachineFunction *MF = CurMBB->getParent();
429 MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));
430 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
431 SmallVector<MachineOperand, 4> Cond;
432 DebugLoc dl = CurMBB->findBranchDebugLoc();
433 if (I != MF->end() && !TII->analyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
434 MachineBasicBlock *NextBB = &*I;
435 if (TBB == NextBB && !Cond.empty() && !FBB) {
436 if (!TII->reverseBranchCondition(Cond)) {
437 TII->removeBranch(*CurMBB);
438 TII->insertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
443 TII->insertBranch(*CurMBB, SuccBB, nullptr,
444 SmallVector<MachineOperand, 0>(), dl);
448 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
449 if (getHash() < o.getHash())
451 if (getHash() > o.getHash())
453 if (getBlock()->getNumber() < o.getBlock()->getNumber())
455 if (getBlock()->getNumber() > o.getBlock()->getNumber())
457 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
458 // an object with itself.
459 #ifndef _GLIBCXX_DEBUG
460 llvm_unreachable("Predecessor appears twice");
467 BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const {
468 auto I = MergedBBFreq.find(MBB);
470 if (I != MergedBBFreq.end())
473 return MBFI.getBlockFreq(MBB);
476 void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB,
478 MergedBBFreq[MBB] = F;
482 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS,
483 const MachineBasicBlock *MBB) const {
484 return MBFI.printBlockFreq(OS, getBlockFreq(MBB));
488 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS,
489 const BlockFrequency Freq) const {
490 return MBFI.printBlockFreq(OS, Freq);
493 void BranchFolder::MBFIWrapper::view(const Twine &Name, bool isSimple) {
494 MBFI.view(Name, isSimple);
498 BranchFolder::MBFIWrapper::getEntryFreq() const {
499 return MBFI.getEntryFreq();
502 /// CountTerminators - Count the number of terminators in the given
503 /// block and set I to the position of the first non-terminator, if there
504 /// is one, or MBB->end() otherwise.
505 static unsigned CountTerminators(MachineBasicBlock *MBB,
506 MachineBasicBlock::iterator &I) {
508 unsigned NumTerms = 0;
510 if (I == MBB->begin()) {
515 if (!I->isTerminator()) break;
521 /// A no successor, non-return block probably ends in unreachable and is cold.
522 /// Also consider a block that ends in an indirect branch to be a return block,
523 /// since many targets use plain indirect branches to return.
524 static bool blockEndsInUnreachable(const MachineBasicBlock *MBB) {
525 if (!MBB->succ_empty())
529 return !(MBB->back().isReturn() || MBB->back().isIndirectBranch());
532 /// ProfitableToMerge - Check if two machine basic blocks have a common tail
533 /// and decide if it would be profitable to merge those tails. Return the
534 /// length of the common tail and iterators to the first common instruction
536 /// MBB1, MBB2 The blocks to check
537 /// MinCommonTailLength Minimum size of tail block to be merged.
538 /// CommonTailLen Out parameter to record the size of the shared tail between
540 /// I1, I2 Iterator references that will be changed to point to the first
541 /// instruction in the common tail shared by MBB1,MBB2
542 /// SuccBB A common successor of MBB1, MBB2 which are in a canonical form
543 /// relative to SuccBB
544 /// PredBB The layout predecessor of SuccBB, if any.
545 /// FuncletMembership map from block to funclet #.
546 /// AfterPlacement True if we are merging blocks after layout. Stricter
547 /// thresholds apply to prevent undoing tail-duplication.
549 ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
550 unsigned MinCommonTailLength, unsigned &CommonTailLen,
551 MachineBasicBlock::iterator &I1,
552 MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB,
553 MachineBasicBlock *PredBB,
554 DenseMap<const MachineBasicBlock *, int> &FuncletMembership,
555 bool AfterPlacement) {
556 // It is never profitable to tail-merge blocks from two different funclets.
557 if (!FuncletMembership.empty()) {
558 auto Funclet1 = FuncletMembership.find(MBB1);
559 assert(Funclet1 != FuncletMembership.end());
560 auto Funclet2 = FuncletMembership.find(MBB2);
561 assert(Funclet2 != FuncletMembership.end());
562 if (Funclet1->second != Funclet2->second)
566 CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
567 if (CommonTailLen == 0)
569 DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
570 << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
573 // It's almost always profitable to merge any number of non-terminator
574 // instructions with the block that falls through into the common successor.
575 // This is true only for a single successor. For multiple successors, we are
576 // trading a conditional branch for an unconditional one.
577 // TODO: Re-visit successor size for non-layout tail merging.
578 if ((MBB1 == PredBB || MBB2 == PredBB) &&
579 (!AfterPlacement || MBB1->succ_size() == 1)) {
580 MachineBasicBlock::iterator I;
581 unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
582 if (CommonTailLen > NumTerms)
586 // If these are identical non-return blocks with no successors, merge them.
587 // Such blocks are typically cold calls to noreturn functions like abort, and
588 // are unlikely to become a fallthrough target after machine block placement.
589 // Tail merging these blocks is unlikely to create additional unconditional
590 // branches, and will reduce the size of this cold code.
591 if (I1 == MBB1->begin() && I2 == MBB2->begin() &&
592 blockEndsInUnreachable(MBB1) && blockEndsInUnreachable(MBB2))
595 // If one of the blocks can be completely merged and happens to be in
596 // a position where the other could fall through into it, merge any number
597 // of instructions, because it can be done without a branch.
598 // TODO: If the blocks are not adjacent, move one of them so that they are?
599 if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
601 if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
604 // If both blocks are identical and end in a branch, merge them unless they
605 // both have a fallthrough predecessor and successor.
606 // We can only do this after block placement because it depends on whether
607 // there are fallthroughs, and we don't know until after layout.
608 if (AfterPlacement && I1 == MBB1->begin() && I2 == MBB2->begin()) {
609 auto BothFallThrough = [](MachineBasicBlock *MBB) {
610 if (MBB->succ_size() != 0 && !MBB->canFallThrough())
612 MachineFunction::iterator I(MBB);
613 MachineFunction *MF = MBB->getParent();
614 return (MBB != &*MF->begin()) && std::prev(I)->canFallThrough();
616 if (!BothFallThrough(MBB1) || !BothFallThrough(MBB2))
620 // If both blocks have an unconditional branch temporarily stripped out,
621 // count that as an additional common instruction for the following
622 // heuristics. This heuristic is only accurate for single-succ blocks, so to
623 // make sure that during layout merging and duplicating don't crash, we check
624 // for that when merging during layout.
625 unsigned EffectiveTailLen = CommonTailLen;
626 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
627 (MBB1->succ_size() == 1 || !AfterPlacement) &&
628 !MBB1->back().isBarrier() &&
629 !MBB2->back().isBarrier())
632 // Check if the common tail is long enough to be worthwhile.
633 if (EffectiveTailLen >= MinCommonTailLength)
636 // If we are optimizing for code size, 2 instructions in common is enough if
637 // we don't have to split a block. At worst we will be introducing 1 new
638 // branch instruction, which is likely to be smaller than the 2
639 // instructions that would be deleted in the merge.
640 MachineFunction *MF = MBB1->getParent();
641 return EffectiveTailLen >= 2 && MF->getFunction()->optForSize() &&
642 (I1 == MBB1->begin() || I2 == MBB2->begin());
645 unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
646 unsigned MinCommonTailLength,
647 MachineBasicBlock *SuccBB,
648 MachineBasicBlock *PredBB) {
649 unsigned maxCommonTailLength = 0U;
651 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
652 MPIterator HighestMPIter = std::prev(MergePotentials.end());
653 for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
654 B = MergePotentials.begin();
655 CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
656 for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
657 unsigned CommonTailLen;
658 if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
660 CommonTailLen, TrialBBI1, TrialBBI2,
663 AfterBlockPlacement)) {
664 if (CommonTailLen > maxCommonTailLength) {
666 maxCommonTailLength = CommonTailLen;
667 HighestMPIter = CurMPIter;
668 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
670 if (HighestMPIter == CurMPIter &&
671 CommonTailLen == maxCommonTailLength)
672 SameTails.push_back(SameTailElt(I, TrialBBI2));
678 return maxCommonTailLength;
681 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
682 MachineBasicBlock *SuccBB,
683 MachineBasicBlock *PredBB) {
684 MPIterator CurMPIter, B;
685 for (CurMPIter = std::prev(MergePotentials.end()),
686 B = MergePotentials.begin();
687 CurMPIter->getHash() == CurHash; --CurMPIter) {
688 // Put the unconditional branch back, if we need one.
689 MachineBasicBlock *CurMBB = CurMPIter->getBlock();
690 if (SuccBB && CurMBB != PredBB)
691 FixTail(CurMBB, SuccBB, TII);
695 if (CurMPIter->getHash() != CurHash)
697 MergePotentials.erase(CurMPIter, MergePotentials.end());
700 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
701 MachineBasicBlock *SuccBB,
702 unsigned maxCommonTailLength,
703 unsigned &commonTailIndex) {
705 unsigned TimeEstimate = ~0U;
706 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
707 // Use PredBB if possible; that doesn't require a new branch.
708 if (SameTails[i].getBlock() == PredBB) {
712 // Otherwise, make a (fairly bogus) choice based on estimate of
713 // how long it will take the various blocks to execute.
714 unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
715 SameTails[i].getTailStartPos());
716 if (t <= TimeEstimate) {
722 MachineBasicBlock::iterator BBI =
723 SameTails[commonTailIndex].getTailStartPos();
724 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
726 DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
727 << maxCommonTailLength);
729 // If the split block unconditionally falls-thru to SuccBB, it will be
730 // merged. In control flow terms it should then take SuccBB's name. e.g. If
731 // SuccBB is an inner loop, the common tail is still part of the inner loop.
732 const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
733 SuccBB->getBasicBlock() : MBB->getBasicBlock();
734 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
736 DEBUG(dbgs() << "... failed!");
740 SameTails[commonTailIndex].setBlock(newMBB);
741 SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
743 // If we split PredBB, newMBB is the new predecessor.
750 void BranchFolder::MergeCommonTailDebugLocs(unsigned commonTailIndex) {
751 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
753 std::vector<MachineBasicBlock::iterator> NextCommonInsts(SameTails.size());
754 for (unsigned int i = 0 ; i != SameTails.size() ; ++i) {
755 if (i != commonTailIndex)
756 NextCommonInsts[i] = SameTails[i].getTailStartPos();
758 assert(SameTails[i].getTailStartPos() == MBB->begin() &&
759 "MBB is not a common tail only block");
763 for (auto &MI : *MBB) {
764 if (MI.isDebugValue())
766 DebugLoc DL = MI.getDebugLoc();
767 for (unsigned int i = 0 ; i < NextCommonInsts.size() ; i++) {
768 if (i == commonTailIndex)
771 auto &Pos = NextCommonInsts[i];
772 assert(Pos != SameTails[i].getBlock()->end() &&
773 "Reached BB end within common tail");
774 while (Pos->isDebugValue()) {
776 assert(Pos != SameTails[i].getBlock()->end() &&
777 "Reached BB end within common tail");
779 assert(MI.isIdenticalTo(*Pos) && "Expected matching MIIs!");
780 DL = DILocation::getMergedLocation(DL, Pos->getDebugLoc());
781 NextCommonInsts[i] = ++Pos;
788 mergeOperations(MachineBasicBlock::iterator MBBIStartPos,
789 MachineBasicBlock &MBBCommon) {
790 MachineBasicBlock *MBB = MBBIStartPos->getParent();
791 // Note CommonTailLen does not necessarily matches the size of
792 // the common BB nor all its instructions because of debug
793 // instructions differences.
794 unsigned CommonTailLen = 0;
795 for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)
798 MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();
799 MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();
800 MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
801 MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
803 while (CommonTailLen--) {
804 assert(MBBI != MBBIE && "Reached BB end within common tail length!");
807 if (MBBI->isDebugValue()) {
812 while ((MBBICommon != MBBIECommon) && MBBICommon->isDebugValue())
815 assert(MBBICommon != MBBIECommon &&
816 "Reached BB end within common tail length!");
817 assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!");
819 // Merge MMOs from memory operations in the common block.
820 if (MBBICommon->mayLoad() || MBBICommon->mayStore())
821 MBBICommon->setMemRefs(MBBICommon->mergeMemRefsWith(*MBBI));
822 // Drop undef flags if they aren't present in all merged instructions.
823 for (unsigned I = 0, E = MBBICommon->getNumOperands(); I != E; ++I) {
824 MachineOperand &MO = MBBICommon->getOperand(I);
825 if (MO.isReg() && MO.isUndef()) {
826 const MachineOperand &OtherMO = MBBI->getOperand(I);
827 if (!OtherMO.isUndef())
828 MO.setIsUndef(false);
837 // See if any of the blocks in MergePotentials (which all have SuccBB as a
838 // successor, or all have no successor if it is null) can be tail-merged.
839 // If there is a successor, any blocks in MergePotentials that are not
840 // tail-merged and are not immediately before Succ must have an unconditional
841 // branch to Succ added (but the predecessor/successor lists need no
842 // adjustment). The lone predecessor of Succ that falls through into Succ,
843 // if any, is given in PredBB.
844 // MinCommonTailLength - Except for the special cases below, tail-merge if
845 // there are at least this many instructions in common.
846 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
847 MachineBasicBlock *PredBB,
848 unsigned MinCommonTailLength) {
849 bool MadeChange = false;
851 DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
852 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
853 dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
854 << (i == e-1 ? "" : ", ");
857 dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n';
859 dbgs() << " which has fall-through from BB#"
860 << PredBB->getNumber() << "\n";
862 dbgs() << "Looking for common tails of at least "
863 << MinCommonTailLength << " instruction"
864 << (MinCommonTailLength == 1 ? "" : "s") << '\n';
867 // Sort by hash value so that blocks with identical end sequences sort
869 array_pod_sort(MergePotentials.begin(), MergePotentials.end());
871 // Walk through equivalence sets looking for actual exact matches.
872 while (MergePotentials.size() > 1) {
873 unsigned CurHash = MergePotentials.back().getHash();
875 // Build SameTails, identifying the set of blocks with this hash code
876 // and with the maximum number of instructions in common.
877 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
881 // If we didn't find any pair that has at least MinCommonTailLength
882 // instructions in common, remove all blocks with this hash code and retry.
883 if (SameTails.empty()) {
884 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
888 // If one of the blocks is the entire common tail (and not the entry
889 // block, which we can't jump to), we can treat all blocks with this same
890 // tail at once. Use PredBB if that is one of the possibilities, as that
891 // will not introduce any extra branches.
892 MachineBasicBlock *EntryBB =
893 &MergePotentials.front().getBlock()->getParent()->front();
894 unsigned commonTailIndex = SameTails.size();
895 // If there are two blocks, check to see if one can be made to fall through
897 if (SameTails.size() == 2 &&
898 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
899 SameTails[1].tailIsWholeBlock())
901 else if (SameTails.size() == 2 &&
902 SameTails[1].getBlock()->isLayoutSuccessor(
903 SameTails[0].getBlock()) &&
904 SameTails[0].tailIsWholeBlock())
907 // Otherwise just pick one, favoring the fall-through predecessor if
909 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
910 MachineBasicBlock *MBB = SameTails[i].getBlock();
911 if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
917 if (SameTails[i].tailIsWholeBlock())
922 if (commonTailIndex == SameTails.size() ||
923 (SameTails[commonTailIndex].getBlock() == PredBB &&
924 !SameTails[commonTailIndex].tailIsWholeBlock())) {
925 // None of the blocks consist entirely of the common tail.
926 // Split a block so that one does.
927 if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
928 maxCommonTailLength, commonTailIndex)) {
929 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
934 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
936 // Recompute common tail MBB's edge weights and block frequency.
937 setCommonTailEdgeWeights(*MBB);
939 // Merge debug locations across identical instructions for common tail.
940 MergeCommonTailDebugLocs(commonTailIndex);
942 // MBB is common tail. Adjust all other BB's to jump to this one.
943 // Traversal must be forwards so erases work.
944 DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
946 for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
947 if (commonTailIndex == i)
949 DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
950 << (i == e-1 ? "" : ", "));
951 // Merge operations (MMOs, undef flags)
952 mergeOperations(SameTails[i].getTailStartPos(), *MBB);
953 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
954 ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
955 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
956 MergePotentials.erase(SameTails[i].getMPIter());
958 DEBUG(dbgs() << "\n");
959 // We leave commonTailIndex in the worklist in case there are other blocks
960 // that match it with a smaller number of instructions.
966 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
967 bool MadeChange = false;
968 if (!EnableTailMerge) return MadeChange;
970 // First find blocks with no successors.
971 // Block placement does not create new tail merging opportunities for these
973 if (!AfterBlockPlacement) {
974 MergePotentials.clear();
975 for (MachineBasicBlock &MBB : MF) {
976 if (MergePotentials.size() == TailMergeThreshold)
978 if (!TriedMerging.count(&MBB) && MBB.succ_empty())
979 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB));
982 // If this is a large problem, avoid visiting the same basic blocks
984 if (MergePotentials.size() == TailMergeThreshold)
985 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
986 TriedMerging.insert(MergePotentials[i].getBlock());
988 // See if we can do any tail merging on those.
989 if (MergePotentials.size() >= 2)
990 MadeChange |= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength);
993 // Look at blocks (IBB) with multiple predecessors (PBB).
994 // We change each predecessor to a canonical form, by
995 // (1) temporarily removing any unconditional branch from the predecessor
997 // (2) alter conditional branches so they branch to the other block
998 // not IBB; this may require adding back an unconditional branch to IBB
999 // later, where there wasn't one coming in. E.g.
1001 // fallthrough to QBB
1004 // with a conceptual B to IBB after that, which never actually exists.
1005 // With those changes, we see whether the predecessors' tails match,
1006 // and merge them if so. We change things out of canonical form and
1007 // back to the way they were later in the process. (OptimizeBranches
1008 // would undo some of this, but we can't use it, because we'd get into
1009 // a compile-time infinite loop repeatedly doing and undoing the same
1010 // transformations.)
1012 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1014 if (I->pred_size() < 2) continue;
1015 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
1016 MachineBasicBlock *IBB = &*I;
1017 MachineBasicBlock *PredBB = &*std::prev(I);
1018 MergePotentials.clear();
1021 // Bail if merging after placement and IBB is the loop header because
1022 // -- If merging predecessors that belong to the same loop as IBB, the
1023 // common tail of merged predecessors may become the loop top if block
1024 // placement is called again and the predecessors may branch to this common
1025 // tail and require more branches. This can be relaxed if
1026 // MachineBlockPlacement::findBestLoopTop is more flexible.
1027 // --If merging predecessors that do not belong to the same loop as IBB, the
1028 // loop info of IBB's loop and the other loops may be affected. Calling the
1029 // block placement again may make big change to the layout and eliminate the
1030 // reason to do tail merging here.
1031 if (AfterBlockPlacement && MLI) {
1032 ML = MLI->getLoopFor(IBB);
1033 if (ML && IBB == ML->getHeader())
1037 for (MachineBasicBlock *PBB : I->predecessors()) {
1038 if (MergePotentials.size() == TailMergeThreshold)
1041 if (TriedMerging.count(PBB))
1044 // Skip blocks that loop to themselves, can't tail merge these.
1048 // Visit each predecessor only once.
1049 if (!UniquePreds.insert(PBB).second)
1052 // Skip blocks which may jump to a landing pad. Can't tail merge these.
1053 if (PBB->hasEHPadSuccessor())
1056 // After block placement, only consider predecessors that belong to the
1057 // same loop as IBB. The reason is the same as above when skipping loop
1059 if (AfterBlockPlacement && MLI)
1060 if (ML != MLI->getLoopFor(PBB))
1063 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1064 SmallVector<MachineOperand, 4> Cond;
1065 if (!TII->analyzeBranch(*PBB, TBB, FBB, Cond, true)) {
1066 // Failing case: IBB is the target of a cbr, and we cannot reverse the
1068 SmallVector<MachineOperand, 4> NewCond(Cond);
1069 if (!Cond.empty() && TBB == IBB) {
1070 if (TII->reverseBranchCondition(NewCond))
1072 // This is the QBB case described above
1074 auto Next = ++PBB->getIterator();
1075 if (Next != MF.end())
1080 // Failing case: the only way IBB can be reached from PBB is via
1081 // exception handling. Happens for landing pads. Would be nice to have
1082 // a bit in the edge so we didn't have to do all this.
1083 if (IBB->isEHPad()) {
1084 MachineFunction::iterator IP = ++PBB->getIterator();
1085 MachineBasicBlock *PredNextBB = nullptr;
1089 if (IBB != PredNextBB) // fallthrough
1092 if (TBB != IBB && FBB != IBB) // cbr then ubr
1094 } else if (Cond.empty()) {
1095 if (TBB != IBB) // ubr
1098 if (TBB != IBB && IBB != PredNextBB) // cbr
1103 // Remove the unconditional branch at the end, if any.
1104 if (TBB && (Cond.empty() || FBB)) {
1105 DebugLoc dl = PBB->findBranchDebugLoc();
1106 TII->removeBranch(*PBB);
1108 // reinsert conditional branch only, for now
1109 TII->insertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
1113 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(*PBB), PBB));
1117 // If this is a large problem, avoid visiting the same basic blocks multiple
1119 if (MergePotentials.size() == TailMergeThreshold)
1120 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
1121 TriedMerging.insert(MergePotentials[i].getBlock());
1123 if (MergePotentials.size() >= 2)
1124 MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength);
1126 // Reinsert an unconditional branch if needed. The 1 below can occur as a
1127 // result of removing blocks in TryTailMergeBlocks.
1128 PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks
1129 if (MergePotentials.size() == 1 &&
1130 MergePotentials.begin()->getBlock() != PredBB)
1131 FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
1137 void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
1138 SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
1139 BlockFrequency AccumulatedMBBFreq;
1141 // Aggregate edge frequency of successor edge j:
1142 // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1143 // where bb is a basic block that is in SameTails.
1144 for (const auto &Src : SameTails) {
1145 const MachineBasicBlock *SrcMBB = Src.getBlock();
1146 BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
1147 AccumulatedMBBFreq += BlockFreq;
1149 // It is not necessary to recompute edge weights if TailBB has less than two
1151 if (TailMBB.succ_size() <= 1)
1154 auto EdgeFreq = EdgeFreqLs.begin();
1156 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1157 SuccI != SuccE; ++SuccI, ++EdgeFreq)
1158 *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
1161 MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1163 if (TailMBB.succ_size() <= 1)
1167 std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0))
1169 auto EdgeFreq = EdgeFreqLs.begin();
1171 if (SumEdgeFreq > 0) {
1172 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1173 SuccI != SuccE; ++SuccI, ++EdgeFreq) {
1174 auto Prob = BranchProbability::getBranchProbability(
1175 EdgeFreq->getFrequency(), SumEdgeFreq);
1176 TailMBB.setSuccProbability(SuccI, Prob);
1181 //===----------------------------------------------------------------------===//
1182 // Branch Optimization
1183 //===----------------------------------------------------------------------===//
1185 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
1186 bool MadeChange = false;
1188 // Make sure blocks are numbered in order
1189 MF.RenumberBlocks();
1190 // Renumbering blocks alters funclet membership, recalculate it.
1191 FuncletMembership = getFuncletMembership(MF);
1193 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1195 MachineBasicBlock *MBB = &*I++;
1196 MadeChange |= OptimizeBlock(MBB);
1198 // If it is dead, remove it.
1199 if (MBB->pred_empty()) {
1200 RemoveDeadBlock(MBB);
1209 // Blocks should be considered empty if they contain only debug info;
1210 // else the debug info would affect codegen.
1211 static bool IsEmptyBlock(MachineBasicBlock *MBB) {
1212 return MBB->getFirstNonDebugInstr() == MBB->end();
1215 // Blocks with only debug info and branches should be considered the same
1216 // as blocks with only branches.
1217 static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
1218 MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();
1219 assert(I != MBB->end() && "empty block!");
1220 return I->isBranch();
1223 /// IsBetterFallthrough - Return true if it would be clearly better to
1224 /// fall-through to MBB1 than to fall through into MBB2. This has to return
1225 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1226 /// result in infinite loops.
1227 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
1228 MachineBasicBlock *MBB2) {
1229 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
1230 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
1231 // optimize branches that branch to either a return block or an assert block
1232 // into a fallthrough to the return.
1233 MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr();
1234 MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr();
1235 if (MBB1I == MBB1->end() || MBB2I == MBB2->end())
1238 // If there is a clear successor ordering we make sure that one block
1239 // will fall through to the next
1240 if (MBB1->isSuccessor(MBB2)) return true;
1241 if (MBB2->isSuccessor(MBB1)) return false;
1243 return MBB2I->isCall() && !MBB1I->isCall();
1246 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1247 /// instructions on the block.
1248 static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
1249 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1250 if (I != MBB.end() && I->isBranch())
1251 return I->getDebugLoc();
1255 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1256 bool MadeChange = false;
1257 MachineFunction &MF = *MBB->getParent();
1260 MachineFunction::iterator FallThrough = MBB->getIterator();
1263 // Make sure MBB and FallThrough belong to the same funclet.
1264 bool SameFunclet = true;
1265 if (!FuncletMembership.empty() && FallThrough != MF.end()) {
1266 auto MBBFunclet = FuncletMembership.find(MBB);
1267 assert(MBBFunclet != FuncletMembership.end());
1268 auto FallThroughFunclet = FuncletMembership.find(&*FallThrough);
1269 assert(FallThroughFunclet != FuncletMembership.end());
1270 SameFunclet = MBBFunclet->second == FallThroughFunclet->second;
1273 // If this block is empty, make everyone use its fall-through, not the block
1274 // explicitly. Landing pads should not do this since the landing-pad table
1275 // points to this block. Blocks with their addresses taken shouldn't be
1277 if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() &&
1279 // Dead block? Leave for cleanup later.
1280 if (MBB->pred_empty()) return MadeChange;
1282 if (FallThrough == MF.end()) {
1283 // TODO: Simplify preds to not branch here if possible!
1284 } else if (FallThrough->isEHPad()) {
1285 // Don't rewrite to a landing pad fallthough. That could lead to the case
1286 // where a BB jumps to more than one landing pad.
1287 // TODO: Is it ever worth rewriting predecessors which don't already
1288 // jump to a landing pad, and so can safely jump to the fallthrough?
1289 } else if (MBB->isSuccessor(&*FallThrough)) {
1290 // Rewrite all predecessors of the old block to go to the fallthrough
1292 while (!MBB->pred_empty()) {
1293 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1294 Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
1296 // If MBB was the target of a jump table, update jump tables to go to the
1297 // fallthrough instead.
1298 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1299 MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
1305 // Check to see if we can simplify the terminator of the block before this
1307 MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
1309 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
1310 SmallVector<MachineOperand, 4> PriorCond;
1311 bool PriorUnAnalyzable =
1312 TII->analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1313 if (!PriorUnAnalyzable) {
1314 // If the CFG for the prior block has extra edges, remove them.
1315 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1316 !PriorCond.empty());
1318 // If the previous branch is conditional and both conditions go to the same
1319 // destination, remove the branch, replacing it with an unconditional one or
1321 if (PriorTBB && PriorTBB == PriorFBB) {
1322 DebugLoc dl = getBranchDebugLoc(PrevBB);
1323 TII->removeBranch(PrevBB);
1325 if (PriorTBB != MBB)
1326 TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1329 goto ReoptimizeBlock;
1332 // If the previous block unconditionally falls through to this block and
1333 // this block has no other predecessors, move the contents of this block
1334 // into the prior block. This doesn't usually happen when SimplifyCFG
1335 // has been used, but it can happen if tail merging splits a fall-through
1336 // predecessor of a block.
1337 // This has to check PrevBB->succ_size() because EH edges are ignored by
1339 if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1340 PrevBB.succ_size() == 1 &&
1341 !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1342 DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1343 << "From MBB: " << *MBB);
1344 // Remove redundant DBG_VALUEs first.
1345 if (PrevBB.begin() != PrevBB.end()) {
1346 MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1348 MachineBasicBlock::iterator MBBIter = MBB->begin();
1349 // Check if DBG_VALUE at the end of PrevBB is identical to the
1350 // DBG_VALUE at the beginning of MBB.
1351 while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1352 && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1353 if (!MBBIter->isIdenticalTo(*PrevBBIter))
1355 MachineInstr &DuplicateDbg = *MBBIter;
1356 ++MBBIter; -- PrevBBIter;
1357 DuplicateDbg.eraseFromParent();
1360 PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1361 PrevBB.removeSuccessor(PrevBB.succ_begin());
1362 assert(PrevBB.succ_empty());
1363 PrevBB.transferSuccessors(MBB);
1368 // If the previous branch *only* branches to *this* block (conditional or
1369 // not) remove the branch.
1370 if (PriorTBB == MBB && !PriorFBB) {
1371 TII->removeBranch(PrevBB);
1374 goto ReoptimizeBlock;
1377 // If the prior block branches somewhere else on the condition and here if
1378 // the condition is false, remove the uncond second branch.
1379 if (PriorFBB == MBB) {
1380 DebugLoc dl = getBranchDebugLoc(PrevBB);
1381 TII->removeBranch(PrevBB);
1382 TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1385 goto ReoptimizeBlock;
1388 // If the prior block branches here on true and somewhere else on false, and
1389 // if the branch condition is reversible, reverse the branch to create a
1391 if (PriorTBB == MBB) {
1392 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1393 if (!TII->reverseBranchCondition(NewPriorCond)) {
1394 DebugLoc dl = getBranchDebugLoc(PrevBB);
1395 TII->removeBranch(PrevBB);
1396 TII->insertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
1399 goto ReoptimizeBlock;
1403 // If this block has no successors (e.g. it is a return block or ends with
1404 // a call to a no-return function like abort or __cxa_throw) and if the pred
1405 // falls through into this block, and if it would otherwise fall through
1406 // into the block after this, move this block to the end of the function.
1408 // We consider it more likely that execution will stay in the function (e.g.
1409 // due to loops) than it is to exit it. This asserts in loops etc, moving
1410 // the assert condition out of the loop body.
1411 if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
1412 MachineFunction::iterator(PriorTBB) == FallThrough &&
1413 !MBB->canFallThrough()) {
1414 bool DoTransform = true;
1416 // We have to be careful that the succs of PredBB aren't both no-successor
1417 // blocks. If neither have successors and if PredBB is the second from
1418 // last block in the function, we'd just keep swapping the two blocks for
1419 // last. Only do the swap if one is clearly better to fall through than
1421 if (FallThrough == --MF.end() &&
1422 !IsBetterFallthrough(PriorTBB, MBB))
1423 DoTransform = false;
1426 // Reverse the branch so we will fall through on the previous true cond.
1427 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1428 if (!TII->reverseBranchCondition(NewPriorCond)) {
1429 DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1430 << "To make fallthrough to: " << *PriorTBB << "\n");
1432 DebugLoc dl = getBranchDebugLoc(PrevBB);
1433 TII->removeBranch(PrevBB);
1434 TII->insertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
1436 // Move this block to the end of the function.
1437 MBB->moveAfter(&MF.back());
1446 if (!IsEmptyBlock(MBB) && MBB->pred_size() == 1 &&
1447 MF.getFunction()->optForSize()) {
1448 // Changing "Jcc foo; foo: jmp bar;" into "Jcc bar;" might change the branch
1449 // direction, thereby defeating careful block placement and regressing
1450 // performance. Therefore, only consider this for optsize functions.
1451 MachineInstr &TailCall = *MBB->getFirstNonDebugInstr();
1452 if (TII->isUnconditionalTailCall(TailCall)) {
1453 MachineBasicBlock *Pred = *MBB->pred_begin();
1454 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1455 SmallVector<MachineOperand, 4> PredCond;
1456 bool PredAnalyzable =
1457 !TII->analyzeBranch(*Pred, PredTBB, PredFBB, PredCond, true);
1459 if (PredAnalyzable && !PredCond.empty() && PredTBB == MBB) {
1460 // The predecessor has a conditional branch to this block which consists
1461 // of only a tail call. Try to fold the tail call into the conditional
1463 if (TII->canMakeTailCallConditional(PredCond, TailCall)) {
1464 // TODO: It would be nice if analyzeBranch() could provide a pointer
1465 // to the branch insturction so replaceBranchWithTailCall() doesn't
1466 // have to search for it.
1467 TII->replaceBranchWithTailCall(*Pred, PredCond, TailCall);
1469 Pred->removeSuccessor(MBB);
1474 // If the predecessor is falling through to this block, we could reverse
1475 // the branch condition and fold the tail call into that. However, after
1476 // that we might have to re-arrange the CFG to fall through to the other
1477 // block and there is a high risk of regressing code size rather than
1482 // Analyze the branch in the current block.
1483 MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
1484 SmallVector<MachineOperand, 4> CurCond;
1485 bool CurUnAnalyzable =
1486 TII->analyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1487 if (!CurUnAnalyzable) {
1488 // If the CFG for the prior block has extra edges, remove them.
1489 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1491 // If this is a two-way branch, and the FBB branches to this block, reverse
1492 // the condition so the single-basic-block loop is faster. Instead of:
1493 // Loop: xxx; jcc Out; jmp Loop
1495 // Loop: xxx; jncc Loop; jmp Out
1496 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1497 SmallVector<MachineOperand, 4> NewCond(CurCond);
1498 if (!TII->reverseBranchCondition(NewCond)) {
1499 DebugLoc dl = getBranchDebugLoc(*MBB);
1500 TII->removeBranch(*MBB);
1501 TII->insertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
1504 goto ReoptimizeBlock;
1508 // If this branch is the only thing in its block, see if we can forward
1509 // other blocks across it.
1510 if (CurTBB && CurCond.empty() && !CurFBB &&
1511 IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1512 !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1513 DebugLoc dl = getBranchDebugLoc(*MBB);
1514 // This block may contain just an unconditional branch. Because there can
1515 // be 'non-branch terminators' in the block, try removing the branch and
1516 // then seeing if the block is empty.
1517 TII->removeBranch(*MBB);
1518 // If the only things remaining in the block are debug info, remove these
1519 // as well, so this will behave the same as an empty block in non-debug
1521 if (IsEmptyBlock(MBB)) {
1522 // Make the block empty, losing the debug info (we could probably
1523 // improve this in some cases.)
1524 MBB->erase(MBB->begin(), MBB->end());
1526 // If this block is just an unconditional branch to CurTBB, we can
1527 // usually completely eliminate the block. The only case we cannot
1528 // completely eliminate the block is when the block before this one
1529 // falls through into MBB and we can't understand the prior block's branch
1532 bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1533 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1534 !PrevBB.isSuccessor(MBB)) {
1535 // If the prior block falls through into us, turn it into an
1536 // explicit branch to us to make updates simpler.
1537 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1538 PriorTBB != MBB && PriorFBB != MBB) {
1540 assert(PriorCond.empty() && !PriorFBB &&
1541 "Bad branch analysis");
1544 assert(!PriorFBB && "Machine CFG out of date!");
1547 DebugLoc pdl = getBranchDebugLoc(PrevBB);
1548 TII->removeBranch(PrevBB);
1549 TII->insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1552 // Iterate through all the predecessors, revectoring each in-turn.
1554 bool DidChange = false;
1555 bool HasBranchToSelf = false;
1556 while(PI != MBB->pred_size()) {
1557 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1559 // If this block has an uncond branch to itself, leave it.
1561 HasBranchToSelf = true;
1564 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1565 // If this change resulted in PMBB ending in a conditional
1566 // branch where both conditions go to the same destination,
1567 // change this to an unconditional branch (and fix the CFG).
1568 MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
1569 SmallVector<MachineOperand, 4> NewCurCond;
1570 bool NewCurUnAnalyzable = TII->analyzeBranch(
1571 *PMBB, NewCurTBB, NewCurFBB, NewCurCond, true);
1572 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1573 DebugLoc pdl = getBranchDebugLoc(*PMBB);
1574 TII->removeBranch(*PMBB);
1576 TII->insertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
1579 PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false);
1584 // Change any jumptables to go to the new MBB.
1585 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1586 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1590 if (!HasBranchToSelf) return MadeChange;
1595 // Add the branch back if the block is more than just an uncond branch.
1596 TII->insertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
1600 // If the prior block doesn't fall through into this block, and if this
1601 // block doesn't fall through into some other block, see if we can find a
1602 // place to move this block where a fall-through will happen.
1603 if (!PrevBB.canFallThrough()) {
1605 // Now we know that there was no fall-through into this block, check to
1606 // see if it has a fall-through into its successor.
1607 bool CurFallsThru = MBB->canFallThrough();
1609 if (!MBB->isEHPad()) {
1610 // Check all the predecessors of this block. If one of them has no fall
1611 // throughs, move this block right after it.
1612 for (MachineBasicBlock *PredBB : MBB->predecessors()) {
1613 // Analyze the branch at the end of the pred.
1614 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1615 SmallVector<MachineOperand, 4> PredCond;
1616 if (PredBB != MBB && !PredBB->canFallThrough() &&
1617 !TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) &&
1618 (!CurFallsThru || !CurTBB || !CurFBB) &&
1619 (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1620 // If the current block doesn't fall through, just move it.
1621 // If the current block can fall through and does not end with a
1622 // conditional branch, we need to append an unconditional jump to
1623 // the (current) next block. To avoid a possible compile-time
1624 // infinite loop, move blocks only backward in this case.
1625 // Also, if there are already 2 branches here, we cannot add a third;
1626 // this means we have the case
1631 MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
1633 TII->insertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
1635 MBB->moveAfter(PredBB);
1637 goto ReoptimizeBlock;
1642 if (!CurFallsThru) {
1643 // Check all successors to see if we can move this block before it.
1644 for (MachineBasicBlock *SuccBB : MBB->successors()) {
1645 // Analyze the branch at the end of the block before the succ.
1646 MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
1648 // If this block doesn't already fall-through to that successor, and if
1649 // the succ doesn't already have a block that can fall through into it,
1650 // and if the successor isn't an EH destination, we can arrange for the
1651 // fallthrough to happen.
1652 if (SuccBB != MBB && &*SuccPrev != MBB &&
1653 !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1654 !SuccBB->isEHPad()) {
1655 MBB->moveBefore(SuccBB);
1657 goto ReoptimizeBlock;
1661 // Okay, there is no really great place to put this block. If, however,
1662 // the block before this one would be a fall-through if this block were
1663 // removed, move this block to the end of the function. There is no real
1664 // advantage in "falling through" to an EH block, so we don't want to
1665 // perform this transformation for that case.
1667 // Also, Windows EH introduced the possibility of an arbitrary number of
1668 // successors to a given block. The analyzeBranch call does not consider
1669 // exception handling and so we can get in a state where a block
1670 // containing a call is followed by multiple EH blocks that would be
1671 // rotated infinitely at the end of the function if the transformation
1672 // below were performed for EH "FallThrough" blocks. Therefore, even if
1673 // that appears not to be happening anymore, we should assume that it is
1674 // possible and not remove the "!FallThrough()->isEHPad" condition below.
1675 MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
1676 SmallVector<MachineOperand, 4> PrevCond;
1677 if (FallThrough != MF.end() &&
1678 !FallThrough->isEHPad() &&
1679 !TII->analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
1680 PrevBB.isSuccessor(&*FallThrough)) {
1681 MBB->moveAfter(&MF.back());
1691 //===----------------------------------------------------------------------===//
1692 // Hoist Common Code
1693 //===----------------------------------------------------------------------===//
1695 bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1696 bool MadeChange = false;
1697 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
1698 MachineBasicBlock *MBB = &*I++;
1699 MadeChange |= HoistCommonCodeInSuccs(MBB);
1705 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1706 /// its 'true' successor.
1707 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1708 MachineBasicBlock *TrueBB) {
1709 for (MachineBasicBlock *SuccBB : BB->successors())
1710 if (SuccBB != TrueBB)
1715 template <class Container>
1716 static void addRegAndItsAliases(unsigned Reg, const TargetRegisterInfo *TRI,
1718 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1719 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1726 /// findHoistingInsertPosAndDeps - Find the location to move common instructions
1727 /// in successors to. The location is usually just before the terminator,
1728 /// however if the terminator is a conditional branch and its previous
1729 /// instruction is the flag setting instruction, the previous instruction is
1730 /// the preferred location. This function also gathers uses and defs of the
1731 /// instructions from the insertion point to the end of the block. The data is
1732 /// used by HoistCommonCodeInSuccs to ensure safety.
1734 MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1735 const TargetInstrInfo *TII,
1736 const TargetRegisterInfo *TRI,
1737 SmallSet<unsigned,4> &Uses,
1738 SmallSet<unsigned,4> &Defs) {
1739 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1740 if (!TII->isUnpredicatedTerminator(*Loc))
1743 for (const MachineOperand &MO : Loc->operands()) {
1746 unsigned Reg = MO.getReg();
1750 addRegAndItsAliases(Reg, TRI, Uses);
1753 // Don't try to hoist code in the rare case the terminator defines a
1754 // register that is later used.
1757 // If the terminator defines a register, make sure we don't hoist
1758 // the instruction whose def might be clobbered by the terminator.
1759 addRegAndItsAliases(Reg, TRI, Defs);
1765 if (Loc == MBB->begin())
1768 // The terminator is probably a conditional branch, try not to separate the
1769 // branch from condition setting instruction.
1770 MachineBasicBlock::iterator PI =
1771 skipDebugInstructionsBackward(std::prev(Loc), MBB->begin());
1774 for (const MachineOperand &MO : PI->operands()) {
1775 // If PI has a regmask operand, it is probably a call. Separate away.
1778 if (!MO.isReg() || MO.isUse())
1780 unsigned Reg = MO.getReg();
1783 if (Uses.count(Reg)) {
1789 // The condition setting instruction is not just before the conditional
1793 // Be conservative, don't insert instruction above something that may have
1794 // side-effects. And since it's potentially bad to separate flag setting
1795 // instruction from the conditional branch, just abort the optimization
1797 // Also avoid moving code above predicated instruction since it's hard to
1798 // reason about register liveness with predicated instruction.
1799 bool DontMoveAcrossStore = true;
1800 if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(*PI))
1804 // Find out what registers are live. Note this routine is ignoring other live
1805 // registers which are only used by instructions in successor blocks.
1806 for (const MachineOperand &MO : PI->operands()) {
1809 unsigned Reg = MO.getReg();
1813 addRegAndItsAliases(Reg, TRI, Uses);
1815 if (Uses.erase(Reg)) {
1816 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1817 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1818 Uses.erase(*SubRegs); // Use sub-registers to be conservative
1821 addRegAndItsAliases(Reg, TRI, Defs);
1828 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1829 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1830 SmallVector<MachineOperand, 4> Cond;
1831 if (TII->analyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
1834 if (!FBB) FBB = findFalseBlock(MBB, TBB);
1836 // Malformed bcc? True and false blocks are the same?
1839 // Restrict the optimization to cases where MBB is the only predecessor,
1840 // it is an obvious win.
1841 if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1844 // Find a suitable position to hoist the common instructions to. Also figure
1845 // out which registers are used or defined by instructions from the insertion
1846 // point to the end of the block.
1847 SmallSet<unsigned, 4> Uses, Defs;
1848 MachineBasicBlock::iterator Loc =
1849 findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1850 if (Loc == MBB->end())
1853 bool HasDups = false;
1854 SmallVector<unsigned, 4> LocalDefs, LocalKills;
1855 SmallSet<unsigned, 4> ActiveDefsSet, AllDefsSet;
1856 MachineBasicBlock::iterator TIB = TBB->begin();
1857 MachineBasicBlock::iterator FIB = FBB->begin();
1858 MachineBasicBlock::iterator TIE = TBB->end();
1859 MachineBasicBlock::iterator FIE = FBB->end();
1860 while (TIB != TIE && FIB != FIE) {
1861 // Skip dbg_value instructions. These do not count.
1862 TIB = skipDebugInstructionsForward(TIB, TIE);
1863 FIB = skipDebugInstructionsForward(FIB, FIE);
1864 if (TIB == TIE || FIB == FIE)
1867 if (!TIB->isIdenticalTo(*FIB, MachineInstr::CheckKillDead))
1870 if (TII->isPredicated(*TIB))
1871 // Hard to reason about register liveness with predicated instruction.
1875 for (MachineOperand &MO : TIB->operands()) {
1876 // Don't attempt to hoist instructions with register masks.
1877 if (MO.isRegMask()) {
1883 unsigned Reg = MO.getReg();
1887 if (Uses.count(Reg)) {
1888 // Avoid clobbering a register that's used by the instruction at
1889 // the point of insertion.
1894 if (Defs.count(Reg) && !MO.isDead()) {
1895 // Don't hoist the instruction if the def would be clobber by the
1896 // instruction at the point insertion. FIXME: This is overly
1897 // conservative. It should be possible to hoist the instructions
1898 // in BB2 in the following example:
1900 // r1, eflag = op1 r2, r3
1909 } else if (!ActiveDefsSet.count(Reg)) {
1910 if (Defs.count(Reg)) {
1911 // Use is defined by the instruction at the point of insertion.
1916 if (MO.isKill() && Uses.count(Reg))
1917 // Kills a register that's read by the instruction at the point of
1918 // insertion. Remove the kill marker.
1919 MO.setIsKill(false);
1925 bool DontMoveAcrossStore = true;
1926 if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore))
1929 // Remove kills from ActiveDefsSet, these registers had short live ranges.
1930 for (const MachineOperand &MO : TIB->operands()) {
1931 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1933 unsigned Reg = MO.getReg();
1936 if (!AllDefsSet.count(Reg)) {
1937 LocalKills.push_back(Reg);
1940 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1941 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1942 ActiveDefsSet.erase(*AI);
1944 ActiveDefsSet.erase(Reg);
1948 // Track local defs so we can update liveins.
1949 for (const MachineOperand &MO : TIB->operands()) {
1950 if (!MO.isReg() || !MO.isDef() || MO.isDead())
1952 unsigned Reg = MO.getReg();
1953 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg))
1955 LocalDefs.push_back(Reg);
1956 addRegAndItsAliases(Reg, TRI, ActiveDefsSet);
1957 addRegAndItsAliases(Reg, TRI, AllDefsSet);
1968 MBB->splice(Loc, TBB, TBB->begin(), TIB);
1969 FBB->erase(FBB->begin(), FIB);
1972 bool ChangedLiveIns = false;
1973 for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
1974 unsigned Def = LocalDefs[i];
1975 if (ActiveDefsSet.count(Def)) {
1976 TBB->addLiveIn(Def);
1977 FBB->addLiveIn(Def);
1978 ChangedLiveIns = true;
1981 for (unsigned K : LocalKills) {
1982 TBB->removeLiveIn(K);
1983 FBB->removeLiveIn(K);
1984 ChangedLiveIns = true;
1987 if (ChangedLiveIns) {
1988 TBB->sortUniqueLiveIns();
1989 FBB->sortUniqueLiveIns();