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
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "branchfolding"
20 #include "BranchFolding.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineJumpTableInfo.h"
26 #include "llvm/CodeGen/RegisterScavenging.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/SetVector.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
41 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
42 STATISTIC(NumBranchOpts, "Number of branches optimized");
43 STATISTIC(NumTailMerge , "Number of block tails merged");
44 STATISTIC(NumHoist , "Number of times common instructions are hoisted");
46 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
47 cl::init(cl::BOU_UNSET), cl::Hidden);
49 // Throttle for huge numbers of predecessors (compile speed problems)
50 static cl::opt<unsigned>
51 TailMergeThreshold("tail-merge-threshold",
52 cl::desc("Max number of predecessors to consider tail merging"),
53 cl::init(150), cl::Hidden);
55 // Heuristic for tail merging (and, inversely, tail duplication).
56 // TODO: This should be replaced with a target query.
57 static cl::opt<unsigned>
58 TailMergeSize("tail-merge-size",
59 cl::desc("Min number of instructions to consider tail merging"),
60 cl::init(3), cl::Hidden);
63 /// BranchFolderPass - Wrap branch folder in a machine function pass.
64 class BranchFolderPass : public MachineFunctionPass {
67 explicit BranchFolderPass(): MachineFunctionPass(ID) {}
69 virtual bool runOnMachineFunction(MachineFunction &MF);
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequired<TargetPassConfig>();
73 MachineFunctionPass::getAnalysisUsage(AU);
78 char BranchFolderPass::ID = 0;
79 char &llvm::BranchFolderPassID = BranchFolderPass::ID;
81 INITIALIZE_PASS(BranchFolderPass, "branch-folder",
82 "Control Flow Optimizer", false, false)
84 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
85 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
86 BranchFolder Folder(PassConfig->getEnableTailMerge(), /*CommonHoist=*/true);
87 return Folder.OptimizeFunction(MF,
88 MF.getTarget().getInstrInfo(),
89 MF.getTarget().getRegisterInfo(),
90 getAnalysisIfAvailable<MachineModuleInfo>());
94 BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist) {
95 switch (FlagEnableTailMerge) {
96 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
97 case cl::BOU_TRUE: EnableTailMerge = true; break;
98 case cl::BOU_FALSE: EnableTailMerge = false; break;
101 EnableHoistCommonCode = CommonHoist;
104 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
105 /// function, updating the CFG.
106 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
107 assert(MBB->pred_empty() && "MBB must be dead!");
108 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
110 MachineFunction *MF = MBB->getParent();
111 // drop all successors.
112 while (!MBB->succ_empty())
113 MBB->removeSuccessor(MBB->succ_end()-1);
115 // Avoid matching if this pointer gets reused.
116 TriedMerging.erase(MBB);
122 /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
123 /// followed by terminators, and if the implicitly defined registers are not
124 /// used by the terminators, remove those implicit_def's. e.g.
126 /// r0 = implicit_def
127 /// r1 = implicit_def
129 /// This block can be optimized away later if the implicit instructions are
131 bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
132 SmallSet<unsigned, 4> ImpDefRegs;
133 MachineBasicBlock::iterator I = MBB->begin();
134 while (I != MBB->end()) {
135 if (!I->isImplicitDef())
137 unsigned Reg = I->getOperand(0).getReg();
138 ImpDefRegs.insert(Reg);
139 for (const uint16_t *SubRegs = TRI->getSubRegisters(Reg);
140 unsigned SubReg = *SubRegs; ++SubRegs)
141 ImpDefRegs.insert(SubReg);
144 if (ImpDefRegs.empty())
147 MachineBasicBlock::iterator FirstTerm = I;
148 while (I != MBB->end()) {
149 if (!TII->isUnpredicatedTerminator(I))
151 // See if it uses any of the implicitly defined registers.
152 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
153 MachineOperand &MO = I->getOperand(i);
154 if (!MO.isReg() || !MO.isUse())
156 unsigned Reg = MO.getReg();
157 if (ImpDefRegs.count(Reg))
164 while (I != FirstTerm) {
165 MachineInstr *ImpDefMI = &*I;
167 MBB->erase(ImpDefMI);
173 /// OptimizeFunction - Perhaps branch folding, tail merging and other
174 /// CFG optimizations on the given function.
175 bool BranchFolder::OptimizeFunction(MachineFunction &MF,
176 const TargetInstrInfo *tii,
177 const TargetRegisterInfo *tri,
178 MachineModuleInfo *mmi) {
179 if (!tii) return false;
181 TriedMerging.clear();
187 RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
189 // Fix CFG. The later algorithms expect it to be right.
190 bool MadeChange = false;
191 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
192 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
193 SmallVector<MachineOperand, 4> Cond;
194 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
195 MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
196 MadeChange |= OptimizeImpDefsBlock(MBB);
199 bool MadeChangeThisIteration = true;
200 while (MadeChangeThisIteration) {
201 MadeChangeThisIteration = TailMergeBlocks(MF);
202 MadeChangeThisIteration |= OptimizeBranches(MF);
203 if (EnableHoistCommonCode)
204 MadeChangeThisIteration |= HoistCommonCode(MF);
205 MadeChange |= MadeChangeThisIteration;
208 // See if any jump tables have become dead as the code generator
210 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
216 // Walk the function to find jump tables that are live.
217 BitVector JTIsLive(JTI->getJumpTables().size());
218 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
220 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
222 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
223 MachineOperand &Op = I->getOperand(op);
224 if (!Op.isJTI()) continue;
226 // Remember that this JT is live.
227 JTIsLive.set(Op.getIndex());
231 // Finally, remove dead jump tables. This happens when the
232 // indirect jump was unreachable (and thus deleted).
233 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
234 if (!JTIsLive.test(i)) {
235 JTI->RemoveJumpTable(i);
243 //===----------------------------------------------------------------------===//
244 // Tail Merging of Blocks
245 //===----------------------------------------------------------------------===//
247 /// HashMachineInstr - Compute a hash value for MI and its operands.
248 static unsigned HashMachineInstr(const MachineInstr *MI) {
249 unsigned Hash = MI->getOpcode();
250 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
251 const MachineOperand &Op = MI->getOperand(i);
253 // Merge in bits from the operand if easy.
254 unsigned OperandHash = 0;
255 switch (Op.getType()) {
256 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
257 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
258 case MachineOperand::MO_MachineBasicBlock:
259 OperandHash = Op.getMBB()->getNumber();
261 case MachineOperand::MO_FrameIndex:
262 case MachineOperand::MO_ConstantPoolIndex:
263 case MachineOperand::MO_JumpTableIndex:
264 OperandHash = Op.getIndex();
266 case MachineOperand::MO_GlobalAddress:
267 case MachineOperand::MO_ExternalSymbol:
268 // Global address / external symbol are too hard, don't bother, but do
269 // pull in the offset.
270 OperandHash = Op.getOffset();
275 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
280 /// HashEndOfMBB - Hash the last instruction in the MBB.
281 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
282 MachineBasicBlock::const_iterator I = MBB->end();
283 if (I == MBB->begin())
284 return 0; // Empty MBB.
287 // Skip debug info so it will not affect codegen.
288 while (I->isDebugValue()) {
290 return 0; // MBB empty except for debug info.
294 return HashMachineInstr(I);
297 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
298 /// of instructions they actually have in common together at their end. Return
299 /// iterators for the first shared instruction in each block.
300 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
301 MachineBasicBlock *MBB2,
302 MachineBasicBlock::iterator &I1,
303 MachineBasicBlock::iterator &I2) {
307 unsigned TailLen = 0;
308 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
310 // Skip debugging pseudos; necessary to avoid changing the code.
311 while (I1->isDebugValue()) {
312 if (I1==MBB1->begin()) {
313 while (I2->isDebugValue()) {
314 if (I2==MBB2->begin())
315 // I1==DBG at begin; I2==DBG at begin
320 // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
325 // I1==first (untested) non-DBG preceding known match
326 while (I2->isDebugValue()) {
327 if (I2==MBB2->begin()) {
329 // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
334 // I1, I2==first (untested) non-DBGs preceding known match
335 if (!I1->isIdenticalTo(I2) ||
336 // FIXME: This check is dubious. It's used to get around a problem where
337 // people incorrectly expect inline asm directives to remain in the same
338 // relative order. This is untenable because normal compiler
339 // optimizations (like this one) may reorder and/or merge these
347 // Back past possible debugging pseudos at beginning of block. This matters
348 // when one block differs from the other only by whether debugging pseudos
349 // are present at the beginning. (This way, the various checks later for
350 // I1==MBB1->begin() work as expected.)
351 if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
353 while (I2->isDebugValue()) {
354 if (I2 == MBB2->begin()) {
361 if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
363 while (I1->isDebugValue()) {
364 if (I1 == MBB1->begin())
373 void BranchFolder::MaintainLiveIns(MachineBasicBlock *CurMBB,
374 MachineBasicBlock *NewMBB) {
376 RS->enterBasicBlock(CurMBB);
377 if (!CurMBB->empty())
378 RS->forward(prior(CurMBB->end()));
379 BitVector RegsLiveAtExit(TRI->getNumRegs());
380 RS->getRegsUsed(RegsLiveAtExit, false);
381 for (unsigned int i = 0, e = TRI->getNumRegs(); i != e; i++)
382 if (RegsLiveAtExit[i])
383 NewMBB->addLiveIn(i);
387 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
388 /// after it, replacing it with an unconditional branch to NewDest.
389 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
390 MachineBasicBlock *NewDest) {
391 MachineBasicBlock *CurMBB = OldInst->getParent();
393 TII->ReplaceTailWithBranchTo(OldInst, NewDest);
395 // For targets that use the register scavenger, we must maintain LiveIns.
396 MaintainLiveIns(CurMBB, NewDest);
401 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
402 /// MBB so that the part before the iterator falls into the part starting at the
403 /// iterator. This returns the new MBB.
404 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
405 MachineBasicBlock::iterator BBI1) {
406 if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
409 MachineFunction &MF = *CurMBB.getParent();
411 // Create the fall-through block.
412 MachineFunction::iterator MBBI = &CurMBB;
413 MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
414 CurMBB.getParent()->insert(++MBBI, NewMBB);
416 // Move all the successors of this block to the specified block.
417 NewMBB->transferSuccessors(&CurMBB);
419 // Add an edge from CurMBB to NewMBB for the fall-through.
420 CurMBB.addSuccessor(NewMBB);
422 // Splice the code over.
423 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
425 // For targets that use the register scavenger, we must maintain LiveIns.
426 MaintainLiveIns(&CurMBB, NewMBB);
431 /// EstimateRuntime - Make a rough estimate for how long it will take to run
432 /// the specified code.
433 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
434 MachineBasicBlock::iterator E) {
436 for (; I != E; ++I) {
437 if (I->isDebugValue())
441 else if (I->mayLoad() || I->mayStore())
449 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
450 // branches temporarily for tail merging). In the case where CurMBB ends
451 // with a conditional branch to the next block, optimize by reversing the
452 // test and conditionally branching to SuccMBB instead.
453 static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
454 const TargetInstrInfo *TII) {
455 MachineFunction *MF = CurMBB->getParent();
456 MachineFunction::iterator I = llvm::next(MachineFunction::iterator(CurMBB));
457 MachineBasicBlock *TBB = 0, *FBB = 0;
458 SmallVector<MachineOperand, 4> Cond;
459 DebugLoc dl; // FIXME: this is nowhere
460 if (I != MF->end() &&
461 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
462 MachineBasicBlock *NextBB = I;
463 if (TBB == NextBB && !Cond.empty() && !FBB) {
464 if (!TII->ReverseBranchCondition(Cond)) {
465 TII->RemoveBranch(*CurMBB);
466 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond, dl);
471 TII->InsertBranch(*CurMBB, SuccBB, NULL,
472 SmallVector<MachineOperand, 0>(), dl);
476 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
477 if (getHash() < o.getHash())
479 else if (getHash() > o.getHash())
481 else if (getBlock()->getNumber() < o.getBlock()->getNumber())
483 else if (getBlock()->getNumber() > o.getBlock()->getNumber())
486 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
487 // an object with itself.
488 #ifndef _GLIBCXX_DEBUG
489 llvm_unreachable("Predecessor appears twice");
496 /// CountTerminators - Count the number of terminators in the given
497 /// block and set I to the position of the first non-terminator, if there
498 /// is one, or MBB->end() otherwise.
499 static unsigned CountTerminators(MachineBasicBlock *MBB,
500 MachineBasicBlock::iterator &I) {
502 unsigned NumTerms = 0;
504 if (I == MBB->begin()) {
509 if (!I->isTerminator()) break;
515 /// ProfitableToMerge - Check if two machine basic blocks have a common tail
516 /// and decide if it would be profitable to merge those tails. Return the
517 /// length of the common tail and iterators to the first common instruction
519 static bool ProfitableToMerge(MachineBasicBlock *MBB1,
520 MachineBasicBlock *MBB2,
521 unsigned minCommonTailLength,
522 unsigned &CommonTailLen,
523 MachineBasicBlock::iterator &I1,
524 MachineBasicBlock::iterator &I2,
525 MachineBasicBlock *SuccBB,
526 MachineBasicBlock *PredBB) {
527 CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
528 if (CommonTailLen == 0)
530 DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
531 << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
534 // It's almost always profitable to merge any number of non-terminator
535 // instructions with the block that falls through into the common successor.
536 if (MBB1 == PredBB || MBB2 == PredBB) {
537 MachineBasicBlock::iterator I;
538 unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
539 if (CommonTailLen > NumTerms)
543 // If one of the blocks can be completely merged and happens to be in
544 // a position where the other could fall through into it, merge any number
545 // of instructions, because it can be done without a branch.
546 // TODO: If the blocks are not adjacent, move one of them so that they are?
547 if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
549 if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
552 // If both blocks have an unconditional branch temporarily stripped out,
553 // count that as an additional common instruction for the following
555 unsigned EffectiveTailLen = CommonTailLen;
556 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
557 !MBB1->back().isBarrier() &&
558 !MBB2->back().isBarrier())
561 // Check if the common tail is long enough to be worthwhile.
562 if (EffectiveTailLen >= minCommonTailLength)
565 // If we are optimizing for code size, 2 instructions in common is enough if
566 // we don't have to split a block. At worst we will be introducing 1 new
567 // branch instruction, which is likely to be smaller than the 2
568 // instructions that would be deleted in the merge.
569 MachineFunction *MF = MBB1->getParent();
570 if (EffectiveTailLen >= 2 &&
571 MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize) &&
572 (I1 == MBB1->begin() || I2 == MBB2->begin()))
578 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
579 /// hash CurHash (guaranteed to match the last element). Build the vector
580 /// SameTails of all those that have the (same) largest number of instructions
581 /// in common of any pair of these blocks. SameTails entries contain an
582 /// iterator into MergePotentials (from which the MachineBasicBlock can be
583 /// found) and a MachineBasicBlock::iterator into that MBB indicating the
584 /// instruction where the matching code sequence begins.
585 /// Order of elements in SameTails is the reverse of the order in which
586 /// those blocks appear in MergePotentials (where they are not necessarily
588 unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
589 unsigned minCommonTailLength,
590 MachineBasicBlock *SuccBB,
591 MachineBasicBlock *PredBB) {
592 unsigned maxCommonTailLength = 0U;
594 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
595 MPIterator HighestMPIter = prior(MergePotentials.end());
596 for (MPIterator CurMPIter = prior(MergePotentials.end()),
597 B = MergePotentials.begin();
598 CurMPIter != B && CurMPIter->getHash() == CurHash;
600 for (MPIterator I = prior(CurMPIter); I->getHash() == CurHash ; --I) {
601 unsigned CommonTailLen;
602 if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
604 CommonTailLen, TrialBBI1, TrialBBI2,
606 if (CommonTailLen > maxCommonTailLength) {
608 maxCommonTailLength = CommonTailLen;
609 HighestMPIter = CurMPIter;
610 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
612 if (HighestMPIter == CurMPIter &&
613 CommonTailLen == maxCommonTailLength)
614 SameTails.push_back(SameTailElt(I, TrialBBI2));
620 return maxCommonTailLength;
623 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
624 /// MergePotentials, restoring branches at ends of blocks as appropriate.
625 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
626 MachineBasicBlock *SuccBB,
627 MachineBasicBlock *PredBB) {
628 MPIterator CurMPIter, B;
629 for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
630 CurMPIter->getHash() == CurHash;
632 // Put the unconditional branch back, if we need one.
633 MachineBasicBlock *CurMBB = CurMPIter->getBlock();
634 if (SuccBB && CurMBB != PredBB)
635 FixTail(CurMBB, SuccBB, TII);
639 if (CurMPIter->getHash() != CurHash)
641 MergePotentials.erase(CurMPIter, MergePotentials.end());
644 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
645 /// only of the common tail. Create a block that does by splitting one.
646 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
647 unsigned maxCommonTailLength,
648 unsigned &commonTailIndex) {
650 unsigned TimeEstimate = ~0U;
651 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
652 // Use PredBB if possible; that doesn't require a new branch.
653 if (SameTails[i].getBlock() == PredBB) {
657 // Otherwise, make a (fairly bogus) choice based on estimate of
658 // how long it will take the various blocks to execute.
659 unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
660 SameTails[i].getTailStartPos());
661 if (t <= TimeEstimate) {
667 MachineBasicBlock::iterator BBI =
668 SameTails[commonTailIndex].getTailStartPos();
669 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
671 // If the common tail includes any debug info we will take it pretty
672 // randomly from one of the inputs. Might be better to remove it?
673 DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
674 << maxCommonTailLength);
676 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
678 DEBUG(dbgs() << "... failed!");
682 SameTails[commonTailIndex].setBlock(newMBB);
683 SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
685 // If we split PredBB, newMBB is the new predecessor.
692 // See if any of the blocks in MergePotentials (which all have a common single
693 // successor, or all have no successor) can be tail-merged. If there is a
694 // successor, any blocks in MergePotentials that are not tail-merged and
695 // are not immediately before Succ must have an unconditional branch to
696 // Succ added (but the predecessor/successor lists need no adjustment).
697 // The lone predecessor of Succ that falls through into Succ,
698 // if any, is given in PredBB.
700 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
701 MachineBasicBlock *PredBB) {
702 bool MadeChange = false;
704 // Except for the special cases below, tail-merge if there are at least
705 // this many instructions in common.
706 unsigned minCommonTailLength = TailMergeSize;
708 DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
709 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
710 dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
711 << (i == e-1 ? "" : ", ");
714 dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n';
716 dbgs() << " which has fall-through from BB#"
717 << PredBB->getNumber() << "\n";
719 dbgs() << "Looking for common tails of at least "
720 << minCommonTailLength << " instruction"
721 << (minCommonTailLength == 1 ? "" : "s") << '\n';
724 // Sort by hash value so that blocks with identical end sequences sort
726 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
728 // Walk through equivalence sets looking for actual exact matches.
729 while (MergePotentials.size() > 1) {
730 unsigned CurHash = MergePotentials.back().getHash();
732 // Build SameTails, identifying the set of blocks with this hash code
733 // and with the maximum number of instructions in common.
734 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
738 // If we didn't find any pair that has at least minCommonTailLength
739 // instructions in common, remove all blocks with this hash code and retry.
740 if (SameTails.empty()) {
741 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
745 // If one of the blocks is the entire common tail (and not the entry
746 // block, which we can't jump to), we can treat all blocks with this same
747 // tail at once. Use PredBB if that is one of the possibilities, as that
748 // will not introduce any extra branches.
749 MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
750 getParent()->begin();
751 unsigned commonTailIndex = SameTails.size();
752 // If there are two blocks, check to see if one can be made to fall through
754 if (SameTails.size() == 2 &&
755 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
756 SameTails[1].tailIsWholeBlock())
758 else if (SameTails.size() == 2 &&
759 SameTails[1].getBlock()->isLayoutSuccessor(
760 SameTails[0].getBlock()) &&
761 SameTails[0].tailIsWholeBlock())
764 // Otherwise just pick one, favoring the fall-through predecessor if
766 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
767 MachineBasicBlock *MBB = SameTails[i].getBlock();
768 if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
774 if (SameTails[i].tailIsWholeBlock())
779 if (commonTailIndex == SameTails.size() ||
780 (SameTails[commonTailIndex].getBlock() == PredBB &&
781 !SameTails[commonTailIndex].tailIsWholeBlock())) {
782 // None of the blocks consist entirely of the common tail.
783 // Split a block so that one does.
784 if (!CreateCommonTailOnlyBlock(PredBB,
785 maxCommonTailLength, commonTailIndex)) {
786 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
791 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
792 // MBB is common tail. Adjust all other BB's to jump to this one.
793 // Traversal must be forwards so erases work.
794 DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
796 for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
797 if (commonTailIndex == i)
799 DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
800 << (i == e-1 ? "" : ", "));
801 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
802 ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
803 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
804 MergePotentials.erase(SameTails[i].getMPIter());
806 DEBUG(dbgs() << "\n");
807 // We leave commonTailIndex in the worklist in case there are other blocks
808 // that match it with a smaller number of instructions.
814 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
816 if (!EnableTailMerge) return false;
818 bool MadeChange = false;
820 // First find blocks with no successors.
821 MergePotentials.clear();
822 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
823 I != E && MergePotentials.size() < TailMergeThreshold; ++I) {
824 if (TriedMerging.count(I))
827 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I));
830 // If this is a large problem, avoid visiting the same basic blocks
832 if (MergePotentials.size() == TailMergeThreshold)
833 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
834 TriedMerging.insert(MergePotentials[i].getBlock());
835 // See if we can do any tail merging on those.
836 if (MergePotentials.size() >= 2)
837 MadeChange |= TryTailMergeBlocks(NULL, NULL);
839 // Look at blocks (IBB) with multiple predecessors (PBB).
840 // We change each predecessor to a canonical form, by
841 // (1) temporarily removing any unconditional branch from the predecessor
843 // (2) alter conditional branches so they branch to the other block
844 // not IBB; this may require adding back an unconditional branch to IBB
845 // later, where there wasn't one coming in. E.g.
847 // fallthrough to QBB
850 // with a conceptual B to IBB after that, which never actually exists.
851 // With those changes, we see whether the predecessors' tails match,
852 // and merge them if so. We change things out of canonical form and
853 // back to the way they were later in the process. (OptimizeBranches
854 // would undo some of this, but we can't use it, because we'd get into
855 // a compile-time infinite loop repeatedly doing and undoing the same
858 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
860 if (I->pred_size() >= 2) {
861 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
862 MachineBasicBlock *IBB = I;
863 MachineBasicBlock *PredBB = prior(I);
864 MergePotentials.clear();
865 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
867 P != E2 && MergePotentials.size() < TailMergeThreshold; ++P) {
868 MachineBasicBlock *PBB = *P;
869 if (TriedMerging.count(PBB))
871 // Skip blocks that loop to themselves, can't tail merge these.
874 // Visit each predecessor only once.
875 if (!UniquePreds.insert(PBB))
877 // Skip blocks which may jump to a landing pad. Can't tail merge these.
878 if (PBB->getLandingPadSuccessor())
880 MachineBasicBlock *TBB = 0, *FBB = 0;
881 SmallVector<MachineOperand, 4> Cond;
882 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
883 // Failing case: IBB is the target of a cbr, and
884 // we cannot reverse the branch.
885 SmallVector<MachineOperand, 4> NewCond(Cond);
886 if (!Cond.empty() && TBB == IBB) {
887 if (TII->ReverseBranchCondition(NewCond))
889 // This is the QBB case described above
891 FBB = llvm::next(MachineFunction::iterator(PBB));
893 // Failing case: the only way IBB can be reached from PBB is via
894 // exception handling. Happens for landing pads. Would be nice
895 // to have a bit in the edge so we didn't have to do all this.
896 if (IBB->isLandingPad()) {
897 MachineFunction::iterator IP = PBB; IP++;
898 MachineBasicBlock *PredNextBB = NULL;
902 if (IBB != PredNextBB) // fallthrough
905 if (TBB != IBB && FBB != IBB) // cbr then ubr
907 } else if (Cond.empty()) {
908 if (TBB != IBB) // ubr
911 if (TBB != IBB && IBB != PredNextBB) // cbr
915 // Remove the unconditional branch at the end, if any.
916 if (TBB && (Cond.empty() || FBB)) {
917 DebugLoc dl; // FIXME: this is nowhere
918 TII->RemoveBranch(*PBB);
920 // reinsert conditional branch only, for now
921 TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, 0, NewCond, dl);
923 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB), *P));
926 // If this is a large problem, avoid visiting the same basic blocks
928 if (MergePotentials.size() == TailMergeThreshold)
929 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
930 TriedMerging.insert(MergePotentials[i].getBlock());
931 if (MergePotentials.size() >= 2)
932 MadeChange |= TryTailMergeBlocks(IBB, PredBB);
933 // Reinsert an unconditional branch if needed.
934 // The 1 below can occur as a result of removing blocks in
935 // TryTailMergeBlocks.
936 PredBB = prior(I); // this may have been changed in TryTailMergeBlocks
937 if (MergePotentials.size() == 1 &&
938 MergePotentials.begin()->getBlock() != PredBB)
939 FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
945 //===----------------------------------------------------------------------===//
946 // Branch Optimization
947 //===----------------------------------------------------------------------===//
949 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
950 bool MadeChange = false;
952 // Make sure blocks are numbered in order
955 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
957 MachineBasicBlock *MBB = I++;
958 MadeChange |= OptimizeBlock(MBB);
960 // If it is dead, remove it.
961 if (MBB->pred_empty()) {
962 RemoveDeadBlock(MBB);
970 // Blocks should be considered empty if they contain only debug info;
971 // else the debug info would affect codegen.
972 static bool IsEmptyBlock(MachineBasicBlock *MBB) {
975 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
976 MBBI!=MBBE; ++MBBI) {
977 if (!MBBI->isDebugValue())
983 // Blocks with only debug info and branches should be considered the same
984 // as blocks with only branches.
985 static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
986 MachineBasicBlock::iterator MBBI, MBBE;
987 for (MBBI = MBB->begin(), MBBE = MBB->end(); MBBI!=MBBE; ++MBBI) {
988 if (!MBBI->isDebugValue())
991 return (MBBI->isBranch());
994 /// IsBetterFallthrough - Return true if it would be clearly better to
995 /// fall-through to MBB1 than to fall through into MBB2. This has to return
996 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
997 /// result in infinite loops.
998 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
999 MachineBasicBlock *MBB2) {
1000 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
1001 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
1002 // optimize branches that branch to either a return block or an assert block
1003 // into a fallthrough to the return.
1004 if (IsEmptyBlock(MBB1) || IsEmptyBlock(MBB2)) return false;
1006 // If there is a clear successor ordering we make sure that one block
1007 // will fall through to the next
1008 if (MBB1->isSuccessor(MBB2)) return true;
1009 if (MBB2->isSuccessor(MBB1)) return false;
1011 // Neither block consists entirely of debug info (per IsEmptyBlock check),
1012 // so we needn't test for falling off the beginning here.
1013 MachineBasicBlock::iterator MBB1I = --MBB1->end();
1014 while (MBB1I->isDebugValue())
1016 MachineBasicBlock::iterator MBB2I = --MBB2->end();
1017 while (MBB2I->isDebugValue())
1019 return MBB2I->isCall() && !MBB1I->isCall();
1022 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1023 /// instructions on the block. Always use the DebugLoc of the first
1024 /// branching instruction found unless its absent, in which case use the
1025 /// DebugLoc of the second if present.
1026 static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
1027 MachineBasicBlock::iterator I = MBB.end();
1028 if (I == MBB.begin())
1031 while (I->isDebugValue() && I != MBB.begin())
1034 return I->getDebugLoc();
1038 /// OptimizeBlock - Analyze and optimize control flow related to the specified
1039 /// block. This is never called on the entry block.
1040 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1041 bool MadeChange = false;
1042 MachineFunction &MF = *MBB->getParent();
1045 MachineFunction::iterator FallThrough = MBB;
1048 // If this block is empty, make everyone use its fall-through, not the block
1049 // explicitly. Landing pads should not do this since the landing-pad table
1050 // points to this block. Blocks with their addresses taken shouldn't be
1052 if (IsEmptyBlock(MBB) && !MBB->isLandingPad() && !MBB->hasAddressTaken()) {
1053 // Dead block? Leave for cleanup later.
1054 if (MBB->pred_empty()) return MadeChange;
1056 if (FallThrough == MF.end()) {
1057 // TODO: Simplify preds to not branch here if possible!
1059 // Rewrite all predecessors of the old block to go to the fallthrough
1061 while (!MBB->pred_empty()) {
1062 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1063 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
1065 // If MBB was the target of a jump table, update jump tables to go to the
1066 // fallthrough instead.
1067 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1068 MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
1074 // Check to see if we can simplify the terminator of the block before this
1076 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
1078 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
1079 SmallVector<MachineOperand, 4> PriorCond;
1080 bool PriorUnAnalyzable =
1081 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1082 if (!PriorUnAnalyzable) {
1083 // If the CFG for the prior block has extra edges, remove them.
1084 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1085 !PriorCond.empty());
1087 // If the previous branch is conditional and both conditions go to the same
1088 // destination, remove the branch, replacing it with an unconditional one or
1090 if (PriorTBB && PriorTBB == PriorFBB) {
1091 DebugLoc dl = getBranchDebugLoc(PrevBB);
1092 TII->RemoveBranch(PrevBB);
1094 if (PriorTBB != MBB)
1095 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond, dl);
1098 goto ReoptimizeBlock;
1101 // If the previous block unconditionally falls through to this block and
1102 // this block has no other predecessors, move the contents of this block
1103 // into the prior block. This doesn't usually happen when SimplifyCFG
1104 // has been used, but it can happen if tail merging splits a fall-through
1105 // predecessor of a block.
1106 // This has to check PrevBB->succ_size() because EH edges are ignored by
1108 if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1109 PrevBB.succ_size() == 1 &&
1110 !MBB->hasAddressTaken() && !MBB->isLandingPad()) {
1111 DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1112 << "From MBB: " << *MBB);
1113 // Remove redundant DBG_VALUEs first.
1114 if (PrevBB.begin() != PrevBB.end()) {
1115 MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1117 MachineBasicBlock::iterator MBBIter = MBB->begin();
1118 // Check if DBG_VALUE at the end of PrevBB is identical to the
1119 // DBG_VALUE at the beginning of MBB.
1120 while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1121 && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1122 if (!MBBIter->isIdenticalTo(PrevBBIter))
1124 MachineInstr *DuplicateDbg = MBBIter;
1125 ++MBBIter; -- PrevBBIter;
1126 DuplicateDbg->eraseFromParent();
1129 PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1130 PrevBB.removeSuccessor(PrevBB.succ_begin());
1131 assert(PrevBB.succ_empty());
1132 PrevBB.transferSuccessors(MBB);
1137 // If the previous branch *only* branches to *this* block (conditional or
1138 // not) remove the branch.
1139 if (PriorTBB == MBB && PriorFBB == 0) {
1140 TII->RemoveBranch(PrevBB);
1143 goto ReoptimizeBlock;
1146 // If the prior block branches somewhere else on the condition and here if
1147 // the condition is false, remove the uncond second branch.
1148 if (PriorFBB == MBB) {
1149 DebugLoc dl = getBranchDebugLoc(PrevBB);
1150 TII->RemoveBranch(PrevBB);
1151 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond, dl);
1154 goto ReoptimizeBlock;
1157 // If the prior block branches here on true and somewhere else on false, and
1158 // if the branch condition is reversible, reverse the branch to create a
1160 if (PriorTBB == MBB) {
1161 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1162 if (!TII->ReverseBranchCondition(NewPriorCond)) {
1163 DebugLoc dl = getBranchDebugLoc(PrevBB);
1164 TII->RemoveBranch(PrevBB);
1165 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond, dl);
1168 goto ReoptimizeBlock;
1172 // If this block has no successors (e.g. it is a return block or ends with
1173 // a call to a no-return function like abort or __cxa_throw) and if the pred
1174 // falls through into this block, and if it would otherwise fall through
1175 // into the block after this, move this block to the end of the function.
1177 // We consider it more likely that execution will stay in the function (e.g.
1178 // due to loops) than it is to exit it. This asserts in loops etc, moving
1179 // the assert condition out of the loop body.
1180 if (MBB->succ_empty() && !PriorCond.empty() && PriorFBB == 0 &&
1181 MachineFunction::iterator(PriorTBB) == FallThrough &&
1182 !MBB->canFallThrough()) {
1183 bool DoTransform = true;
1185 // We have to be careful that the succs of PredBB aren't both no-successor
1186 // blocks. If neither have successors and if PredBB is the second from
1187 // last block in the function, we'd just keep swapping the two blocks for
1188 // last. Only do the swap if one is clearly better to fall through than
1190 if (FallThrough == --MF.end() &&
1191 !IsBetterFallthrough(PriorTBB, MBB))
1192 DoTransform = false;
1195 // Reverse the branch so we will fall through on the previous true cond.
1196 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1197 if (!TII->ReverseBranchCondition(NewPriorCond)) {
1198 DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1199 << "To make fallthrough to: " << *PriorTBB << "\n");
1201 DebugLoc dl = getBranchDebugLoc(PrevBB);
1202 TII->RemoveBranch(PrevBB);
1203 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond, dl);
1205 // Move this block to the end of the function.
1206 MBB->moveAfter(--MF.end());
1215 // Analyze the branch in the current block.
1216 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
1217 SmallVector<MachineOperand, 4> CurCond;
1218 bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1219 if (!CurUnAnalyzable) {
1220 // If the CFG for the prior block has extra edges, remove them.
1221 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1223 // If this is a two-way branch, and the FBB branches to this block, reverse
1224 // the condition so the single-basic-block loop is faster. Instead of:
1225 // Loop: xxx; jcc Out; jmp Loop
1227 // Loop: xxx; jncc Loop; jmp Out
1228 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1229 SmallVector<MachineOperand, 4> NewCond(CurCond);
1230 if (!TII->ReverseBranchCondition(NewCond)) {
1231 DebugLoc dl = getBranchDebugLoc(*MBB);
1232 TII->RemoveBranch(*MBB);
1233 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
1236 goto ReoptimizeBlock;
1240 // If this branch is the only thing in its block, see if we can forward
1241 // other blocks across it.
1242 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
1243 IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1244 !MBB->hasAddressTaken()) {
1245 DebugLoc dl = getBranchDebugLoc(*MBB);
1246 // This block may contain just an unconditional branch. Because there can
1247 // be 'non-branch terminators' in the block, try removing the branch and
1248 // then seeing if the block is empty.
1249 TII->RemoveBranch(*MBB);
1250 // If the only things remaining in the block are debug info, remove these
1251 // as well, so this will behave the same as an empty block in non-debug
1253 if (!MBB->empty()) {
1254 bool NonDebugInfoFound = false;
1255 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
1257 if (!I->isDebugValue()) {
1258 NonDebugInfoFound = true;
1262 if (!NonDebugInfoFound)
1263 // Make the block empty, losing the debug info (we could probably
1264 // improve this in some cases.)
1265 MBB->erase(MBB->begin(), MBB->end());
1267 // If this block is just an unconditional branch to CurTBB, we can
1268 // usually completely eliminate the block. The only case we cannot
1269 // completely eliminate the block is when the block before this one
1270 // falls through into MBB and we can't understand the prior block's branch
1273 bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1274 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1275 !PrevBB.isSuccessor(MBB)) {
1276 // If the prior block falls through into us, turn it into an
1277 // explicit branch to us to make updates simpler.
1278 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1279 PriorTBB != MBB && PriorFBB != MBB) {
1280 if (PriorTBB == 0) {
1281 assert(PriorCond.empty() && PriorFBB == 0 &&
1282 "Bad branch analysis");
1285 assert(PriorFBB == 0 && "Machine CFG out of date!");
1288 DebugLoc pdl = getBranchDebugLoc(PrevBB);
1289 TII->RemoveBranch(PrevBB);
1290 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1293 // Iterate through all the predecessors, revectoring each in-turn.
1295 bool DidChange = false;
1296 bool HasBranchToSelf = false;
1297 while(PI != MBB->pred_size()) {
1298 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1300 // If this block has an uncond branch to itself, leave it.
1302 HasBranchToSelf = true;
1305 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1306 // If this change resulted in PMBB ending in a conditional
1307 // branch where both conditions go to the same destination,
1308 // change this to an unconditional branch (and fix the CFG).
1309 MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
1310 SmallVector<MachineOperand, 4> NewCurCond;
1311 bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1312 NewCurFBB, NewCurCond, true);
1313 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1314 DebugLoc pdl = getBranchDebugLoc(*PMBB);
1315 TII->RemoveBranch(*PMBB);
1317 TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond, pdl);
1320 PMBB->CorrectExtraCFGEdges(NewCurTBB, 0, false);
1325 // Change any jumptables to go to the new MBB.
1326 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1327 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1331 if (!HasBranchToSelf) return MadeChange;
1336 // Add the branch back if the block is more than just an uncond branch.
1337 TII->InsertBranch(*MBB, CurTBB, 0, CurCond, dl);
1341 // If the prior block doesn't fall through into this block, and if this
1342 // block doesn't fall through into some other block, see if we can find a
1343 // place to move this block where a fall-through will happen.
1344 if (!PrevBB.canFallThrough()) {
1346 // Now we know that there was no fall-through into this block, check to
1347 // see if it has a fall-through into its successor.
1348 bool CurFallsThru = MBB->canFallThrough();
1350 if (!MBB->isLandingPad()) {
1351 // Check all the predecessors of this block. If one of them has no fall
1352 // throughs, move this block right after it.
1353 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1354 E = MBB->pred_end(); PI != E; ++PI) {
1355 // Analyze the branch at the end of the pred.
1356 MachineBasicBlock *PredBB = *PI;
1357 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1358 MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
1359 SmallVector<MachineOperand, 4> PredCond;
1360 if (PredBB != MBB && !PredBB->canFallThrough() &&
1361 !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)
1362 && (!CurFallsThru || !CurTBB || !CurFBB)
1363 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1364 // If the current block doesn't fall through, just move it.
1365 // If the current block can fall through and does not end with a
1366 // conditional branch, we need to append an unconditional jump to
1367 // the (current) next block. To avoid a possible compile-time
1368 // infinite loop, move blocks only backward in this case.
1369 // Also, if there are already 2 branches here, we cannot add a third;
1370 // this means we have the case
1375 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1377 TII->InsertBranch(*MBB, NextBB, 0, CurCond, DebugLoc());
1379 MBB->moveAfter(PredBB);
1381 goto ReoptimizeBlock;
1386 if (!CurFallsThru) {
1387 // Check all successors to see if we can move this block before it.
1388 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1389 E = MBB->succ_end(); SI != E; ++SI) {
1390 // Analyze the branch at the end of the block before the succ.
1391 MachineBasicBlock *SuccBB = *SI;
1392 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1394 // If this block doesn't already fall-through to that successor, and if
1395 // the succ doesn't already have a block that can fall through into it,
1396 // and if the successor isn't an EH destination, we can arrange for the
1397 // fallthrough to happen.
1398 if (SuccBB != MBB && &*SuccPrev != MBB &&
1399 !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1400 !SuccBB->isLandingPad()) {
1401 MBB->moveBefore(SuccBB);
1403 goto ReoptimizeBlock;
1407 // Okay, there is no really great place to put this block. If, however,
1408 // the block before this one would be a fall-through if this block were
1409 // removed, move this block to the end of the function.
1410 MachineBasicBlock *PrevTBB = 0, *PrevFBB = 0;
1411 SmallVector<MachineOperand, 4> PrevCond;
1412 if (FallThrough != MF.end() &&
1413 !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
1414 PrevBB.isSuccessor(FallThrough)) {
1415 MBB->moveAfter(--MF.end());
1425 //===----------------------------------------------------------------------===//
1426 // Hoist Common Code
1427 //===----------------------------------------------------------------------===//
1429 /// HoistCommonCode - Hoist common instruction sequences at the start of basic
1430 /// blocks to their common predecessor.
1431 bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1432 bool MadeChange = false;
1433 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
1434 MachineBasicBlock *MBB = I++;
1435 MadeChange |= HoistCommonCodeInSuccs(MBB);
1441 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1442 /// its 'true' successor.
1443 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1444 MachineBasicBlock *TrueBB) {
1445 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1446 E = BB->succ_end(); SI != E; ++SI) {
1447 MachineBasicBlock *SuccBB = *SI;
1448 if (SuccBB != TrueBB)
1454 /// findHoistingInsertPosAndDeps - Find the location to move common instructions
1455 /// in successors to. The location is ususally just before the terminator,
1456 /// however if the terminator is a conditional branch and its previous
1457 /// instruction is the flag setting instruction, the previous instruction is
1458 /// the preferred location. This function also gathers uses and defs of the
1459 /// instructions from the insertion point to the end of the block. The data is
1460 /// used by HoistCommonCodeInSuccs to ensure safety.
1462 MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1463 const TargetInstrInfo *TII,
1464 const TargetRegisterInfo *TRI,
1465 SmallSet<unsigned,4> &Uses,
1466 SmallSet<unsigned,4> &Defs) {
1467 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1468 if (!TII->isUnpredicatedTerminator(Loc))
1471 for (unsigned i = 0, e = Loc->getNumOperands(); i != e; ++i) {
1472 const MachineOperand &MO = Loc->getOperand(i);
1475 unsigned Reg = MO.getReg();
1480 for (const uint16_t *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1482 } else if (!MO.isDead())
1483 // Don't try to hoist code in the rare case the terminator defines a
1484 // register that is later used.
1490 if (Loc == MBB->begin())
1493 // The terminator is probably a conditional branch, try not to separate the
1494 // branch from condition setting instruction.
1495 MachineBasicBlock::iterator PI = Loc;
1497 while (PI != MBB->begin() && Loc->isDebugValue())
1501 for (unsigned i = 0, e = PI->getNumOperands(); !IsDef && i != e; ++i) {
1502 const MachineOperand &MO = PI->getOperand(i);
1503 // If PI has a regmask operand, it is probably a call. Separate away.
1506 if (!MO.isReg() || MO.isUse())
1508 unsigned Reg = MO.getReg();
1511 if (Uses.count(Reg))
1515 // The condition setting instruction is not just before the conditional
1519 // Be conservative, don't insert instruction above something that may have
1520 // side-effects. And since it's potentially bad to separate flag setting
1521 // instruction from the conditional branch, just abort the optimization
1523 // Also avoid moving code above predicated instruction since it's hard to
1524 // reason about register liveness with predicated instruction.
1525 bool DontMoveAcrossStore = true;
1526 if (!PI->isSafeToMove(TII, 0, DontMoveAcrossStore) ||
1527 TII->isPredicated(PI))
1531 // Find out what registers are live. Note this routine is ignoring other live
1532 // registers which are only used by instructions in successor blocks.
1533 for (unsigned i = 0, e = PI->getNumOperands(); i != e; ++i) {
1534 const MachineOperand &MO = PI->getOperand(i);
1537 unsigned Reg = MO.getReg();
1542 for (const uint16_t *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1545 if (Uses.count(Reg)) {
1547 for (const uint16_t *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1548 Uses.erase(*SR); // Use getSubRegisters to be conservative
1551 for (const uint16_t *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1559 /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
1560 /// sequence at the start of the function, move the instructions before MBB
1561 /// terminator if it's legal.
1562 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1563 MachineBasicBlock *TBB = 0, *FBB = 0;
1564 SmallVector<MachineOperand, 4> Cond;
1565 if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
1568 if (!FBB) FBB = findFalseBlock(MBB, TBB);
1570 // Malformed bcc? True and false blocks are the same?
1573 // Restrict the optimization to cases where MBB is the only predecessor,
1574 // it is an obvious win.
1575 if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1578 // Find a suitable position to hoist the common instructions to. Also figure
1579 // out which registers are used or defined by instructions from the insertion
1580 // point to the end of the block.
1581 SmallSet<unsigned, 4> Uses, Defs;
1582 MachineBasicBlock::iterator Loc =
1583 findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1584 if (Loc == MBB->end())
1587 bool HasDups = false;
1588 SmallVector<unsigned, 4> LocalDefs;
1589 SmallSet<unsigned, 4> LocalDefsSet;
1590 MachineBasicBlock::iterator TIB = TBB->begin();
1591 MachineBasicBlock::iterator FIB = FBB->begin();
1592 MachineBasicBlock::iterator TIE = TBB->end();
1593 MachineBasicBlock::iterator FIE = FBB->end();
1594 while (TIB != TIE && FIB != FIE) {
1595 // Skip dbg_value instructions. These do not count.
1596 if (TIB->isDebugValue()) {
1597 while (TIB != TIE && TIB->isDebugValue())
1602 if (FIB->isDebugValue()) {
1603 while (FIB != FIE && FIB->isDebugValue())
1608 if (!TIB->isIdenticalTo(FIB, MachineInstr::CheckKillDead))
1611 if (TII->isPredicated(TIB))
1612 // Hard to reason about register liveness with predicated instruction.
1616 for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1617 MachineOperand &MO = TIB->getOperand(i);
1618 // Don't attempt to hoist instructions with register masks.
1619 if (MO.isRegMask()) {
1625 unsigned Reg = MO.getReg();
1629 if (Uses.count(Reg)) {
1630 // Avoid clobbering a register that's used by the instruction at
1631 // the point of insertion.
1636 if (Defs.count(Reg) && !MO.isDead()) {
1637 // Don't hoist the instruction if the def would be clobber by the
1638 // instruction at the point insertion. FIXME: This is overly
1639 // conservative. It should be possible to hoist the instructions
1640 // in BB2 in the following example:
1642 // r1, eflag = op1 r2, r3
1651 } else if (!LocalDefsSet.count(Reg)) {
1652 if (Defs.count(Reg)) {
1653 // Use is defined by the instruction at the point of insertion.
1658 if (MO.isKill() && Uses.count(Reg))
1659 // Kills a register that's read by the instruction at the point of
1660 // insertion. Remove the kill marker.
1661 MO.setIsKill(false);
1667 bool DontMoveAcrossStore = true;
1668 if (!TIB->isSafeToMove(TII, 0, DontMoveAcrossStore))
1671 // Remove kills from LocalDefsSet, these registers had short live ranges.
1672 for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1673 MachineOperand &MO = TIB->getOperand(i);
1674 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1676 unsigned Reg = MO.getReg();
1677 if (!Reg || !LocalDefsSet.count(Reg))
1679 for (const uint16_t *OR = TRI->getOverlaps(Reg); *OR; ++OR)
1680 LocalDefsSet.erase(*OR);
1683 // Track local defs so we can update liveins.
1684 for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1685 MachineOperand &MO = TIB->getOperand(i);
1686 if (!MO.isReg() || !MO.isDef() || MO.isDead())
1688 unsigned Reg = MO.getReg();
1691 LocalDefs.push_back(Reg);
1692 for (const uint16_t *OR = TRI->getOverlaps(Reg); *OR; ++OR)
1693 LocalDefsSet.insert(*OR);
1704 MBB->splice(Loc, TBB, TBB->begin(), TIB);
1705 FBB->erase(FBB->begin(), FIB);
1708 for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
1709 unsigned Def = LocalDefs[i];
1710 if (LocalDefsSet.count(Def)) {
1711 TBB->addLiveIn(Def);
1712 FBB->addLiveIn(Def);