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