Do not dup malloc, vector instructions, etc. Throttle the default theshold way down.
[oota-llvm.git] / lib / Transforms / Scalar / TailDuplication.cpp
1 //===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
15 //
16 // This pass could be enhanced in the future to use profile information to be
17 // more aggressive.
18 //
19 //===----------------------------------------------------------------------===//
20
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"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include <map>
37 using namespace llvm;
38
39 STATISTIC(NumEliminated, "Number of unconditional branches eliminated");
40
41 static cl::opt<unsigned>
42 TailDupThreshold("taildup-threshold",
43                  cl::desc("Max block size to tail duplicate"),
44                  cl::init(1), cl::Hidden);
45
46 namespace {
47   class VISIBILITY_HIDDEN TailDup : public FunctionPass {
48     bool runOnFunction(Function &F);
49   public:
50     static char ID; // Pass identification, replacement for typeid
51     TailDup() : FunctionPass((intptr_t)&ID) {}
52
53   private:
54     inline bool shouldEliminateUnconditionalBranch(TerminatorInst *, unsigned);
55     inline void eliminateUnconditionalBranch(BranchInst *BI);
56     SmallPtrSet<BasicBlock*, 4> CycleDetector;
57   };
58 }
59
60 char TailDup::ID = 0;
61 static RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
62
63 // Public interface to the Tail Duplication pass
64 FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
65
66 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
67 /// the function, eliminating it if it looks attractive enough.  CycleDetector
68 /// prevents infinite loops by checking that we aren't redirecting a branch to
69 /// a place it already pointed to earlier; see PR 2323.
70 bool TailDup::runOnFunction(Function &F) {
71   bool Changed = false;
72   CycleDetector.clear();
73   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
74     if (shouldEliminateUnconditionalBranch(I->getTerminator(),
75                                            TailDupThreshold)) {
76       eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
77       Changed = true;
78     } else {
79       ++I;
80       CycleDetector.clear();
81     }
82   }
83   return Changed;
84 }
85
86 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
87 /// attractive to eliminate.  We eliminate the branch if the destination basic
88 /// block has <= 5 instructions in it, not counting PHI nodes.  In practice,
89 /// since one of these is a terminator instruction, this means that we will add
90 /// up to 4 instructions to the new block.
91 ///
92 /// We don't count PHI nodes in the count since they will be removed when the
93 /// contents of the block are copied over.
94 ///
95 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI,
96                                                  unsigned Threshold) {
97   BranchInst *BI = dyn_cast<BranchInst>(TI);
98   if (!BI || !BI->isUnconditional()) return false;  // Not an uncond branch!
99
100   BasicBlock *Dest = BI->getSuccessor(0);
101   if (Dest == BI->getParent()) return false;        // Do not loop infinitely!
102
103   // Do not inline a block if we will just get another branch to the same block!
104   TerminatorInst *DTI = Dest->getTerminator();
105   if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
106     if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
107       return false;                                 // Do not loop infinitely!
108
109   // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
110   // because doing so would require breaking critical edges.  This should be
111   // fixed eventually.
112   if (!DTI->use_empty())
113     return false;
114
115   // Do not bother with blocks with only a single predecessor: simplify
116   // CFG will fold these two blocks together!
117   pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
118   ++PI;
119   if (PI == PE) return false;  // Exactly one predecessor!
120
121   BasicBlock::iterator I = Dest->begin();
122   while (isa<PHINode>(*I)) ++I;
123
124   for (unsigned Size = 0; I != Dest->end(); ++I) {
125     if (Size == Threshold) return false;  // The block is too large.
126     
127     // Don't tail duplicate call instructions.  They are very large compared to
128     // other instructions.
129     if (isa<CallInst>(I) || isa<InvokeInst>(I)) return false;
130
131     // Allso alloca and malloc.
132     if (isa<AllocationInst>(I)) return false;
133
134     // Some vector instructions can expand into a number of instructions.
135     if (isa<ShuffleVectorInst>(I) || isa<ExtractElementInst>(I) ||
136         isa<InsertElementInst>(I)) return false;
137     
138     // Only count instructions that are not debugger intrinsics.
139     if (!isa<DbgInfoIntrinsic>(I)) ++Size;
140   }
141
142   // Do not tail duplicate a block that has thousands of successors into a block
143   // with a single successor if the block has many other predecessors.  This can
144   // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
145   // cases that have a large number of indirect gotos.
146   unsigned NumSuccs = DTI->getNumSuccessors();
147   if (NumSuccs > 8) {
148     unsigned TooMany = 128;
149     if (NumSuccs >= TooMany) return false;
150     TooMany = TooMany/NumSuccs;
151     for (; PI != PE; ++PI)
152       if (TooMany-- == 0) return false;
153   }
154   
155   // If this unconditional branch is a fall-through, be careful about
156   // tail duplicating it.  In particular, we don't want to taildup it if the
157   // original block will still be there after taildup is completed: doing so
158   // would eliminate the fall-through, requiring unconditional branches.
159   Function::iterator DestI = Dest;
160   if (&*--DestI == BI->getParent()) {
161     // The uncond branch is a fall-through.  Tail duplication of the block is
162     // will eliminate the fall-through-ness and end up cloning the terminator
163     // at the end of the Dest block.  Since the original Dest block will
164     // continue to exist, this means that one or the other will not be able to
165     // fall through.  One typical example that this helps with is code like:
166     // if (a)
167     //   foo();
168     // if (b)
169     //   foo();
170     // Cloning the 'if b' block into the end of the first foo block is messy.
171     
172     // The messy case is when the fall-through block falls through to other
173     // blocks.  This is what we would be preventing if we cloned the block.
174     DestI = Dest;
175     if (++DestI != Dest->getParent()->end()) {
176       BasicBlock *DestSucc = DestI;
177       // If any of Dest's successors are fall-throughs, don't do this xform.
178       for (succ_iterator SI = succ_begin(Dest), SE = succ_end(Dest);
179            SI != SE; ++SI)
180         if (*SI == DestSucc)
181           return false;
182     }
183   }
184
185   // Finally, check that we haven't redirected to this target block earlier;
186   // there are cases where we loop forever if we don't check this (PR 2323).
187   if (!CycleDetector.insert(Dest))
188     return false;
189
190   return true;
191 }
192
193 /// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
194 /// DestBlock, and that SrcBlock is not the only predecessor of DstBlock.  If we
195 /// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
196 /// DstBlock, return it.
197 static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
198                                           BasicBlock *DstBlock) {
199   // SrcBlock must have a single predecessor.
200   pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
201   if (PI == PE || ++PI != PE) return 0;
202
203   BasicBlock *SrcPred = *pred_begin(SrcBlock);
204
205   // Look at the predecessors of DstBlock.  One of them will be SrcBlock.  If
206   // there is only one other pred, get it, otherwise we can't handle it.
207   PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
208   BasicBlock *DstOtherPred = 0;
209   if (*PI == SrcBlock) {
210     if (++PI == PE) return 0;
211     DstOtherPred = *PI;
212     if (++PI != PE) return 0;
213   } else {
214     DstOtherPred = *PI;
215     if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
216   }
217
218   // We can handle two situations here: "if then" and "if then else" blocks.  An
219   // 'if then' situation is just where DstOtherPred == SrcPred.
220   if (DstOtherPred == SrcPred)
221     return SrcPred;
222
223   // Check to see if we have an "if then else" situation, which means that
224   // DstOtherPred will have a single predecessor and it will be SrcPred.
225   PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
226   if (PI != PE && *PI == SrcPred) {
227     if (++PI != PE) return 0;  // Not a single pred.
228     return SrcPred;  // Otherwise, it's an "if then" situation.  Return the if.
229   }
230
231   // Otherwise, this is something we can't handle.
232   return 0;
233 }
234
235
236 /// eliminateUnconditionalBranch - Clone the instructions from the destination
237 /// block into the source block, eliminating the specified unconditional branch.
238 /// If the destination block defines values used by successors of the dest
239 /// block, we may need to insert PHI nodes.
240 ///
241 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
242   BasicBlock *SourceBlock = Branch->getParent();
243   BasicBlock *DestBlock = Branch->getSuccessor(0);
244   assert(SourceBlock != DestBlock && "Our predicate is broken!");
245
246   DOUT << "TailDuplication[" << SourceBlock->getParent()->getName()
247        << "]: Eliminating branch: " << *Branch;
248
249   // See if we can avoid duplicating code by moving it up to a dominator of both
250   // blocks.
251   if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
252     DOUT << "Found shared dominator: " << DomBlock->getName() << "\n";
253
254     // If there are non-phi instructions in DestBlock that have no operands
255     // defined in DestBlock, and if the instruction has no side effects, we can
256     // move the instruction to DomBlock instead of duplicating it.
257     BasicBlock::iterator BBI = DestBlock->begin();
258     while (isa<PHINode>(BBI)) ++BBI;
259     while (!isa<TerminatorInst>(BBI)) {
260       Instruction *I = BBI++;
261
262       bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
263       if (CanHoist) {
264         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
265           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
266             if (OpI->getParent() == DestBlock ||
267                 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
268               CanHoist = false;
269               break;
270             }
271         if (CanHoist) {
272           // Remove from DestBlock, move right before the term in DomBlock.
273           DestBlock->getInstList().remove(I);
274           DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
275           DOUT << "Hoisted: " << *I;
276         }
277       }
278     }
279   }
280
281   // Tail duplication can not update SSA properties correctly if the values
282   // defined in the duplicated tail are used outside of the tail itself.  For
283   // this reason, we spill all values that are used outside of the tail to the
284   // stack.
285   for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
286     if (I->isUsedOutsideOfBlock(DestBlock)) {
287       // We found a use outside of the tail.  Create a new stack slot to
288       // break this inter-block usage pattern.
289       DemoteRegToStack(*I);
290     }
291
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.
296   //
297   std::map<Value*, Value*> ValueMapping;
298
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);
303
304   // Clone the non-phi instructions of the dest block into the source block,
305   // keeping track of the mapping...
306   //
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;
312   }
313
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
317   // instructions.
318   //
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);
324
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);
328        SI != SE; ++SI) {
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
333       // DestBlock.
334       Value *IV = PN->getIncomingValueForBlock(DestBlock);
335
336       // Remap the value if necessary...
337       if (Value *MappedIV = ValueMapping[IV])
338         IV = MappedIV;
339       PN->addIncoming(IV, SourceBlock);
340     }
341   }
342
343   // Next, remove the old branch instruction, and any PHI node entries that we
344   // had.
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...
348
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.
352   //
353   if (HadPHINodes)
354     while (BI != SourceBlock->end())
355       if (!dceInstruction(BI) && !doConstantPropagation(BI))
356         ++BI;
357
358   ++NumEliminated;  // We just killed a branch!
359 }