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