1 //===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs a limited form of tail duplication, intended to simplify
11 // CFGs by removing some unconditional branches. This pass is necessary to
12 // straighten out loops created by the C front-end, but also is capable of
13 // making other code nicer. After this pass is run, the CFG simplify pass
14 // should be run to clean up the mess.
16 // This pass could be enhanced in the future to use profile information to be
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Constant.h"
23 #include "llvm/Function.h"
24 #include "llvm/iPHINode.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Type.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Support/ValueHolder.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "Support/CommandLine.h"
32 #include "Support/Debug.h"
33 #include "Support/Statistic.h"
38 Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
39 cl::init(6), cl::Hidden);
40 Statistic<> NumEliminated("tailduplicate",
41 "Number of unconditional branches eliminated");
42 Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
44 class TailDup : public FunctionPass {
45 bool runOnFunction(Function &F);
47 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
48 inline void eliminateUnconditionalBranch(BranchInst *BI);
50 RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
53 // Public interface to the Tail Duplication pass
54 Pass *llvm::createTailDuplicationPass() { return new TailDup(); }
56 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
57 /// the function, eliminating it if it looks attractive enough.
59 bool TailDup::runOnFunction(Function &F) {
61 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
62 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
63 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
71 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
72 /// attractive to eliminate. We eliminate the branch if the destination basic
73 /// block has <= 5 instructions in it, not counting PHI nodes. In practice,
74 /// since one of these is a terminator instruction, this means that we will add
75 /// up to 4 instructions to the new block.
77 /// We don't count PHI nodes in the count since they will be removed when the
78 /// contents of the block are copied over.
80 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
81 BranchInst *BI = dyn_cast<BranchInst>(TI);
82 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
84 BasicBlock *Dest = BI->getSuccessor(0);
85 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
87 // Do not inline a block if we will just get another branch to the same block!
88 TerminatorInst *DTI = Dest->getTerminator();
89 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
90 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
91 return false; // Do not loop infinitely!
93 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
94 // because doing so would require breaking critical edges. This should be
96 if (!DTI->use_empty())
99 // Do not bother working on dead blocks...
100 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
101 if (PI == PE && Dest != Dest->getParent()->begin())
102 return false; // It's just a dead block, ignore it...
104 // Also, do not bother with blocks with only a single predecessor: simplify
105 // CFG will fold these two blocks together!
107 if (PI == PE) return false; // Exactly one predecessor!
109 BasicBlock::iterator I = Dest->begin();
110 while (isa<PHINode>(*I)) ++I;
112 for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
113 if (Size == Threshold) return false; // The block is too large...
115 // Do not tail duplicate a block that has thousands of successors into a block
116 // with a single successor if the block has many other predecessors. This can
117 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
118 // cases that have a large number of indirect gotos.
119 if (DTI->getNumSuccessors() > 8)
120 if (std::distance(PI, PE) * DTI->getNumSuccessors() > 128)
127 /// eliminateUnconditionalBranch - Clone the instructions from the destination
128 /// block into the source block, eliminating the specified unconditional branch.
129 /// If the destination block defines values used by successors of the dest
130 /// block, we may need to insert PHI nodes.
132 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
133 BasicBlock *SourceBlock = Branch->getParent();
134 BasicBlock *DestBlock = Branch->getSuccessor(0);
135 assert(SourceBlock != DestBlock && "Our predicate is broken!");
137 DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
138 << "]: Eliminating branch: " << *Branch);
140 // Tail duplication can not update SSA properties correctly if the values
141 // defined in the duplicated tail are used outside of the tail itself. For
142 // this reason, we spill all values that are used outside of the tail to the
144 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
145 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
147 bool ShouldDemote = false;
148 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
149 // We must allow our successors to use tail values in their PHI nodes
150 // (if the incoming value corresponds to the tail block).
151 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
152 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
153 if (PN->getIncomingValue(i) == I &&
154 PN->getIncomingBlock(i) != DestBlock) {
162 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
163 // If the user of this instruction is a PHI node in the current block,
164 // which has an entry from another block using the value, spill it.
165 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
166 if (PN->getIncomingValue(i) == I &&
167 PN->getIncomingBlock(i) != DestBlock) {
174 // We found a use outside of the tail. Create a new stack slot to
175 // break this inter-block usage pattern.
176 DemoteRegToStack(*I);
181 // We are going to have to map operands from the original block B to the new
182 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
183 // nodes also define part of this mapping. Loop over these PHI nodes, adding
184 // them to our mapping.
186 std::map<Value*, Value*> ValueMapping;
188 BasicBlock::iterator BI = DestBlock->begin();
189 bool HadPHINodes = isa<PHINode>(BI);
190 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
191 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
193 // Clone the non-phi instructions of the dest block into the source block,
194 // keeping track of the mapping...
196 for (; BI != DestBlock->end(); ++BI) {
197 Instruction *New = BI->clone();
198 New->setName(BI->getName());
199 SourceBlock->getInstList().push_back(New);
200 ValueMapping[BI] = New;
203 // Now that we have built the mapping information and cloned all of the
204 // instructions (giving us a new terminator, among other things), walk the new
205 // instructions, rewriting references of old instructions to use new
208 BI = Branch; ++BI; // Get an iterator to the first new instruction
209 for (; BI != SourceBlock->end(); ++BI)
210 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
211 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
212 BI->setOperand(i, Remapped);
214 // Next we check to see if any of the successors of DestBlock had PHI nodes.
215 // If so, we need to add entries to the PHI nodes for SourceBlock now.
216 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
218 BasicBlock *Succ = *SI;
219 for (BasicBlock::iterator PNI = Succ->begin();
220 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
221 // Ok, we have a PHI node. Figure out what the incoming value was for the
223 Value *IV = PN->getIncomingValueForBlock(DestBlock);
225 // Remap the value if necessary...
226 if (Value *MappedIV = ValueMapping[IV])
228 PN->addIncoming(IV, SourceBlock);
232 // Next, remove the old branch instruction, and any PHI node entries that we
234 BI = Branch; ++BI; // Get an iterator to the first new instruction
235 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
236 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
238 // Final step: now that we have finished everything up, walk the cloned
239 // instructions one last time, constant propagating and DCE'ing them, because
240 // they may not be needed anymore.
243 while (BI != SourceBlock->end())
244 if (!dceInstruction(BI) && !doConstantPropagation(BI))
247 ++NumEliminated; // We just killed a branch!