02eb4d6f60a66607ab60a0a34e3e9dd123c05adc
[oota-llvm.git] / lib / Transforms / Utils / BasicBlockUtils.cpp
1 //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
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 family of functions perform manipulations on basic blocks, and
11 // instructions contained within basic blocks.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Constant.h"
19 #include "llvm/Type.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include <algorithm>
24 using namespace llvm;
25
26 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
27 /// if possible.  The return value indicates success or failure.
28 bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
29   // Can't merge the entry block.
30   if (pred_begin(BB) == pred_end(BB)) return false;
31   // Can't merge if there are multiple preds.
32   if (++pred_begin(BB) != pred_end(BB)) return false;
33   
34   BasicBlock* PredBB = *pred_begin(BB);
35   
36   // Can't merge if the edge is critical.
37   if (PredBB->getTerminator()->getNumSuccessors() != 1) return false;
38   
39   // Begin by getting rid of unneeded PHIs.
40   while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
41     PN->replaceAllUsesWith(PN->getIncomingValue(0));
42     BB->getInstList().pop_front();  // Delete the phi node...
43   }
44   
45   // Delete the unconditional branch from the predecessor...
46   PredBB->getInstList().pop_back();
47   
48   // Move all definitions in the successor to the predecessor...
49   PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
50   
51   // Make all PHI nodes that referred to BB now refer to Pred as their
52   // source...
53   BB->replaceAllUsesWith(PredBB);
54   
55   // Finally, erase the old block and update dominator info.
56   if (P) {
57     if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) {
58       DomTreeNode* DTN = DT->getNode(BB);
59       DomTreeNode* PredDTN = DT->getNode(PredBB);
60   
61       if (DTN) {
62         SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
63         for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
64              DE = Children.end(); DI != DE; ++DI)
65           DT->changeImmediateDominator(*DI, PredDTN);
66
67         DT->eraseNode(BB);
68       }
69     }
70   }
71   
72   BB->eraseFromParent();
73   
74   
75   return true;
76 }
77
78 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
79 /// with a value, then remove and delete the original instruction.
80 ///
81 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
82                                 BasicBlock::iterator &BI, Value *V) {
83   Instruction &I = *BI;
84   // Replaces all of the uses of the instruction with uses of the value
85   I.replaceAllUsesWith(V);
86
87   // Make sure to propagate a name if there is one already.
88   if (I.hasName() && !V->hasName())
89     V->takeName(&I);
90
91   // Delete the unnecessary instruction now...
92   BI = BIL.erase(BI);
93 }
94
95
96 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
97 /// instruction specified by I.  The original instruction is deleted and BI is
98 /// updated to point to the new instruction.
99 ///
100 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
101                                BasicBlock::iterator &BI, Instruction *I) {
102   assert(I->getParent() == 0 &&
103          "ReplaceInstWithInst: Instruction already inserted into basic block!");
104
105   // Insert the new instruction into the basic block...
106   BasicBlock::iterator New = BIL.insert(BI, I);
107
108   // Replace all uses of the old instruction, and delete it.
109   ReplaceInstWithValue(BIL, BI, I);
110
111   // Move BI back to point to the newly inserted instruction
112   BI = New;
113 }
114
115 /// ReplaceInstWithInst - Replace the instruction specified by From with the
116 /// instruction specified by To.
117 ///
118 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
119   BasicBlock::iterator BI(From);
120   ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
121 }
122
123 /// RemoveSuccessor - Change the specified terminator instruction such that its
124 /// successor SuccNum no longer exists.  Because this reduces the outgoing
125 /// degree of the current basic block, the actual terminator instruction itself
126 /// may have to be changed.  In the case where the last successor of the block 
127 /// is deleted, a return instruction is inserted in its place which can cause a
128 /// surprising change in program behavior if it is not expected.
129 ///
130 void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
131   assert(SuccNum < TI->getNumSuccessors() &&
132          "Trying to remove a nonexistant successor!");
133
134   // If our old successor block contains any PHI nodes, remove the entry in the
135   // PHI nodes that comes from this branch...
136   //
137   BasicBlock *BB = TI->getParent();
138   TI->getSuccessor(SuccNum)->removePredecessor(BB);
139
140   TerminatorInst *NewTI = 0;
141   switch (TI->getOpcode()) {
142   case Instruction::Br:
143     // If this is a conditional branch... convert to unconditional branch.
144     if (TI->getNumSuccessors() == 2) {
145       cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
146     } else {                    // Otherwise convert to a return instruction...
147       Value *RetVal = 0;
148
149       // Create a value to return... if the function doesn't return null...
150       if (BB->getParent()->getReturnType() != Type::VoidTy)
151         RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
152
153       // Create the return...
154       NewTI = ReturnInst::Create(RetVal);
155     }
156     break;
157
158   case Instruction::Invoke:    // Should convert to call
159   case Instruction::Switch:    // Should remove entry
160   default:
161   case Instruction::Ret:       // Cannot happen, has no successors!
162     assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
163     abort();
164   }
165
166   if (NewTI)   // If it's a different instruction, replace.
167     ReplaceInstWithInst(TI, NewTI);
168 }
169
170 /// SplitEdge -  Split the edge connecting specified block. Pass P must 
171 /// not be NULL. 
172 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
173   TerminatorInst *LatchTerm = BB->getTerminator();
174   unsigned SuccNum = 0;
175   for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
176     assert(i != e && "Didn't find edge?");
177     if (LatchTerm->getSuccessor(i) == Succ) {
178       SuccNum = i;
179       break;
180     }
181   }
182   
183   // If this is a critical edge, let SplitCriticalEdge do it.
184   if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
185     return LatchTerm->getSuccessor(SuccNum);
186
187   // If the edge isn't critical, then BB has a single successor or Succ has a
188   // single pred.  Split the block.
189   BasicBlock::iterator SplitPoint;
190   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
191     // If the successor only has a single pred, split the top of the successor
192     // block.
193     assert(SP == BB && "CFG broken");
194     return SplitBlock(Succ, Succ->begin(), P);
195   } else {
196     // Otherwise, if BB has a single successor, split it at the bottom of the
197     // block.
198     assert(BB->getTerminator()->getNumSuccessors() == 1 &&
199            "Should have a single succ!"); 
200     return SplitBlock(BB, BB->getTerminator(), P);
201   }
202 }
203
204 /// SplitBlock - Split the specified block at the specified instruction - every
205 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
206 /// to a new block.  The two blocks are joined by an unconditional branch and
207 /// the loop info is updated.
208 ///
209 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
210
211   LoopInfo &LI = P->getAnalysis<LoopInfo>();
212   BasicBlock::iterator SplitIt = SplitPt;
213   while (isa<PHINode>(SplitIt))
214     ++SplitIt;
215   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
216
217   // The new block lives in whichever loop the old one did.
218   if (Loop *L = LI.getLoopFor(Old))
219     L->addBasicBlockToLoop(New, LI.getBase());
220
221   if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>()) 
222     {
223       // Old dominates New. New node domiantes all other nodes dominated by Old.
224       DomTreeNode *OldNode = DT->getNode(Old);
225       std::vector<DomTreeNode *> Children;
226       for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
227            I != E; ++I) 
228         Children.push_back(*I);
229
230       DomTreeNode *NewNode =   DT->addNewBlock(New,Old);
231
232       for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
233              E = Children.end(); I != E; ++I) 
234         DT->changeImmediateDominator(*I, NewNode);
235     }
236
237   if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
238     DF->splitBlock(Old);
239     
240   return New;
241 }
242
243
244 /// SplitBlockPredecessors - This method transforms BB by introducing a new
245 /// basic block into the function, and moving some of the predecessors of BB to
246 /// be predecessors of the new block.  The new predecessors are indicated by the
247 /// Preds array, which has NumPreds elements in it.  The new block is given a
248 /// suffix of 'Suffix'.
249 ///
250 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
251 /// DominanceFrontier, but no other analyses.
252 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 
253                                          BasicBlock *const *Preds,
254                                          unsigned NumPreds, const char *Suffix,
255                                          Pass *P) {
256   // Create new basic block, insert right before the original block.
257   BasicBlock *NewBB =
258     BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
259   
260   // The new block unconditionally branches to the old block.
261   BranchInst *BI = BranchInst::Create(BB, NewBB);
262   
263   // Move the edges from Preds to point to NewBB instead of BB.
264   for (unsigned i = 0; i != NumPreds; ++i)
265     Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
266   
267   // Update dominator tree and dominator frontier if available.
268   DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
269   if (DT)
270     DT->splitBlock(NewBB);
271   if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
272     DF->splitBlock(NewBB);
273   AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
274   
275   
276   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
277   // node becomes an incoming value for BB's phi node.  However, if the Preds
278   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
279   // account for the newly created predecessor.
280   if (NumPreds == 0) {
281     // Insert dummy values as the incoming value.
282     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
283       cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
284     return NewBB;
285   }
286   
287   // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
288   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
289     PHINode *PN = cast<PHINode>(I++);
290     
291     // Check to see if all of the values coming in are the same.  If so, we
292     // don't need to create a new PHI node.
293     Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
294     for (unsigned i = 1; i != NumPreds; ++i)
295       if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
296         InVal = 0;
297         break;
298       }
299     
300     if (InVal) {
301       // If all incoming values for the new PHI would be the same, just don't
302       // make a new PHI.  Instead, just remove the incoming values from the old
303       // PHI.
304       for (unsigned i = 0; i != NumPreds; ++i)
305         PN->removeIncomingValue(Preds[i], false);
306     } else {
307       // If the values coming into the block are not the same, we need a PHI.
308       // Create the new PHI node, insert it into NewBB at the end of the block
309       PHINode *NewPHI =
310         PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
311       if (AA) AA->copyValue(PN, NewPHI);
312       
313       // Move all of the PHI values for 'Preds' to the new PHI.
314       for (unsigned i = 0; i != NumPreds; ++i) {
315         Value *V = PN->removeIncomingValue(Preds[i], false);
316         NewPHI->addIncoming(V, Preds[i]);
317       }
318       InVal = NewPHI;
319     }
320     
321     // Add an incoming value to the PHI node in the loop for the preheader
322     // edge.
323     PN->addIncoming(InVal, NewBB);
324     
325     // Check to see if we can eliminate this phi node.
326     if (Value *V = PN->hasConstantValue(DT != 0)) {
327       Instruction *I = dyn_cast<Instruction>(V);
328       if (!I || DT == 0 || DT->dominates(I, PN)) {
329         PN->replaceAllUsesWith(V);
330         if (AA) AA->deleteValue(PN);
331         PN->eraseFromParent();
332       }
333     }
334   }
335   
336   return NewBB;
337 }