Remove unused header file.
[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 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Constant.h"
23 #include "llvm/Function.h"
24 #include "llvm/iPHINode.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Type.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "Support/CommandLine.h"
31 #include "Support/Debug.h"
32 #include "Support/Statistic.h"
33 using namespace llvm;
34
35 namespace {
36   cl::opt<unsigned>
37   Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
38             cl::init(6), cl::Hidden);
39   Statistic<> NumEliminated("tailduplicate",
40                             "Number of unconditional branches eliminated");
41   Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
42
43   class TailDup : public FunctionPass {
44     bool runOnFunction(Function &F);
45   private:
46     inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
47     inline void eliminateUnconditionalBranch(BranchInst *BI);
48   };
49   RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
50 }
51
52 // Public interface to the Tail Duplication pass
53 Pass *llvm::createTailDuplicationPass() { return new TailDup(); }
54
55 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
56 /// the function, eliminating it if it looks attractive enough.
57 ///
58 bool TailDup::runOnFunction(Function &F) {
59   bool Changed = false;
60   for (Function::iterator I = F.begin(), E = F.end(); I != E; )
61     if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
62       eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
63       Changed = true;
64     } else {
65       ++I;
66     }
67   return Changed;
68 }
69
70 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
71 /// attractive to eliminate.  We eliminate the branch if the destination basic
72 /// block has <= 5 instructions in it, not counting PHI nodes.  In practice,
73 /// since one of these is a terminator instruction, this means that we will add
74 /// up to 4 instructions to the new block.
75 ///
76 /// We don't count PHI nodes in the count since they will be removed when the
77 /// contents of the block are copied over.
78 ///
79 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
80   BranchInst *BI = dyn_cast<BranchInst>(TI);
81   if (!BI || !BI->isUnconditional()) return false;  // Not an uncond branch!
82
83   BasicBlock *Dest = BI->getSuccessor(0);
84   if (Dest == BI->getParent()) return false;        // Do not loop infinitely!
85
86   // Do not inline a block if we will just get another branch to the same block!
87   TerminatorInst *DTI = Dest->getTerminator();
88   if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
89     if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
90       return false;                                 // Do not loop infinitely!
91
92   // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
93   // because doing so would require breaking critical edges.  This should be
94   // fixed eventually.
95   if (!DTI->use_empty())
96     return false;
97
98   // Do not bother working on dead blocks...
99   pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
100   if (PI == PE && Dest != Dest->getParent()->begin())
101     return false;   // It's just a dead block, ignore it...
102
103   // Also, do not bother with blocks with only a single predecessor: simplify
104   // CFG will fold these two blocks together!
105   ++PI;
106   if (PI == PE) return false;  // Exactly one predecessor!
107
108   BasicBlock::iterator I = Dest->begin();
109   while (isa<PHINode>(*I)) ++I;
110
111   for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
112     if (Size == Threshold) return false;  // The block is too large...
113
114   // Do not tail duplicate a block that has thousands of successors into a block
115   // with a single successor if the block has many other predecessors.  This can
116   // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
117   // cases that have a large number of indirect gotos.
118   if (DTI->getNumSuccessors() > 8)
119     if (std::distance(PI, PE) * DTI->getNumSuccessors() > 128)
120       return false;
121
122   return true;  
123 }
124
125
126 /// eliminateUnconditionalBranch - Clone the instructions from the destination
127 /// block into the source block, eliminating the specified unconditional branch.
128 /// If the destination block defines values used by successors of the dest
129 /// block, we may need to insert PHI nodes.
130 ///
131 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
132   BasicBlock *SourceBlock = Branch->getParent();
133   BasicBlock *DestBlock = Branch->getSuccessor(0);
134   assert(SourceBlock != DestBlock && "Our predicate is broken!");
135
136   DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
137                   << "]: Eliminating branch: " << *Branch);
138
139   // Tail duplication can not update SSA properties correctly if the values
140   // defined in the duplicated tail are used outside of the tail itself.  For
141   // this reason, we spill all values that are used outside of the tail to the
142   // stack.
143   for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
144     for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
145          ++UI) {
146       bool ShouldDemote = false;
147       if (cast<Instruction>(*UI)->getParent() != DestBlock) {
148         // We must allow our successors to use tail values in their PHI nodes
149         // (if the incoming value corresponds to the tail block).
150         if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
151           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
152             if (PN->getIncomingValue(i) == I &&
153                 PN->getIncomingBlock(i) != DestBlock) {
154               ShouldDemote = true;
155               break;
156             }
157
158         } else {
159           ShouldDemote = true;
160         }
161       } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
162         // If the user of this instruction is a PHI node in the current block,
163         // which has an entry from another block using the value, spill it.
164         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
165           if (PN->getIncomingValue(i) == I &&
166               PN->getIncomingBlock(i) != DestBlock) {
167             ShouldDemote = true;
168             break;
169           }
170       }
171
172       if (ShouldDemote) {
173         // We found a use outside of the tail.  Create a new stack slot to
174         // break this inter-block usage pattern.
175         DemoteRegToStack(*I);
176         break;
177       }
178     }
179
180   // We are going to have to map operands from the original block B to the new
181   // copy of the block B'.  If there are PHI nodes in the DestBlock, these PHI
182   // nodes also define part of this mapping.  Loop over these PHI nodes, adding
183   // them to our mapping.
184   //
185   std::map<Value*, Value*> ValueMapping;
186
187   BasicBlock::iterator BI = DestBlock->begin();
188   bool HadPHINodes = isa<PHINode>(BI);
189   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
190     ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
191
192   // Clone the non-phi instructions of the dest block into the source block,
193   // keeping track of the mapping...
194   //
195   for (; BI != DestBlock->end(); ++BI) {
196     Instruction *New = BI->clone();
197     New->setName(BI->getName());
198     SourceBlock->getInstList().push_back(New);
199     ValueMapping[BI] = New;
200   }
201
202   // Now that we have built the mapping information and cloned all of the
203   // instructions (giving us a new terminator, among other things), walk the new
204   // instructions, rewriting references of old instructions to use new
205   // instructions.
206   //
207   BI = Branch; ++BI;  // Get an iterator to the first new instruction
208   for (; BI != SourceBlock->end(); ++BI)
209     for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
210       if (Value *Remapped = ValueMapping[BI->getOperand(i)])
211         BI->setOperand(i, Remapped);
212
213   // Next we check to see if any of the successors of DestBlock had PHI nodes.
214   // If so, we need to add entries to the PHI nodes for SourceBlock now.
215   for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
216        SI != SE; ++SI) {
217     BasicBlock *Succ = *SI;
218     for (BasicBlock::iterator PNI = Succ->begin();
219          PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
220       // Ok, we have a PHI node.  Figure out what the incoming value was for the
221       // DestBlock.
222       Value *IV = PN->getIncomingValueForBlock(DestBlock);
223       
224       // Remap the value if necessary...
225       if (Value *MappedIV = ValueMapping[IV])
226         IV = MappedIV;
227       PN->addIncoming(IV, SourceBlock);
228     }
229   }
230
231   // Next, remove the old branch instruction, and any PHI node entries that we
232   // had.
233   BI = Branch; ++BI;  // Get an iterator to the first new instruction
234   DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
235   SourceBlock->getInstList().erase(Branch);  // Destroy the uncond branch...
236
237   // Final step: now that we have finished everything up, walk the cloned
238   // instructions one last time, constant propagating and DCE'ing them, because
239   // they may not be needed anymore.
240   //
241   if (HadPHINodes)
242     while (BI != SourceBlock->end())
243       if (!dceInstruction(BI) && !doConstantPropagation(BI))
244         ++BI;
245
246   ++NumEliminated;  // We just killed a branch!
247 }