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 #define DEBUG_TYPE "tailduplicate"
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Constant.h"
24 #include "llvm/Function.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Type.h"
29 #include "llvm/Support/CFG.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/ADT/Statistic.h"
37 STATISTIC(NumEliminated, "Number of unconditional branches eliminated");
41 Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
42 cl::init(6), cl::Hidden);
43 class VISIBILITY_HIDDEN TailDup : public FunctionPass {
44 bool runOnFunction(Function &F);
46 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
47 inline void eliminateUnconditionalBranch(BranchInst *BI);
49 RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
52 // Public interface to the Tail Duplication pass
53 FunctionPass *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(); ++I) {
112 if (Size == Threshold) return false; // The block is too large.
113 // Only count instructions that are not debugger intrinsics.
114 if (!isa<DbgInfoIntrinsic>(I)) ++Size;
117 // Do not tail duplicate a block that has thousands of successors into a block
118 // with a single successor if the block has many other predecessors. This can
119 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
120 // cases that have a large number of indirect gotos.
121 unsigned NumSuccs = DTI->getNumSuccessors();
123 unsigned TooMany = 128;
124 if (NumSuccs >= TooMany) return false;
125 TooMany = TooMany/NumSuccs;
126 for (; PI != PE; ++PI)
127 if (TooMany-- == 0) return false;
130 // Finally, if this unconditional branch is a fall-through, be careful about
131 // tail duplicating it. In particular, we don't want to taildup it if the
132 // original block will still be there after taildup is completed: doing so
133 // would eliminate the fall-through, requiring unconditional branches.
134 Function::iterator DestI = Dest;
135 if (&*--DestI == BI->getParent()) {
136 // The uncond branch is a fall-through. Tail duplication of the block is
137 // will eliminate the fall-through-ness and end up cloning the terminator
138 // at the end of the Dest block. Since the original Dest block will
139 // continue to exist, this means that one or the other will not be able to
140 // fall through. One typical example that this helps with is code like:
145 // Cloning the 'if b' block into the end of the first foo block is messy.
147 // The messy case is when the fall-through block falls through to other
148 // blocks. This is what we would be preventing if we cloned the block.
150 if (++DestI != Dest->getParent()->end()) {
151 BasicBlock *DestSucc = DestI;
152 // If any of Dest's successors are fall-throughs, don't do this xform.
153 for (succ_iterator SI = succ_begin(Dest), SE = succ_end(Dest);
163 /// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
164 /// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
165 /// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
166 /// DstBlock, return it.
167 static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
168 BasicBlock *DstBlock) {
169 // SrcBlock must have a single predecessor.
170 pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
171 if (PI == PE || ++PI != PE) return 0;
173 BasicBlock *SrcPred = *pred_begin(SrcBlock);
175 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
176 // there is only one other pred, get it, otherwise we can't handle it.
177 PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
178 BasicBlock *DstOtherPred = 0;
179 if (*PI == SrcBlock) {
180 if (++PI == PE) return 0;
182 if (++PI != PE) return 0;
185 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
188 // We can handle two situations here: "if then" and "if then else" blocks. An
189 // 'if then' situation is just where DstOtherPred == SrcPred.
190 if (DstOtherPred == SrcPred)
193 // Check to see if we have an "if then else" situation, which means that
194 // DstOtherPred will have a single predecessor and it will be SrcPred.
195 PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
196 if (PI != PE && *PI == SrcPred) {
197 if (++PI != PE) return 0; // Not a single pred.
198 return SrcPred; // Otherwise, it's an "if then" situation. Return the if.
201 // Otherwise, this is something we can't handle.
206 /// eliminateUnconditionalBranch - Clone the instructions from the destination
207 /// block into the source block, eliminating the specified unconditional branch.
208 /// If the destination block defines values used by successors of the dest
209 /// block, we may need to insert PHI nodes.
211 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
212 BasicBlock *SourceBlock = Branch->getParent();
213 BasicBlock *DestBlock = Branch->getSuccessor(0);
214 assert(SourceBlock != DestBlock && "Our predicate is broken!");
216 DOUT << "TailDuplication[" << SourceBlock->getParent()->getName()
217 << "]: Eliminating branch: " << *Branch;
219 // See if we can avoid duplicating code by moving it up to a dominator of both
221 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
222 DOUT << "Found shared dominator: " << DomBlock->getName() << "\n";
224 // If there are non-phi instructions in DestBlock that have no operands
225 // defined in DestBlock, and if the instruction has no side effects, we can
226 // move the instruction to DomBlock instead of duplicating it.
227 BasicBlock::iterator BBI = DestBlock->begin();
228 while (isa<PHINode>(BBI)) ++BBI;
229 while (!isa<TerminatorInst>(BBI)) {
230 Instruction *I = BBI++;
232 bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
234 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
235 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
236 if (OpI->getParent() == DestBlock ||
237 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
242 // Remove from DestBlock, move right before the term in DomBlock.
243 DestBlock->getInstList().remove(I);
244 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
245 DOUT << "Hoisted: " << *I;
251 // Tail duplication can not update SSA properties correctly if the values
252 // defined in the duplicated tail are used outside of the tail itself. For
253 // this reason, we spill all values that are used outside of the tail to the
255 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
256 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
258 bool ShouldDemote = false;
259 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
260 // We must allow our successors to use tail values in their PHI nodes
261 // (if the incoming value corresponds to the tail block).
262 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
263 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
264 if (PN->getIncomingValue(i) == I &&
265 PN->getIncomingBlock(i) != DestBlock) {
273 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
274 // If the user of this instruction is a PHI node in the current block,
275 // which has an entry from another block using the value, spill it.
276 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
277 if (PN->getIncomingValue(i) == I &&
278 PN->getIncomingBlock(i) != DestBlock) {
285 // We found a use outside of the tail. Create a new stack slot to
286 // break this inter-block usage pattern.
287 DemoteRegToStack(*I);
292 // We are going to have to map operands from the original block B to the new
293 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
294 // nodes also define part of this mapping. Loop over these PHI nodes, adding
295 // them to our mapping.
297 std::map<Value*, Value*> ValueMapping;
299 BasicBlock::iterator BI = DestBlock->begin();
300 bool HadPHINodes = isa<PHINode>(BI);
301 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
302 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
304 // Clone the non-phi instructions of the dest block into the source block,
305 // keeping track of the mapping...
307 for (; BI != DestBlock->end(); ++BI) {
308 Instruction *New = BI->clone();
309 New->setName(BI->getName());
310 SourceBlock->getInstList().push_back(New);
311 ValueMapping[BI] = New;
314 // Now that we have built the mapping information and cloned all of the
315 // instructions (giving us a new terminator, among other things), walk the new
316 // instructions, rewriting references of old instructions to use new
319 BI = Branch; ++BI; // Get an iterator to the first new instruction
320 for (; BI != SourceBlock->end(); ++BI)
321 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
322 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
323 BI->setOperand(i, Remapped);
325 // Next we check to see if any of the successors of DestBlock had PHI nodes.
326 // If so, we need to add entries to the PHI nodes for SourceBlock now.
327 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
329 BasicBlock *Succ = *SI;
330 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
331 PHINode *PN = cast<PHINode>(PNI);
332 // Ok, we have a PHI node. Figure out what the incoming value was for the
334 Value *IV = PN->getIncomingValueForBlock(DestBlock);
336 // Remap the value if necessary...
337 if (Value *MappedIV = ValueMapping[IV])
339 PN->addIncoming(IV, SourceBlock);
343 // Next, remove the old branch instruction, and any PHI node entries that we
345 BI = Branch; ++BI; // Get an iterator to the first new instruction
346 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
347 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
349 // Final step: now that we have finished everything up, walk the cloned
350 // instructions one last time, constant propagating and DCE'ing them, because
351 // they may not be needed anymore.
354 while (BI != SourceBlock->end())
355 if (!dceInstruction(BI) && !doConstantPropagation(BI))
358 ++NumEliminated; // We just killed a branch!