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/Transforms/Utils/Local.h"
30 #include "Support/CommandLine.h"
31 #include "Support/Debug.h"
32 #include "Support/Statistic.h"
37 Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
38 cl::init(6), cl::Hidden);
39 Statistic<> NumEliminated("tailduplicate",
40 "Number of unconditional branches eliminated");
41 Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
43 class TailDup : public FunctionPass {
44 bool runOnFunction(Function &F);
46 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
47 inline void eliminateUnconditionalBranch(BranchInst *BI);
49 RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
52 // Public interface to the Tail Duplication pass
53 Pass *llvm::createTailDuplicationPass() { return new TailDup(); }
55 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
56 /// the function, eliminating it if it looks attractive enough.
58 bool TailDup::runOnFunction(Function &F) {
60 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
61 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
62 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
70 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
71 /// attractive to eliminate. We eliminate the branch if the destination basic
72 /// block has <= 5 instructions in it, not counting PHI nodes. In practice,
73 /// since one of these is a terminator instruction, this means that we will add
74 /// up to 4 instructions to the new block.
76 /// We don't count PHI nodes in the count since they will be removed when the
77 /// contents of the block are copied over.
79 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
80 BranchInst *BI = dyn_cast<BranchInst>(TI);
81 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
83 BasicBlock *Dest = BI->getSuccessor(0);
84 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
86 // Do not inline a block if we will just get another branch to the same block!
87 TerminatorInst *DTI = Dest->getTerminator();
88 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
89 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
90 return false; // Do not loop infinitely!
92 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
93 // because doing so would require breaking critical edges. This should be
95 if (!DTI->use_empty())
98 // Do not bother working on dead blocks...
99 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
100 if (PI == PE && Dest != Dest->getParent()->begin())
101 return false; // It's just a dead block, ignore it...
103 // Also, do not bother with blocks with only a single predecessor: simplify
104 // CFG will fold these two blocks together!
106 if (PI == PE) return false; // Exactly one predecessor!
108 BasicBlock::iterator I = Dest->begin();
109 while (isa<PHINode>(*I)) ++I;
111 for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
112 if (Size == Threshold) return false; // The block is too large...
114 // Do not tail duplicate a block that has thousands of successors into a block
115 // with a single successor if the block has many other predecessors. This can
116 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
117 // cases that have a large number of indirect gotos.
118 if (DTI->getNumSuccessors() > 8)
119 if (std::distance(PI, PE) * DTI->getNumSuccessors() > 128)
126 /// eliminateUnconditionalBranch - Clone the instructions from the destination
127 /// block into the source block, eliminating the specified unconditional branch.
128 /// If the destination block defines values used by successors of the dest
129 /// block, we may need to insert PHI nodes.
131 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
132 BasicBlock *SourceBlock = Branch->getParent();
133 BasicBlock *DestBlock = Branch->getSuccessor(0);
134 assert(SourceBlock != DestBlock && "Our predicate is broken!");
136 DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
137 << "]: Eliminating branch: " << *Branch);
139 // Tail duplication can not update SSA properties correctly if the values
140 // defined in the duplicated tail are used outside of the tail itself. For
141 // this reason, we spill all values that are used outside of the tail to the
143 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
144 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
146 bool ShouldDemote = false;
147 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
148 // We must allow our successors to use tail values in their PHI nodes
149 // (if the incoming value corresponds to the tail block).
150 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
151 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
152 if (PN->getIncomingValue(i) == I &&
153 PN->getIncomingBlock(i) != DestBlock) {
161 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
162 // If the user of this instruction is a PHI node in the current block,
163 // which has an entry from another block using the value, spill it.
164 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
165 if (PN->getIncomingValue(i) == I &&
166 PN->getIncomingBlock(i) != DestBlock) {
173 // We found a use outside of the tail. Create a new stack slot to
174 // break this inter-block usage pattern.
175 DemoteRegToStack(*I);
180 // We are going to have to map operands from the original block B to the new
181 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
182 // nodes also define part of this mapping. Loop over these PHI nodes, adding
183 // them to our mapping.
185 std::map<Value*, Value*> ValueMapping;
187 BasicBlock::iterator BI = DestBlock->begin();
188 bool HadPHINodes = isa<PHINode>(BI);
189 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
190 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
192 // Clone the non-phi instructions of the dest block into the source block,
193 // keeping track of the mapping...
195 for (; BI != DestBlock->end(); ++BI) {
196 Instruction *New = BI->clone();
197 New->setName(BI->getName());
198 SourceBlock->getInstList().push_back(New);
199 ValueMapping[BI] = New;
202 // Now that we have built the mapping information and cloned all of the
203 // instructions (giving us a new terminator, among other things), walk the new
204 // instructions, rewriting references of old instructions to use new
207 BI = Branch; ++BI; // Get an iterator to the first new instruction
208 for (; BI != SourceBlock->end(); ++BI)
209 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
210 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
211 BI->setOperand(i, Remapped);
213 // Next we check to see if any of the successors of DestBlock had PHI nodes.
214 // If so, we need to add entries to the PHI nodes for SourceBlock now.
215 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
217 BasicBlock *Succ = *SI;
218 for (BasicBlock::iterator PNI = Succ->begin();
219 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
220 // Ok, we have a PHI node. Figure out what the incoming value was for the
222 Value *IV = PN->getIncomingValueForBlock(DestBlock);
224 // Remap the value if necessary...
225 if (Value *MappedIV = ValueMapping[IV])
227 PN->addIncoming(IV, SourceBlock);
231 // Next, remove the old branch instruction, and any PHI node entries that we
233 BI = Branch; ++BI; // Get an iterator to the first new instruction
234 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
235 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
237 // Final step: now that we have finished everything up, walk the cloned
238 // instructions one last time, constant propagating and DCE'ing them, because
239 // they may not be needed anymore.
242 while (BI != SourceBlock->end())
243 if (!dceInstruction(BI) && !doConstantPropagation(BI))
246 ++NumEliminated; // We just killed a branch!