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 static char ID; // Pass identification, replacement for typeid
47 TailDup() : FunctionPass((intptr_t)&ID) {}
50 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
51 inline void eliminateUnconditionalBranch(BranchInst *BI);
54 RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
57 // Public interface to the Tail Duplication pass
58 FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
60 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
61 /// the function, eliminating it if it looks attractive enough.
63 bool TailDup::runOnFunction(Function &F) {
65 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
66 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
67 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
75 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
76 /// attractive to eliminate. We eliminate the branch if the destination basic
77 /// block has <= 5 instructions in it, not counting PHI nodes. In practice,
78 /// since one of these is a terminator instruction, this means that we will add
79 /// up to 4 instructions to the new block.
81 /// We don't count PHI nodes in the count since they will be removed when the
82 /// contents of the block are copied over.
84 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
85 BranchInst *BI = dyn_cast<BranchInst>(TI);
86 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
88 BasicBlock *Dest = BI->getSuccessor(0);
89 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
91 // Do not inline a block if we will just get another branch to the same block!
92 TerminatorInst *DTI = Dest->getTerminator();
93 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
94 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
95 return false; // Do not loop infinitely!
97 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
98 // because doing so would require breaking critical edges. This should be
100 if (!DTI->use_empty())
103 // Do not bother working on dead blocks...
104 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
105 if (PI == PE && Dest != Dest->getParent()->begin())
106 return false; // It's just a dead block, ignore it...
108 // Also, do not bother with blocks with only a single predecessor: simplify
109 // CFG will fold these two blocks together!
111 if (PI == PE) return false; // Exactly one predecessor!
113 BasicBlock::iterator I = Dest->begin();
114 while (isa<PHINode>(*I)) ++I;
116 for (unsigned Size = 0; I != Dest->end(); ++I) {
117 if (Size == Threshold) return false; // The block is too large.
118 // Only count instructions that are not debugger intrinsics.
119 if (!isa<DbgInfoIntrinsic>(I)) ++Size;
122 // Do not tail duplicate a block that has thousands of successors into a block
123 // with a single successor if the block has many other predecessors. This can
124 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
125 // cases that have a large number of indirect gotos.
126 unsigned NumSuccs = DTI->getNumSuccessors();
128 unsigned TooMany = 128;
129 if (NumSuccs >= TooMany) return false;
130 TooMany = TooMany/NumSuccs;
131 for (; PI != PE; ++PI)
132 if (TooMany-- == 0) return false;
135 // Finally, if this unconditional branch is a fall-through, be careful about
136 // tail duplicating it. In particular, we don't want to taildup it if the
137 // original block will still be there after taildup is completed: doing so
138 // would eliminate the fall-through, requiring unconditional branches.
139 Function::iterator DestI = Dest;
140 if (&*--DestI == BI->getParent()) {
141 // The uncond branch is a fall-through. Tail duplication of the block is
142 // will eliminate the fall-through-ness and end up cloning the terminator
143 // at the end of the Dest block. Since the original Dest block will
144 // continue to exist, this means that one or the other will not be able to
145 // fall through. One typical example that this helps with is code like:
150 // Cloning the 'if b' block into the end of the first foo block is messy.
152 // The messy case is when the fall-through block falls through to other
153 // blocks. This is what we would be preventing if we cloned the block.
155 if (++DestI != Dest->getParent()->end()) {
156 BasicBlock *DestSucc = DestI;
157 // If any of Dest's successors are fall-throughs, don't do this xform.
158 for (succ_iterator SI = succ_begin(Dest), SE = succ_end(Dest);
168 /// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
169 /// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
170 /// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
171 /// DstBlock, return it.
172 static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
173 BasicBlock *DstBlock) {
174 // SrcBlock must have a single predecessor.
175 pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
176 if (PI == PE || ++PI != PE) return 0;
178 BasicBlock *SrcPred = *pred_begin(SrcBlock);
180 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
181 // there is only one other pred, get it, otherwise we can't handle it.
182 PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
183 BasicBlock *DstOtherPred = 0;
184 if (*PI == SrcBlock) {
185 if (++PI == PE) return 0;
187 if (++PI != PE) return 0;
190 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
193 // We can handle two situations here: "if then" and "if then else" blocks. An
194 // 'if then' situation is just where DstOtherPred == SrcPred.
195 if (DstOtherPred == SrcPred)
198 // Check to see if we have an "if then else" situation, which means that
199 // DstOtherPred will have a single predecessor and it will be SrcPred.
200 PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
201 if (PI != PE && *PI == SrcPred) {
202 if (++PI != PE) return 0; // Not a single pred.
203 return SrcPred; // Otherwise, it's an "if then" situation. Return the if.
206 // Otherwise, this is something we can't handle.
211 /// eliminateUnconditionalBranch - Clone the instructions from the destination
212 /// block into the source block, eliminating the specified unconditional branch.
213 /// If the destination block defines values used by successors of the dest
214 /// block, we may need to insert PHI nodes.
216 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
217 BasicBlock *SourceBlock = Branch->getParent();
218 BasicBlock *DestBlock = Branch->getSuccessor(0);
219 assert(SourceBlock != DestBlock && "Our predicate is broken!");
221 DOUT << "TailDuplication[" << SourceBlock->getParent()->getName()
222 << "]: Eliminating branch: " << *Branch;
224 // See if we can avoid duplicating code by moving it up to a dominator of both
226 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
227 DOUT << "Found shared dominator: " << DomBlock->getName() << "\n";
229 // If there are non-phi instructions in DestBlock that have no operands
230 // defined in DestBlock, and if the instruction has no side effects, we can
231 // move the instruction to DomBlock instead of duplicating it.
232 BasicBlock::iterator BBI = DestBlock->begin();
233 while (isa<PHINode>(BBI)) ++BBI;
234 while (!isa<TerminatorInst>(BBI)) {
235 Instruction *I = BBI++;
237 bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
239 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
240 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
241 if (OpI->getParent() == DestBlock ||
242 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
247 // Remove from DestBlock, move right before the term in DomBlock.
248 DestBlock->getInstList().remove(I);
249 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
250 DOUT << "Hoisted: " << *I;
256 // Tail duplication can not update SSA properties correctly if the values
257 // defined in the duplicated tail are used outside of the tail itself. For
258 // this reason, we spill all values that are used outside of the tail to the
260 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
261 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
263 bool ShouldDemote = false;
264 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
265 // We must allow our successors to use tail values in their PHI nodes
266 // (if the incoming value corresponds to the tail block).
267 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
268 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
269 if (PN->getIncomingValue(i) == I &&
270 PN->getIncomingBlock(i) != DestBlock) {
278 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
279 // If the user of this instruction is a PHI node in the current block,
280 // which has an entry from another block using the value, spill it.
281 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
282 if (PN->getIncomingValue(i) == I &&
283 PN->getIncomingBlock(i) != DestBlock) {
290 // We found a use outside of the tail. Create a new stack slot to
291 // break this inter-block usage pattern.
292 DemoteRegToStack(*I);
297 // We are going to have to map operands from the original block B to the new
298 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
299 // nodes also define part of this mapping. Loop over these PHI nodes, adding
300 // them to our mapping.
302 std::map<Value*, Value*> ValueMapping;
304 BasicBlock::iterator BI = DestBlock->begin();
305 bool HadPHINodes = isa<PHINode>(BI);
306 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
307 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
309 // Clone the non-phi instructions of the dest block into the source block,
310 // keeping track of the mapping...
312 for (; BI != DestBlock->end(); ++BI) {
313 Instruction *New = BI->clone();
314 New->setName(BI->getName());
315 SourceBlock->getInstList().push_back(New);
316 ValueMapping[BI] = New;
319 // Now that we have built the mapping information and cloned all of the
320 // instructions (giving us a new terminator, among other things), walk the new
321 // instructions, rewriting references of old instructions to use new
324 BI = Branch; ++BI; // Get an iterator to the first new instruction
325 for (; BI != SourceBlock->end(); ++BI)
326 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
327 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
328 BI->setOperand(i, Remapped);
330 // Next we check to see if any of the successors of DestBlock had PHI nodes.
331 // If so, we need to add entries to the PHI nodes for SourceBlock now.
332 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
334 BasicBlock *Succ = *SI;
335 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
336 PHINode *PN = cast<PHINode>(PNI);
337 // Ok, we have a PHI node. Figure out what the incoming value was for the
339 Value *IV = PN->getIncomingValueForBlock(DestBlock);
341 // Remap the value if necessary...
342 if (Value *MappedIV = ValueMapping[IV])
344 PN->addIncoming(IV, SourceBlock);
348 // Next, remove the old branch instruction, and any PHI node entries that we
350 BI = Branch; ++BI; // Get an iterator to the first new instruction
351 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
352 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
354 // Final step: now that we have finished everything up, walk the cloned
355 // instructions one last time, constant propagating and DCE'ing them, because
356 // they may not be needed anymore.
359 while (BI != SourceBlock->end())
360 if (!dceInstruction(BI) && !doConstantPropagation(BI))
363 ++NumEliminated; // We just killed a branch!