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 "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
36 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
37 STATISTIC(NumBranchOpts, "Number of branches optimized");
38 STATISTIC(NumTailMerge , "Number of block tails merged");
39 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
40 cl::init(cl::BOU_UNSET), cl::Hidden);
42 // Throttle for huge numbers of predecessors (compile speed problems)
43 static cl::opt<unsigned>
44 TailMergeThreshold("tail-merge-threshold",
45 cl::desc("Max number of predecessors to consider tail merging"),
46 cl::init(100), cl::Hidden);
48 struct VISIBILITY_HIDDEN BranchFolder : public MachineFunctionPass {
50 explicit BranchFolder(bool defaultEnableTailMerge) :
51 MachineFunctionPass((intptr_t)&ID) {
52 switch (FlagEnableTailMerge) {
53 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
54 case cl::BOU_TRUE: EnableTailMerge = true; break;
55 case cl::BOU_FALSE: EnableTailMerge = false; break;
59 virtual bool runOnMachineFunction(MachineFunction &MF);
60 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
61 const TargetInstrInfo *TII;
62 MachineModuleInfo *MMI;
67 bool TailMergeBlocks(MachineFunction &MF);
68 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
69 MachineBasicBlock* PredBB);
70 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
71 MachineBasicBlock *NewDest);
72 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
73 MachineBasicBlock::iterator BBI1);
74 unsigned ComputeSameTails(unsigned CurHash, unsigned minCommonTailLength);
75 void RemoveBlocksWithHash(unsigned CurHash, MachineBasicBlock* SuccBB,
76 MachineBasicBlock* PredBB);
78 typedef std::pair<unsigned,MachineBasicBlock*> MergePotentialsElt;
79 typedef std::vector<MergePotentialsElt>::iterator MPIterator;
80 std::vector<MergePotentialsElt> MergePotentials;
81 typedef std::pair<MPIterator, MachineBasicBlock::iterator> SameTailElt;
82 std::vector<SameTailElt> SameTails;
84 const TargetRegisterInfo *RegInfo;
87 bool OptimizeBranches(MachineFunction &MF);
88 void OptimizeBlock(MachineBasicBlock *MBB);
89 void RemoveDeadBlock(MachineBasicBlock *MBB);
90 bool OptimizeImpDefsBlock(MachineBasicBlock *MBB);
92 bool CanFallThrough(MachineBasicBlock *CurBB);
93 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
94 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
95 const std::vector<MachineOperand> &Cond);
97 char BranchFolder::ID = 0;
100 FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
101 return new BranchFolder(DefaultEnableTailMerge); }
103 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
104 /// function, updating the CFG.
105 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
106 assert(MBB->pred_empty() && "MBB must be dead!");
107 DOUT << "\nRemoving MBB: " << *MBB;
109 MachineFunction *MF = MBB->getParent();
110 // drop all successors.
111 while (!MBB->succ_empty())
112 MBB->removeSuccessor(MBB->succ_end()-1);
114 // If there is DWARF info to active, check to see if there are any LABEL
115 // records in the basic block. If so, unregister them from MachineModuleInfo.
116 if (MMI && !MBB->empty()) {
117 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
119 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
120 // The label ID # is always operand #0, an immediate.
121 MMI->InvalidateLabel(I->getOperand(0).getImm());
127 MF->getBasicBlockList().erase(MBB);
130 /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
131 /// followed by terminators, and if the implicitly defined registers are not
132 /// used by the terminators, remove those implicit_def's. e.g.
134 /// r0 = implicit_def
135 /// r1 = implicit_def
137 /// This block can be optimized away later if the implicit instructions are
139 bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
140 SmallSet<unsigned, 4> ImpDefRegs;
141 MachineBasicBlock::iterator I = MBB->begin();
142 while (I != MBB->end()) {
143 if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
145 unsigned Reg = I->getOperand(0).getReg();
146 ImpDefRegs.insert(Reg);
147 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
148 unsigned SubReg = *SubRegs; ++SubRegs)
149 ImpDefRegs.insert(SubReg);
152 if (ImpDefRegs.empty())
155 MachineBasicBlock::iterator FirstTerm = I;
156 while (I != MBB->end()) {
157 if (!TII->isUnpredicatedTerminator(I))
159 // See if it uses any of the implicitly defined registers.
160 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
161 MachineOperand &MO = I->getOperand(i);
162 if (!MO.isReg() || !MO.isUse())
164 unsigned Reg = MO.getReg();
165 if (ImpDefRegs.count(Reg))
172 while (I != FirstTerm) {
173 MachineInstr *ImpDefMI = &*I;
175 MBB->erase(ImpDefMI);
181 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
182 TII = MF.getTarget().getInstrInfo();
183 if (!TII) return false;
185 RegInfo = MF.getTarget().getRegisterInfo();
187 // Fix CFG. The later algorithms expect it to be right.
188 bool EverMadeChange = false;
189 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
190 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
191 std::vector<MachineOperand> Cond;
192 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
193 EverMadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
194 EverMadeChange |= OptimizeImpDefsBlock(MBB);
197 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
199 MMI = getAnalysisToUpdate<MachineModuleInfo>();
201 bool MadeChangeThisIteration = true;
202 while (MadeChangeThisIteration) {
203 MadeChangeThisIteration = false;
204 MadeChangeThisIteration |= TailMergeBlocks(MF);
205 MadeChangeThisIteration |= OptimizeBranches(MF);
206 EverMadeChange |= MadeChangeThisIteration;
209 // See if any jump tables have become mergable or dead as the code generator
211 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
212 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
214 // Figure out how these jump tables should be merged.
215 std::vector<unsigned> JTMapping;
216 JTMapping.reserve(JTs.size());
218 // We always keep the 0th jump table.
219 JTMapping.push_back(0);
221 // Scan the jump tables, seeing if there are any duplicates. Note that this
222 // is N^2, which should be fixed someday.
223 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
224 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
226 // If a jump table was merge with another one, walk the function rewriting
227 // references to jump tables to reference the new JT ID's. Keep track of
228 // whether we see a jump table idx, if not, we can delete the JT.
229 BitVector JTIsLive(JTs.size());
230 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
232 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
234 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
235 MachineOperand &Op = I->getOperand(op);
236 if (!Op.isJumpTableIndex()) continue;
237 unsigned NewIdx = JTMapping[Op.getIndex()];
240 // Remember that this JT is live.
241 JTIsLive.set(NewIdx);
245 // Finally, remove dead jump tables. This happens either because the
246 // indirect jump was unreachable (and thus deleted) or because the jump
247 // table was merged with some other one.
248 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
249 if (!JTIsLive.test(i)) {
250 JTI->RemoveJumpTable(i);
251 EverMadeChange = true;
256 return EverMadeChange;
259 //===----------------------------------------------------------------------===//
260 // Tail Merging of Blocks
261 //===----------------------------------------------------------------------===//
263 /// HashMachineInstr - Compute a hash value for MI and its operands.
264 static unsigned HashMachineInstr(const MachineInstr *MI) {
265 unsigned Hash = MI->getOpcode();
266 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
267 const MachineOperand &Op = MI->getOperand(i);
269 // Merge in bits from the operand if easy.
270 unsigned OperandHash = 0;
271 switch (Op.getType()) {
272 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
273 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
274 case MachineOperand::MO_MachineBasicBlock:
275 OperandHash = Op.getMBB()->getNumber();
277 case MachineOperand::MO_FrameIndex:
278 case MachineOperand::MO_ConstantPoolIndex:
279 case MachineOperand::MO_JumpTableIndex:
280 OperandHash = Op.getIndex();
282 case MachineOperand::MO_GlobalAddress:
283 case MachineOperand::MO_ExternalSymbol:
284 // Global address / external symbol are too hard, don't bother, but do
285 // pull in the offset.
286 OperandHash = Op.getOffset();
291 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
296 /// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
297 /// with no successors, we hash two instructions, because cross-jumping
298 /// only saves code when at least two instructions are removed (since a
299 /// branch must be inserted). For blocks with a successor, one of the
300 /// two blocks to be tail-merged will end with a branch already, so
301 /// it gains to cross-jump even for one instruction.
303 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
304 unsigned minCommonTailLength) {
305 MachineBasicBlock::const_iterator I = MBB->end();
306 if (I == MBB->begin())
307 return 0; // Empty MBB.
310 unsigned Hash = HashMachineInstr(I);
312 if (I == MBB->begin() || minCommonTailLength == 1)
313 return Hash; // Single instr MBB.
316 // Hash in the second-to-last instruction.
317 Hash ^= HashMachineInstr(I) << 2;
321 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
322 /// of instructions they actually have in common together at their end. Return
323 /// iterators for the first shared instruction in each block.
324 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
325 MachineBasicBlock *MBB2,
326 MachineBasicBlock::iterator &I1,
327 MachineBasicBlock::iterator &I2) {
331 unsigned TailLen = 0;
332 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
334 if (!I1->isIdenticalTo(I2) ||
335 // FIXME: This check is dubious. It's used to get around a problem where
336 // people incorrectly expect inline asm directives to remain in the same
337 // relative order. This is untenable because normal compiler
338 // optimizations (like this one) may reorder and/or merge these
340 I1->getOpcode() == TargetInstrInfo::INLINEASM) {
349 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
350 /// after it, replacing it with an unconditional branch to NewDest. This
351 /// returns true if OldInst's block is modified, false if NewDest is modified.
352 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
353 MachineBasicBlock *NewDest) {
354 MachineBasicBlock *OldBB = OldInst->getParent();
356 // Remove all the old successors of OldBB from the CFG.
357 while (!OldBB->succ_empty())
358 OldBB->removeSuccessor(OldBB->succ_begin());
360 // Remove all the dead instructions from the end of OldBB.
361 OldBB->erase(OldInst, OldBB->end());
363 // If OldBB isn't immediately before OldBB, insert a branch to it.
364 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
365 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
366 OldBB->addSuccessor(NewDest);
370 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
371 /// MBB so that the part before the iterator falls into the part starting at the
372 /// iterator. This returns the new MBB.
373 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
374 MachineBasicBlock::iterator BBI1) {
375 // Create the fall-through block.
376 MachineFunction::iterator MBBI = &CurMBB;
377 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
378 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
380 // Move all the successors of this block to the specified block.
381 while (!CurMBB.succ_empty()) {
382 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
383 NewMBB->addSuccessor(S);
384 CurMBB.removeSuccessor(S);
387 // Add an edge from CurMBB to NewMBB for the fall-through.
388 CurMBB.addSuccessor(NewMBB);
390 // Splice the code over.
391 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
393 // For targets that use the register scavenger, we must maintain LiveIns.
395 RS->enterBasicBlock(&CurMBB);
397 RS->forward(prior(CurMBB.end()));
398 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
399 RS->getRegsUsed(RegsLiveAtExit, false);
400 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
401 if (RegsLiveAtExit[i])
402 NewMBB->addLiveIn(i);
408 /// EstimateRuntime - Make a rough estimate for how long it will take to run
409 /// the specified code.
410 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
411 MachineBasicBlock::iterator E) {
413 for (; I != E; ++I) {
414 const TargetInstrDesc &TID = I->getDesc();
417 else if (TID.isSimpleLoad() || TID.mayStore())
425 /// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
426 /// MBB2I and then insert an unconditional branch in the other block. Determine
427 /// which is the best to split
428 static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
429 MachineBasicBlock::iterator MBB1I,
430 MachineBasicBlock *MBB2,
431 MachineBasicBlock::iterator MBB2I,
432 MachineBasicBlock *PredBB) {
433 // If one block is the entry block, split the other one; we can't generate
434 // a branch to the entry block, as its label is not emitted.
435 MachineBasicBlock *Entry = MBB1->getParent()->begin();
441 // If one block falls through into the common successor, choose that
442 // one to split; it is one instruction less to do that.
446 else if (MBB2 == PredBB)
449 // TODO: if we had some notion of which block was hotter, we could split
450 // the hot block, so it is the fall-through. Since we don't have profile info
451 // make a decision based on which will hurt most to split.
452 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I);
453 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I);
455 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
456 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
457 // have a lower overall impact on the program execution.
458 return MBB1Time < MBB2Time;
461 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
462 // branches temporarily for tail merging). In the case where CurMBB ends
463 // with a conditional branch to the next block, optimize by reversing the
464 // test and conditionally branching to SuccMBB instead.
466 static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
467 const TargetInstrInfo *TII) {
468 MachineFunction *MF = CurMBB->getParent();
469 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
470 MachineBasicBlock *TBB = 0, *FBB = 0;
471 std::vector<MachineOperand> Cond;
472 if (I != MF->end() &&
473 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
474 MachineBasicBlock *NextBB = I;
475 if (TBB == NextBB && !Cond.empty() && !FBB) {
476 if (!TII->ReverseBranchCondition(Cond)) {
477 TII->RemoveBranch(*CurMBB);
478 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
483 TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
486 static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
487 const std::pair<unsigned,MachineBasicBlock*> &q) {
488 if (p.first < q.first)
490 else if (p.first > q.first)
492 else if (p.second->getNumber() < q.second->getNumber())
494 else if (p.second->getNumber() > q.second->getNumber())
497 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
498 // an object with itself.
499 #ifndef _GLIBCXX_DEBUG
500 assert(0 && "Predecessor appears twice");
506 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
507 /// hash CurHash (guaranteed to match the last element). Build the vector
508 /// SameTails of all those that have the (same) largest number of instructions
509 /// in common of any pair of these blocks. SameTails entries contain an
510 /// iterator into MergePotentials (from which the MachineBasicBlock can be
511 /// found) and a MachineBasicBlock::iterator into that MBB indicating the
512 /// instruction where the matching code sequence begins.
513 /// Order of elements in SameTails is the reverse of the order in which
514 /// those blocks appear in MergePotentials (where they are not necessarily
516 unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
517 unsigned minCommonTailLength) {
518 unsigned maxCommonTailLength = 0U;
520 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
521 MPIterator HighestMPIter = prior(MergePotentials.end());
522 for (MPIterator CurMPIter = prior(MergePotentials.end()),
523 B = MergePotentials.begin();
524 CurMPIter!=B && CurMPIter->first==CurHash;
526 for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
527 unsigned CommonTailLen = ComputeCommonTailLength(
530 TrialBBI1, TrialBBI2);
531 if (CommonTailLen >= minCommonTailLength) {
532 if (CommonTailLen > maxCommonTailLength) {
534 maxCommonTailLength = CommonTailLen;
535 HighestMPIter = CurMPIter;
536 SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
538 if (HighestMPIter == CurMPIter &&
539 CommonTailLen == maxCommonTailLength)
540 SameTails.push_back(std::make_pair(I, TrialBBI2));
546 return maxCommonTailLength;
549 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
550 /// MergePotentials, restoring branches at ends of blocks as appropriate.
551 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
552 MachineBasicBlock* SuccBB,
553 MachineBasicBlock* PredBB) {
554 for (MPIterator CurMPIter = prior(MergePotentials.end()),
555 B = MergePotentials.begin();
556 CurMPIter->first==CurHash;
558 // Put the unconditional branch back, if we need one.
559 MachineBasicBlock *CurMBB = CurMPIter->second;
560 if (SuccBB && CurMBB != PredBB)
561 FixTail(CurMBB, SuccBB, TII);
562 MergePotentials.erase(CurMPIter);
568 // See if any of the blocks in MergePotentials (which all have a common single
569 // successor, or all have no successor) can be tail-merged. If there is a
570 // successor, any blocks in MergePotentials that are not tail-merged and
571 // are not immediately before Succ must have an unconditional branch to
572 // Succ added (but the predecessor/successor lists need no adjustment).
573 // The lone predecessor of Succ that falls through into Succ,
574 // if any, is given in PredBB.
576 bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
577 MachineBasicBlock* PredBB) {
578 // We cannot jump to the entry block, which affects various choices below.
579 MachineBasicBlock *Entry = MergePotentials.begin()->second->
580 getParent()->begin();
582 // It doesn't make sense to save a single instruction since tail merging
584 // FIXME: Ask the target to provide the threshold?
585 unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
588 DOUT << "\nTryMergeBlocks " << MergePotentials.size();
590 // Sort by hash value so that blocks with identical end sequences sort
592 std::stable_sort(MergePotentials.begin(), MergePotentials.end(),MergeCompare);
594 // Walk through equivalence sets looking for actual exact matches.
595 while (MergePotentials.size() > 1) {
596 unsigned CurHash = prior(MergePotentials.end())->first;
598 // Build SameTails, identifying the set of blocks with this hash code
599 // and with the maximum number of instructions in common.
600 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
601 minCommonTailLength);
603 // If we didn't find any pair that has at least minCommonTailLength
604 // instructions in common, remove all blocks with this hash code and retry.
605 if (SameTails.empty()) {
606 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
610 // If one of the blocks is the entire common tail (and not the entry
611 // block, which we can't jump to), treat all blocks with this same
614 for (i=0; i<SameTails.size(); i++) {
615 MachineBasicBlock *MBB = SameTails[i].first->second;
616 if (MBB->begin() == SameTails[i].second && MBB != Entry)
619 if (i!=SameTails.size()) {
620 MachineBasicBlock *MBB = SameTails[i].first->second;
621 // MBB is common tail. Adjust all other BB's to jump to this one.
622 // Traversal must be forwards so erases work.
623 DOUT << "\nUsing common tail " << MBB->getNumber() << " for ";
624 for (unsigned int j=0; j<SameTails.size(); ++j) {
627 DOUT << SameTails[j].first->second->getNumber() << ",";
628 // Hack the end off BB j, making it jump to BB i instead.
629 ReplaceTailWithBranchTo(SameTails[j].second, MBB);
630 // This modifies BB j, so remove it from the worklist.
631 MergePotentials.erase(SameTails[j].first);
634 // We leave i in the worklist in case there are other blocks that
635 // match it with a smaller number of instructions.
640 // Otherwise, merge the 2 blocks in SameTails that are latest in
641 // MergePotentials; these are at indices 0 and 1 in SameTails.
642 MachineBasicBlock::iterator BBI1 = (SameTails[0]).second;
643 MachineBasicBlock::iterator BBI2 = (SameTails[1]).second;
644 MachineBasicBlock *MBB1 = (SameTails[0]).first->second;
645 MachineBasicBlock *MBB2 = (SameTails[1]).first->second;
647 DOUT << "\nMerging " << MBB1->getNumber() << "," <<
648 MBB2->getNumber() << ", size " << maxCommonTailLength;
650 // Neither block is the entire common tail; split the tail of one block
651 // to make it redundant with the other tail. We cannot jump to the
652 // entry block, so if one block is the entry block, split the other one.
654 // The second half of the split block will remain in SameTails, and will
655 // consist entirely of common code. Thus in the case where there are
656 // multiple blocks that would all need to be split, the next iteration of
657 // the outer loop will handle all the rest of them.
659 // Decide whether we want to split MBB1 or MBB2.
660 if (ShouldSplitFirstBlock(MBB1, BBI1, MBB2, BBI2, PredBB)) {
661 MBB1 = SplitMBBAt(*MBB1, BBI1);
662 BBI1 = MBB1->begin();
663 SameTails[0].first->second = MBB1;
665 MBB2 = SplitMBBAt(*MBB2, BBI2);
666 BBI2 = MBB2->begin();
667 SameTails[1].first->second = MBB2;
670 if (MBB2->begin() == BBI2 && MBB2 != Entry) {
671 // Hack the end off MBB1, making it jump to MBB2 instead.
672 ReplaceTailWithBranchTo(BBI1, MBB2);
673 // This modifies MBB1, so remove it from the worklist.
674 MergePotentials.erase(SameTails[0].first);
676 assert(MBB1->begin() == BBI1 && MBB1 != Entry &&
677 "Didn't split block correctly?");
678 // Hack the end off MBB2, making it jump to MBB1 instead.
679 ReplaceTailWithBranchTo(BBI2, MBB1);
680 // This modifies MBB2, so remove it from the worklist.
681 MergePotentials.erase(SameTails[1].first);
688 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
690 if (!EnableTailMerge) return false;
694 // First find blocks with no successors.
695 MergePotentials.clear();
696 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
698 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
700 // See if we can do any tail merging on those.
701 if (MergePotentials.size() < TailMergeThreshold &&
702 MergePotentials.size() >= 2)
703 MadeChange |= TryMergeBlocks(NULL, NULL);
705 // Look at blocks (IBB) with multiple predecessors (PBB).
706 // We change each predecessor to a canonical form, by
707 // (1) temporarily removing any unconditional branch from the predecessor
709 // (2) alter conditional branches so they branch to the other block
710 // not IBB; this may require adding back an unconditional branch to IBB
711 // later, where there wasn't one coming in. E.g.
713 // fallthrough to QBB
716 // with a conceptual B to IBB after that, which never actually exists.
717 // With those changes, we see whether the predecessors' tails match,
718 // and merge them if so. We change things out of canonical form and
719 // back to the way they were later in the process. (OptimizeBranches
720 // would undo some of this, but we can't use it, because we'd get into
721 // a compile-time infinite loop repeatedly doing and undoing the same
724 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
725 if (!I->succ_empty() && I->pred_size() >= 2 &&
726 I->pred_size() < TailMergeThreshold) {
727 MachineBasicBlock *IBB = I;
728 MachineBasicBlock *PredBB = prior(I);
729 MergePotentials.clear();
730 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
733 MachineBasicBlock* PBB = *P;
734 // Skip blocks that loop to themselves, can't tail merge these.
737 MachineBasicBlock *TBB = 0, *FBB = 0;
738 std::vector<MachineOperand> Cond;
739 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
740 // Failing case: IBB is the target of a cbr, and
741 // we cannot reverse the branch.
742 std::vector<MachineOperand> NewCond(Cond);
743 if (!Cond.empty() && TBB==IBB) {
744 if (TII->ReverseBranchCondition(NewCond))
746 // This is the QBB case described above
748 FBB = next(MachineFunction::iterator(PBB));
750 // Failing case: the only way IBB can be reached from PBB is via
751 // exception handling. Happens for landing pads. Would be nice
752 // to have a bit in the edge so we didn't have to do all this.
753 if (IBB->isLandingPad()) {
754 MachineFunction::iterator IP = PBB; IP++;
755 MachineBasicBlock* PredNextBB = NULL;
759 if (IBB!=PredNextBB) // fallthrough
762 if (TBB!=IBB && FBB!=IBB) // cbr then ubr
764 } else if (Cond.empty()) {
768 if (TBB!=IBB && IBB!=PredNextBB) // cbr
772 // Remove the unconditional branch at the end, if any.
773 if (TBB && (Cond.empty() || FBB)) {
774 TII->RemoveBranch(*PBB);
776 // reinsert conditional branch only, for now
777 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
779 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
782 if (MergePotentials.size() >= 2)
783 MadeChange |= TryMergeBlocks(I, PredBB);
784 // Reinsert an unconditional branch if needed.
785 // The 1 below can be either an original single predecessor, or a result
786 // of removing blocks in TryMergeBlocks.
787 PredBB = prior(I); // this may have been changed in TryMergeBlocks
788 if (MergePotentials.size()==1 &&
789 (MergePotentials.begin())->second != PredBB)
790 FixTail((MergePotentials.begin())->second, I, TII);
796 //===----------------------------------------------------------------------===//
797 // Branch Optimization
798 //===----------------------------------------------------------------------===//
800 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
803 // Make sure blocks are numbered in order
806 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
807 MachineBasicBlock *MBB = I++;
810 // If it is dead, remove it.
811 if (MBB->pred_empty()) {
812 RemoveDeadBlock(MBB);
821 /// CanFallThrough - Return true if the specified block (with the specified
822 /// branch condition) can implicitly transfer control to the block after it by
823 /// falling off the end of it. This should return false if it can reach the
824 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
826 /// True is a conservative answer.
828 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
829 bool BranchUnAnalyzable,
830 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
831 const std::vector<MachineOperand> &Cond) {
832 MachineFunction::iterator Fallthrough = CurBB;
834 // If FallthroughBlock is off the end of the function, it can't fall through.
835 if (Fallthrough == CurBB->getParent()->end())
838 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
839 if (!CurBB->isSuccessor(Fallthrough))
842 // If we couldn't analyze the branch, assume it could fall through.
843 if (BranchUnAnalyzable) return true;
845 // If there is no branch, control always falls through.
846 if (TBB == 0) return true;
848 // If there is some explicit branch to the fallthrough block, it can obviously
849 // reach, even though the branch should get folded to fall through implicitly.
850 if (MachineFunction::iterator(TBB) == Fallthrough ||
851 MachineFunction::iterator(FBB) == Fallthrough)
854 // If it's an unconditional branch to some block not the fall through, it
855 // doesn't fall through.
856 if (Cond.empty()) return false;
858 // Otherwise, if it is conditional and has no explicit false block, it falls
863 /// CanFallThrough - Return true if the specified can implicitly transfer
864 /// control to the block after it by falling off the end of it. This should
865 /// return false if it can reach the block after it, but it uses an explicit
866 /// branch to do so (e.g. a table jump).
868 /// True is a conservative answer.
870 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
871 MachineBasicBlock *TBB = 0, *FBB = 0;
872 std::vector<MachineOperand> Cond;
873 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
874 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
877 /// IsBetterFallthrough - Return true if it would be clearly better to
878 /// fall-through to MBB1 than to fall through into MBB2. This has to return
879 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
880 /// result in infinite loops.
881 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
882 MachineBasicBlock *MBB2) {
883 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
884 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
885 // optimize branches that branch to either a return block or an assert block
886 // into a fallthrough to the return.
887 if (MBB1->empty() || MBB2->empty()) return false;
889 // If there is a clear successor ordering we make sure that one block
890 // will fall through to the next
891 if (MBB1->isSuccessor(MBB2)) return true;
892 if (MBB2->isSuccessor(MBB1)) return false;
894 MachineInstr *MBB1I = --MBB1->end();
895 MachineInstr *MBB2I = --MBB2->end();
896 return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
899 /// OptimizeBlock - Analyze and optimize control flow related to the specified
900 /// block. This is never called on the entry block.
901 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
902 MachineFunction::iterator FallThrough = MBB;
905 // If this block is empty, make everyone use its fall-through, not the block
906 // explicitly. Landing pads should not do this since the landing-pad table
907 // points to this block.
908 if (MBB->empty() && !MBB->isLandingPad()) {
909 // Dead block? Leave for cleanup later.
910 if (MBB->pred_empty()) return;
912 if (FallThrough == MBB->getParent()->end()) {
913 // TODO: Simplify preds to not branch here if possible!
915 // Rewrite all predecessors of the old block to go to the fallthrough
917 while (!MBB->pred_empty()) {
918 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
919 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
922 // If MBB was the target of a jump table, update jump tables to go to the
923 // fallthrough instead.
924 MBB->getParent()->getJumpTableInfo()->
925 ReplaceMBBInJumpTables(MBB, FallThrough);
931 // Check to see if we can simplify the terminator of the block before this
933 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
935 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
936 std::vector<MachineOperand> PriorCond;
937 bool PriorUnAnalyzable =
938 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
939 if (!PriorUnAnalyzable) {
940 // If the CFG for the prior block has extra edges, remove them.
941 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
944 // If the previous branch is conditional and both conditions go to the same
945 // destination, remove the branch, replacing it with an unconditional one or
947 if (PriorTBB && PriorTBB == PriorFBB) {
948 TII->RemoveBranch(PrevBB);
951 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
954 return OptimizeBlock(MBB);
957 // If the previous branch *only* branches to *this* block (conditional or
958 // not) remove the branch.
959 if (PriorTBB == MBB && PriorFBB == 0) {
960 TII->RemoveBranch(PrevBB);
963 return OptimizeBlock(MBB);
966 // If the prior block branches somewhere else on the condition and here if
967 // the condition is false, remove the uncond second branch.
968 if (PriorFBB == MBB) {
969 TII->RemoveBranch(PrevBB);
970 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
973 return OptimizeBlock(MBB);
976 // If the prior block branches here on true and somewhere else on false, and
977 // if the branch condition is reversible, reverse the branch to create a
979 if (PriorTBB == MBB) {
980 std::vector<MachineOperand> NewPriorCond(PriorCond);
981 if (!TII->ReverseBranchCondition(NewPriorCond)) {
982 TII->RemoveBranch(PrevBB);
983 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
986 return OptimizeBlock(MBB);
990 // If this block doesn't fall through (e.g. it ends with an uncond branch or
991 // has no successors) and if the pred falls through into this block, and if
992 // it would otherwise fall through into the block after this, move this
993 // block to the end of the function.
995 // We consider it more likely that execution will stay in the function (e.g.
996 // due to loops) than it is to exit it. This asserts in loops etc, moving
997 // the assert condition out of the loop body.
998 if (!PriorCond.empty() && PriorFBB == 0 &&
999 MachineFunction::iterator(PriorTBB) == FallThrough &&
1000 !CanFallThrough(MBB)) {
1001 bool DoTransform = true;
1003 // We have to be careful that the succs of PredBB aren't both no-successor
1004 // blocks. If neither have successors and if PredBB is the second from
1005 // last block in the function, we'd just keep swapping the two blocks for
1006 // last. Only do the swap if one is clearly better to fall through than
1008 if (FallThrough == --MBB->getParent()->end() &&
1009 !IsBetterFallthrough(PriorTBB, MBB))
1010 DoTransform = false;
1012 // We don't want to do this transformation if we have control flow like:
1021 // In this case, we could actually be moving the return block *into* a
1023 if (DoTransform && !MBB->succ_empty() &&
1024 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
1025 DoTransform = false;
1029 // Reverse the branch so we will fall through on the previous true cond.
1030 std::vector<MachineOperand> NewPriorCond(PriorCond);
1031 if (!TII->ReverseBranchCondition(NewPriorCond)) {
1032 DOUT << "\nMoving MBB: " << *MBB;
1033 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
1035 TII->RemoveBranch(PrevBB);
1036 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
1038 // Move this block to the end of the function.
1039 MBB->moveAfter(--MBB->getParent()->end());
1048 // Analyze the branch in the current block.
1049 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
1050 std::vector<MachineOperand> CurCond;
1051 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
1052 if (!CurUnAnalyzable) {
1053 // If the CFG for the prior block has extra edges, remove them.
1054 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1056 // If this is a two-way branch, and the FBB branches to this block, reverse
1057 // the condition so the single-basic-block loop is faster. Instead of:
1058 // Loop: xxx; jcc Out; jmp Loop
1060 // Loop: xxx; jncc Loop; jmp Out
1061 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1062 std::vector<MachineOperand> NewCond(CurCond);
1063 if (!TII->ReverseBranchCondition(NewCond)) {
1064 TII->RemoveBranch(*MBB);
1065 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1068 return OptimizeBlock(MBB);
1073 // If this branch is the only thing in its block, see if we can forward
1074 // other blocks across it.
1075 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
1076 MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
1077 // This block may contain just an unconditional branch. Because there can
1078 // be 'non-branch terminators' in the block, try removing the branch and
1079 // then seeing if the block is empty.
1080 TII->RemoveBranch(*MBB);
1082 // If this block is just an unconditional branch to CurTBB, we can
1083 // usually completely eliminate the block. The only case we cannot
1084 // completely eliminate the block is when the block before this one
1085 // falls through into MBB and we can't understand the prior block's branch
1088 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1089 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1090 !PrevBB.isSuccessor(MBB)) {
1091 // If the prior block falls through into us, turn it into an
1092 // explicit branch to us to make updates simpler.
1093 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1094 PriorTBB != MBB && PriorFBB != MBB) {
1095 if (PriorTBB == 0) {
1096 assert(PriorCond.empty() && PriorFBB == 0 &&
1097 "Bad branch analysis");
1100 assert(PriorFBB == 0 && "Machine CFG out of date!");
1103 TII->RemoveBranch(PrevBB);
1104 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
1107 // Iterate through all the predecessors, revectoring each in-turn.
1109 bool DidChange = false;
1110 bool HasBranchToSelf = false;
1111 while(PI != MBB->pred_size()) {
1112 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1114 // If this block has an uncond branch to itself, leave it.
1116 HasBranchToSelf = true;
1119 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1123 // Change any jumptables to go to the new MBB.
1124 MBB->getParent()->getJumpTableInfo()->
1125 ReplaceMBBInJumpTables(MBB, CurTBB);
1129 if (!HasBranchToSelf) return;
1134 // Add the branch back if the block is more than just an uncond branch.
1135 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1139 // If the prior block doesn't fall through into this block, and if this
1140 // block doesn't fall through into some other block, see if we can find a
1141 // place to move this block where a fall-through will happen.
1142 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1143 PriorTBB, PriorFBB, PriorCond)) {
1144 // Now we know that there was no fall-through into this block, check to
1145 // see if it has a fall-through into its successor.
1146 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
1149 if (!MBB->isLandingPad()) {
1150 // Check all the predecessors of this block. If one of them has no fall
1151 // throughs, move this block right after it.
1152 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1153 E = MBB->pred_end(); PI != E; ++PI) {
1154 // Analyze the branch at the end of the pred.
1155 MachineBasicBlock *PredBB = *PI;
1156 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1157 if (PredBB != MBB && !CanFallThrough(PredBB)
1158 && (!CurFallsThru || !CurTBB || !CurFBB)
1159 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1160 // If the current block doesn't fall through, just move it.
1161 // If the current block can fall through and does not end with a
1162 // conditional branch, we need to append an unconditional jump to
1163 // the (current) next block. To avoid a possible compile-time
1164 // infinite loop, move blocks only backward in this case.
1165 // Also, if there are already 2 branches here, we cannot add a third;
1166 // this means we have the case
1171 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1173 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1175 MBB->moveAfter(PredBB);
1177 return OptimizeBlock(MBB);
1182 if (!CurFallsThru) {
1183 // Check all successors to see if we can move this block before it.
1184 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1185 E = MBB->succ_end(); SI != E; ++SI) {
1186 // Analyze the branch at the end of the block before the succ.
1187 MachineBasicBlock *SuccBB = *SI;
1188 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1189 std::vector<MachineOperand> SuccPrevCond;
1191 // If this block doesn't already fall-through to that successor, and if
1192 // the succ doesn't already have a block that can fall through into it,
1193 // and if the successor isn't an EH destination, we can arrange for the
1194 // fallthrough to happen.
1195 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1196 !SuccBB->isLandingPad()) {
1197 MBB->moveBefore(SuccBB);
1199 return OptimizeBlock(MBB);
1203 // Okay, there is no really great place to put this block. If, however,
1204 // the block before this one would be a fall-through if this block were
1205 // removed, move this block to the end of the function.
1206 if (FallThrough != MBB->getParent()->end() &&
1207 PrevBB.isSuccessor(FallThrough)) {
1208 MBB->moveAfter(--MBB->getParent()->end());