Put all LLVM code into the llvm namespace, as per bug 109.
[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/Support/ValueHolder.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "Support/Debug.h"
32 #include "Support/Statistic.h"
33
34 namespace llvm {
35
36 namespace {
37   Statistic<> NumEliminated("tailduplicate",
38                             "Number of unconditional branches eliminated");
39   Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
40
41   class TailDup : public FunctionPass {
42     bool runOnFunction(Function &F);
43   private:
44     inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
45     inline void eliminateUnconditionalBranch(BranchInst *BI);
46     inline void InsertPHINodesIfNecessary(Instruction *OrigInst, Value *NewInst,
47                                           BasicBlock *NewBlock);
48     inline Value *GetValueInBlock(BasicBlock *BB, Value *OrigVal,
49                                   std::map<BasicBlock*, ValueHolder> &ValueMap,
50                               std::map<BasicBlock*, ValueHolder> &OutValueMap);
51     inline Value *GetValueOutBlock(BasicBlock *BB, Value *OrigVal,
52                                    std::map<BasicBlock*, ValueHolder> &ValueMap,
53                                std::map<BasicBlock*, ValueHolder> &OutValueMap);
54   };
55   RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
56 }
57
58 // Public interface to the Tail Duplication pass
59 Pass *createTailDuplicationPass() { return new TailDup(); }
60
61 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
62 /// the function, eliminating it if it looks attractive enough.
63 ///
64 bool TailDup::runOnFunction(Function &F) {
65   bool Changed = false;
66   for (Function::iterator I = F.begin(), E = F.end(); I != E; )
67     if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
68       eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
69       Changed = true;
70     } else {
71       ++I;
72     }
73   return Changed;
74 }
75
76 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
77 /// attractive to eliminate.  We eliminate the branch if the destination basic
78 /// block has <= 5 instructions in it, not counting PHI nodes.  In practice,
79 /// since one of these is a terminator instruction, this means that we will add
80 /// up to 4 instructions to the new block.
81 ///
82 /// We don't count PHI nodes in the count since they will be removed when the
83 /// contents of the block are copied over.
84 ///
85 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
86   BranchInst *BI = dyn_cast<BranchInst>(TI);
87   if (!BI || !BI->isUnconditional()) return false;  // Not an uncond branch!
88
89   BasicBlock *Dest = BI->getSuccessor(0);
90   if (Dest == BI->getParent()) return false;        // Do not loop infinitely!
91
92   // Do not inline a block if we will just get another branch to the same block!
93   if (BranchInst *DBI = dyn_cast<BranchInst>(Dest->getTerminator()))
94     if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
95       return false;                                 // Do not loop infinitely!
96
97   // Do not bother working on dead blocks...
98   pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
99   if (PI == PE && Dest != Dest->getParent()->begin())
100     return false;   // It's just a dead block, ignore it...
101
102   // Also, do not bother with blocks with only a single predecessor: simplify
103   // CFG will fold these two blocks together!
104   ++PI;
105   if (PI == PE) return false;  // Exactly one predecessor!
106
107   BasicBlock::iterator I = Dest->begin();
108   while (isa<PHINode>(*I)) ++I;
109
110   for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
111     if (Size == 6) return false;  // The block is too large...
112   return true;  
113 }
114
115
116 /// eliminateUnconditionalBranch - Clone the instructions from the destination
117 /// block into the source block, eliminating the specified unconditional branch.
118 /// If the destination block defines values used by successors of the dest
119 /// block, we may need to insert PHI nodes.
120 ///
121 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
122   BasicBlock *SourceBlock = Branch->getParent();
123   BasicBlock *DestBlock = Branch->getSuccessor(0);
124   assert(SourceBlock != DestBlock && "Our predicate is broken!");
125
126   DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
127                   << "]: Eliminating branch: " << *Branch);
128
129   // We are going to have to map operands from the original block B to the new
130   // copy of the block B'.  If there are PHI nodes in the DestBlock, these PHI
131   // nodes also define part of this mapping.  Loop over these PHI nodes, adding
132   // them to our mapping.
133   //
134   std::map<Value*, Value*> ValueMapping;
135
136   BasicBlock::iterator BI = DestBlock->begin();
137   bool HadPHINodes = isa<PHINode>(BI);
138   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
139     ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
140
141   // Clone the non-phi instructions of the dest block into the source block,
142   // keeping track of the mapping...
143   //
144   for (; BI != DestBlock->end(); ++BI) {
145     Instruction *New = BI->clone();
146     New->setName(BI->getName());
147     SourceBlock->getInstList().push_back(New);
148     ValueMapping[BI] = New;
149   }
150
151   // Now that we have built the mapping information and cloned all of the
152   // instructions (giving us a new terminator, among other things), walk the new
153   // instructions, rewriting references of old instructions to use new
154   // instructions.
155   //
156   BI = Branch; ++BI;  // Get an iterator to the first new instruction
157   for (; BI != SourceBlock->end(); ++BI)
158     for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
159       if (Value *Remapped = ValueMapping[BI->getOperand(i)])
160         BI->setOperand(i, Remapped);
161
162   // Next we check to see if any of the successors of DestBlock had PHI nodes.
163   // If so, we need to add entries to the PHI nodes for SourceBlock now.
164   for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
165        SI != SE; ++SI) {
166     BasicBlock *Succ = *SI;
167     for (BasicBlock::iterator PNI = Succ->begin();
168          PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
169       // Ok, we have a PHI node.  Figure out what the incoming value was for the
170       // DestBlock.
171       Value *IV = PN->getIncomingValueForBlock(DestBlock);
172       
173       // Remap the value if necessary...
174       if (Value *MappedIV = ValueMapping[IV])
175         IV = MappedIV;
176       PN->addIncoming(IV, SourceBlock);
177     }
178   }
179   
180   // Now that all of the instructions are correctly copied into the SourceBlock,
181   // we have one more minor problem: the successors of the original DestBB may
182   // use the values computed in DestBB either directly (if DestBB dominated the
183   // block), or through a PHI node.  In either case, we need to insert PHI nodes
184   // into any successors of DestBB (which are now our successors) for each value
185   // that is computed in DestBB, but is used outside of it.  All of these uses
186   // we have to rewrite with the new PHI node.
187   //
188   if (succ_begin(SourceBlock) != succ_end(SourceBlock)) // Avoid wasting time...
189     for (BI = DestBlock->begin(); BI != DestBlock->end(); ++BI)
190       if (BI->getType() != Type::VoidTy)
191         InsertPHINodesIfNecessary(BI, ValueMapping[BI], SourceBlock);
192
193   // Final step: now that we have finished everything up, walk the cloned
194   // instructions one last time, constant propagating and DCE'ing them, because
195   // they may not be needed anymore.
196   //
197   BI = Branch; ++BI;  // Get an iterator to the first new instruction
198   if (HadPHINodes)
199     while (BI != SourceBlock->end())
200       if (!dceInstruction(BI) && !doConstantPropagation(BI))
201         ++BI;
202
203   DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
204   SourceBlock->getInstList().erase(Branch);  // Destroy the uncond branch...
205   
206   ++NumEliminated;  // We just killed a branch!
207 }
208
209 /// InsertPHINodesIfNecessary - So at this point, we cloned the OrigInst
210 /// instruction into the NewBlock with the value of NewInst.  If OrigInst was
211 /// used outside of its defining basic block, we need to insert a PHI nodes into
212 /// the successors.
213 ///
214 void TailDup::InsertPHINodesIfNecessary(Instruction *OrigInst, Value *NewInst,
215                                         BasicBlock *NewBlock) {
216   // Loop over all of the uses of OrigInst, rewriting them to be newly inserted
217   // PHI nodes, unless they are in the same basic block as OrigInst.
218   BasicBlock *OrigBlock = OrigInst->getParent();
219   std::vector<Instruction*> Users;
220   Users.reserve(OrigInst->use_size());
221   for (Value::use_iterator I = OrigInst->use_begin(), E = OrigInst->use_end();
222        I != E; ++I) {
223     Instruction *In = cast<Instruction>(*I);
224     if (In->getParent() != OrigBlock ||  // Don't modify uses in the orig block!
225         isa<PHINode>(In))
226       Users.push_back(In);
227   }
228
229   // The common case is that the instruction is only used within the block that
230   // defines it.  If we have this case, quick exit.
231   //
232   if (Users.empty()) return; 
233
234   // Otherwise, we have a more complex case, handle it now.  This requires the
235   // construction of a mapping between a basic block and the value to use when
236   // in the scope of that basic block.  This map will map to the original and
237   // new values when in the original or new block, but will map to inserted PHI
238   // nodes when in other blocks.
239   //
240   std::map<BasicBlock*, ValueHolder> ValueMap;
241   std::map<BasicBlock*, ValueHolder> OutValueMap;   // The outgoing value map
242   OutValueMap[OrigBlock] = OrigInst;
243   OutValueMap[NewBlock ] = NewInst;    // Seed the initial values...
244
245   DEBUG(std::cerr << "  ** Inserting PHI nodes for " << OrigInst);
246   while (!Users.empty()) {
247     Instruction *User = Users.back(); Users.pop_back();
248
249     if (PHINode *PN = dyn_cast<PHINode>(User)) {
250       // PHI nodes must be handled specially here, because their operands are
251       // actually defined in predecessor basic blocks, NOT in the block that the
252       // PHI node lives in.  Note that we have already added entries to PHI nods
253       // which are in blocks that are immediate successors of OrigBlock, so
254       // don't modify them again.
255       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
256         if (PN->getIncomingValue(i) == OrigInst &&
257             PN->getIncomingBlock(i) != OrigBlock) {
258           Value *V = GetValueOutBlock(PN->getIncomingBlock(i), OrigInst,
259                                       ValueMap, OutValueMap);
260           PN->setIncomingValue(i, V);
261         }
262       
263     } else {
264       // Any other user of the instruction can just replace any uses with the
265       // new value defined in the block it resides in.
266       Value *V = GetValueInBlock(User->getParent(), OrigInst, ValueMap,
267                                  OutValueMap);
268       User->replaceUsesOfWith(OrigInst, V);
269     }
270   }
271 }
272
273 /// GetValueInBlock - This is a recursive method which inserts PHI nodes into
274 /// the function until there is a value available in basic block BB.
275 ///
276 Value *TailDup::GetValueInBlock(BasicBlock *BB, Value *OrigVal,
277                                 std::map<BasicBlock*, ValueHolder> &ValueMap,
278                                 std::map<BasicBlock*,ValueHolder> &OutValueMap){
279   ValueHolder &BBVal = ValueMap[BB];
280   if (BBVal) return BBVal;       // Value already computed for this block?
281
282   // If this block has no predecessors, then it must be unreachable, thus, it
283   // doesn't matter which value we use.
284   if (pred_begin(BB) == pred_end(BB))
285     return BBVal = Constant::getNullValue(OrigVal->getType());
286
287   // If there is no value already available in this basic block, we need to
288   // either reuse a value from an incoming, dominating, basic block, or we need
289   // to create a new PHI node to merge in different incoming values.  Because we
290   // don't know if we're part of a loop at this point or not, we create a PHI
291   // node, even if we will ultimately eliminate it.
292   PHINode *PN = new PHINode(OrigVal->getType(), OrigVal->getName()+".pn",
293                             BB->begin());
294   BBVal = PN;   // Insert this into the BBVal slot in case of cycles...
295
296   ValueHolder &BBOutVal = OutValueMap[BB];
297   if (BBOutVal == 0) BBOutVal = PN;
298
299   // Now that we have created the PHI node, loop over all of the predecessors of
300   // this block, computing an incoming value for the predecessor.
301   std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
302   for (unsigned i = 0, e = Preds.size(); i != e; ++i)
303     PN->addIncoming(GetValueOutBlock(Preds[i], OrigVal, ValueMap, OutValueMap),
304                     Preds[i]);
305
306   // The PHI node is complete.  In many cases, however the PHI node was
307   // ultimately unnecessary: we could have just reused a dominating incoming
308   // value.  If this is the case, nuke the PHI node and replace the map entry
309   // with the dominating value.
310   //
311   assert(PN->getNumIncomingValues() > 0 && "No predecessors?");
312
313   // Check to see if all of the elements in the PHI node are either the PHI node
314   // itself or ONE particular value.
315   unsigned i = 0;
316   Value *ReplVal = PN->getIncomingValue(i);
317   for (; ReplVal == PN && i != PN->getNumIncomingValues(); ++i)
318     ReplVal = PN->getIncomingValue(i);  // Skip values equal to the PN
319
320   for (; i != PN->getNumIncomingValues(); ++i)
321     if (PN->getIncomingValue(i) != PN && PN->getIncomingValue(i) != ReplVal) {
322       ReplVal = 0;
323       break;
324     }
325
326   // Found a value to replace the PHI node with?
327   if (ReplVal && ReplVal != PN) {
328     PN->replaceAllUsesWith(ReplVal);
329     BB->getInstList().erase(PN);   // Erase the PHI node...
330   } else {
331     ++NumPHINodes;
332   }
333
334   return BBVal;
335 }
336
337 Value *TailDup::GetValueOutBlock(BasicBlock *BB, Value *OrigVal,
338                                  std::map<BasicBlock*, ValueHolder> &ValueMap,
339                               std::map<BasicBlock*, ValueHolder> &OutValueMap) {
340   ValueHolder &BBVal = OutValueMap[BB];
341   if (BBVal) return BBVal;       // Value already computed for this block?
342
343   return GetValueInBlock(BB, OrigVal, ValueMap, OutValueMap);
344 }
345
346 } // End llvm namespace