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