Move FindAvailableLoadedValue isSafeToLoadUnconditionally out of
[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/IntrinsicInst.h"
19 #include "llvm/Constant.h"
20 #include "llvm/Type.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Transforms/Utils/Local.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ValueHandle.h"
29 #include <algorithm>
30 using namespace llvm;
31
32 /// DeleteDeadBlock - Delete the specified block, which must have no
33 /// predecessors.
34 void llvm::DeleteDeadBlock(BasicBlock *BB) {
35   assert((pred_begin(BB) == pred_end(BB) ||
36          // Can delete self loop.
37          BB->getSinglePredecessor() == BB) && "Block is not dead!");
38   TerminatorInst *BBTerm = BB->getTerminator();
39   
40   // Loop through all of our successors and make sure they know that one
41   // of their predecessors is going away.
42   for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
43     BBTerm->getSuccessor(i)->removePredecessor(BB);
44   
45   // Zap all the instructions in the block.
46   while (!BB->empty()) {
47     Instruction &I = BB->back();
48     // If this instruction is used, replace uses with an arbitrary value.
49     // Because control flow can't get here, we don't care what we replace the
50     // value with.  Note that since this block is unreachable, and all values
51     // contained within it must dominate their uses, that all uses will
52     // eventually be removed (they are themselves dead).
53     if (!I.use_empty())
54       I.replaceAllUsesWith(UndefValue::get(I.getType()));
55     BB->getInstList().pop_back();
56   }
57   
58   // Zap the block!
59   BB->eraseFromParent();
60 }
61
62 /// FoldSingleEntryPHINodes - We know that BB has one predecessor.  If there are
63 /// any single-entry PHI nodes in it, fold them away.  This handles the case
64 /// when all entries to the PHI nodes in a block are guaranteed equal, such as
65 /// when the block has exactly one predecessor.
66 void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
67   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
68     if (PN->getIncomingValue(0) != PN)
69       PN->replaceAllUsesWith(PN->getIncomingValue(0));
70     else
71       PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
72     PN->eraseFromParent();
73   }
74 }
75
76
77 /// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
78 /// is dead. Also recursively delete any operands that become dead as
79 /// a result. This includes tracing the def-use list from the PHI to see if
80 /// it is ultimately unused or if it reaches an unused cycle.
81 bool llvm::DeleteDeadPHIs(BasicBlock *BB) {
82   // Recursively deleting a PHI may cause multiple PHIs to be deleted
83   // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
84   SmallVector<WeakVH, 8> PHIs;
85   for (BasicBlock::iterator I = BB->begin();
86        PHINode *PN = dyn_cast<PHINode>(I); ++I)
87     PHIs.push_back(PN);
88
89   bool Changed = false;
90   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
91     if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
92       Changed |= RecursivelyDeleteDeadPHINode(PN);
93
94   return Changed;
95 }
96
97 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
98 /// if possible.  The return value indicates success or failure.
99 bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
100   pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
101   // Can't merge the entry block.  Don't merge away blocks who have their
102   // address taken: this is a bug if the predecessor block is the entry node
103   // (because we'd end up taking the address of the entry) and undesirable in
104   // any case.
105   if (pred_begin(BB) == pred_end(BB) ||
106       BB->hasAddressTaken()) return false;
107   
108   BasicBlock *PredBB = *PI++;
109   for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
110     if (*PI != PredBB) {
111       PredBB = 0;       // There are multiple different predecessors...
112       break;
113     }
114   
115   // Can't merge if there are multiple predecessors.
116   if (!PredBB) return false;
117   // Don't break self-loops.
118   if (PredBB == BB) return false;
119   // Don't break invokes.
120   if (isa<InvokeInst>(PredBB->getTerminator())) return false;
121   
122   succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
123   BasicBlock* OnlySucc = BB;
124   for (; SI != SE; ++SI)
125     if (*SI != OnlySucc) {
126       OnlySucc = 0;     // There are multiple distinct successors!
127       break;
128     }
129   
130   // Can't merge if there are multiple successors.
131   if (!OnlySucc) return false;
132
133   // Can't merge if there is PHI loop.
134   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
135     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
136       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
137         if (PN->getIncomingValue(i) == PN)
138           return false;
139     } else
140       break;
141   }
142
143   // Begin by getting rid of unneeded PHIs.
144   while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
145     PN->replaceAllUsesWith(PN->getIncomingValue(0));
146     BB->getInstList().pop_front();  // Delete the phi node...
147   }
148   
149   // Delete the unconditional branch from the predecessor...
150   PredBB->getInstList().pop_back();
151   
152   // Move all definitions in the successor to the predecessor...
153   PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
154   
155   // Make all PHI nodes that referred to BB now refer to Pred as their
156   // source...
157   BB->replaceAllUsesWith(PredBB);
158   
159   // Inherit predecessors name if it exists.
160   if (!PredBB->hasName())
161     PredBB->takeName(BB);
162   
163   // Finally, erase the old block and update dominator info.
164   if (P) {
165     if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
166       DomTreeNode* DTN = DT->getNode(BB);
167       DomTreeNode* PredDTN = DT->getNode(PredBB);
168   
169       if (DTN) {
170         SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
171         for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
172              DE = Children.end(); DI != DE; ++DI)
173           DT->changeImmediateDominator(*DI, PredDTN);
174
175         DT->eraseNode(BB);
176       }
177     }
178   }
179   
180   BB->eraseFromParent();
181   
182   
183   return true;
184 }
185
186 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
187 /// with a value, then remove and delete the original instruction.
188 ///
189 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
190                                 BasicBlock::iterator &BI, Value *V) {
191   Instruction &I = *BI;
192   // Replaces all of the uses of the instruction with uses of the value
193   I.replaceAllUsesWith(V);
194
195   // Make sure to propagate a name if there is one already.
196   if (I.hasName() && !V->hasName())
197     V->takeName(&I);
198
199   // Delete the unnecessary instruction now...
200   BI = BIL.erase(BI);
201 }
202
203
204 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
205 /// instruction specified by I.  The original instruction is deleted and BI is
206 /// updated to point to the new instruction.
207 ///
208 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
209                                BasicBlock::iterator &BI, Instruction *I) {
210   assert(I->getParent() == 0 &&
211          "ReplaceInstWithInst: Instruction already inserted into basic block!");
212
213   // Insert the new instruction into the basic block...
214   BasicBlock::iterator New = BIL.insert(BI, I);
215
216   // Replace all uses of the old instruction, and delete it.
217   ReplaceInstWithValue(BIL, BI, I);
218
219   // Move BI back to point to the newly inserted instruction
220   BI = New;
221 }
222
223 /// ReplaceInstWithInst - Replace the instruction specified by From with the
224 /// instruction specified by To.
225 ///
226 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
227   BasicBlock::iterator BI(From);
228   ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
229 }
230
231 /// RemoveSuccessor - Change the specified terminator instruction such that its
232 /// successor SuccNum no longer exists.  Because this reduces the outgoing
233 /// degree of the current basic block, the actual terminator instruction itself
234 /// may have to be changed.  In the case where the last successor of the block 
235 /// is deleted, a return instruction is inserted in its place which can cause a
236 /// surprising change in program behavior if it is not expected.
237 ///
238 void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
239   assert(SuccNum < TI->getNumSuccessors() &&
240          "Trying to remove a nonexistant successor!");
241
242   // If our old successor block contains any PHI nodes, remove the entry in the
243   // PHI nodes that comes from this branch...
244   //
245   BasicBlock *BB = TI->getParent();
246   TI->getSuccessor(SuccNum)->removePredecessor(BB);
247
248   TerminatorInst *NewTI = 0;
249   switch (TI->getOpcode()) {
250   case Instruction::Br:
251     // If this is a conditional branch... convert to unconditional branch.
252     if (TI->getNumSuccessors() == 2) {
253       cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
254     } else {                    // Otherwise convert to a return instruction...
255       Value *RetVal = 0;
256
257       // Create a value to return... if the function doesn't return null...
258       if (!BB->getParent()->getReturnType()->isVoidTy())
259         RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
260
261       // Create the return...
262       NewTI = ReturnInst::Create(TI->getContext(), RetVal);
263     }
264     break;
265
266   case Instruction::Invoke:    // Should convert to call
267   case Instruction::Switch:    // Should remove entry
268   default:
269   case Instruction::Ret:       // Cannot happen, has no successors!
270     llvm_unreachable("Unhandled terminator instruction type in RemoveSuccessor!");
271   }
272
273   if (NewTI)   // If it's a different instruction, replace.
274     ReplaceInstWithInst(TI, NewTI);
275 }
276
277 /// GetSuccessorNumber - Search for the specified successor of basic block BB
278 /// and return its position in the terminator instruction's list of
279 /// successors.  It is an error to call this with a block that is not a
280 /// successor.
281 unsigned llvm::GetSuccessorNumber(BasicBlock *BB, BasicBlock *Succ) {
282   TerminatorInst *Term = BB->getTerminator();
283 #ifndef NDEBUG
284   unsigned e = Term->getNumSuccessors();
285 #endif
286   for (unsigned i = 0; ; ++i) {
287     assert(i != e && "Didn't find edge?");
288     if (Term->getSuccessor(i) == Succ)
289       return i;
290   }
291   return 0;
292 }
293
294 /// SplitEdge -  Split the edge connecting specified block. Pass P must 
295 /// not be NULL. 
296 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
297   unsigned SuccNum = GetSuccessorNumber(BB, Succ);
298   
299   // If this is a critical edge, let SplitCriticalEdge do it.
300   TerminatorInst *LatchTerm = BB->getTerminator();
301   if (SplitCriticalEdge(LatchTerm, SuccNum, P))
302     return LatchTerm->getSuccessor(SuccNum);
303
304   // If the edge isn't critical, then BB has a single successor or Succ has a
305   // single pred.  Split the block.
306   BasicBlock::iterator SplitPoint;
307   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
308     // If the successor only has a single pred, split the top of the successor
309     // block.
310     assert(SP == BB && "CFG broken");
311     SP = NULL;
312     return SplitBlock(Succ, Succ->begin(), P);
313   } else {
314     // Otherwise, if BB has a single successor, split it at the bottom of the
315     // block.
316     assert(BB->getTerminator()->getNumSuccessors() == 1 &&
317            "Should have a single succ!"); 
318     return SplitBlock(BB, BB->getTerminator(), P);
319   }
320 }
321
322 /// SplitBlock - Split the specified block at the specified instruction - every
323 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
324 /// to a new block.  The two blocks are joined by an unconditional branch and
325 /// the loop info is updated.
326 ///
327 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
328   BasicBlock::iterator SplitIt = SplitPt;
329   while (isa<PHINode>(SplitIt))
330     ++SplitIt;
331   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
332
333   // The new block lives in whichever loop the old one did. This preserves
334   // LCSSA as well, because we force the split point to be after any PHI nodes.
335   if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
336     if (Loop *L = LI->getLoopFor(Old))
337       L->addBasicBlockToLoop(New, LI->getBase());
338
339   if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) {
340     // Old dominates New. New node domiantes all other nodes dominated by Old.
341     DomTreeNode *OldNode = DT->getNode(Old);
342     std::vector<DomTreeNode *> Children;
343     for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
344          I != E; ++I) 
345       Children.push_back(*I);
346
347       DomTreeNode *NewNode = DT->addNewBlock(New,Old);
348       for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
349              E = Children.end(); I != E; ++I) 
350         DT->changeImmediateDominator(*I, NewNode);
351   }
352
353   if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
354     DF->splitBlock(Old);
355     
356   return New;
357 }
358
359
360 /// SplitBlockPredecessors - This method transforms BB by introducing a new
361 /// basic block into the function, and moving some of the predecessors of BB to
362 /// be predecessors of the new block.  The new predecessors are indicated by the
363 /// Preds array, which has NumPreds elements in it.  The new block is given a
364 /// suffix of 'Suffix'.
365 ///
366 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
367 /// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
368 /// In particular, it does not preserve LoopSimplify (because it's
369 /// complicated to handle the case where one of the edges being split
370 /// is an exit of a loop with other exits).
371 ///
372 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 
373                                          BasicBlock *const *Preds,
374                                          unsigned NumPreds, const char *Suffix,
375                                          Pass *P) {
376   // Create new basic block, insert right before the original block.
377   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
378                                          BB->getParent(), BB);
379   
380   // The new block unconditionally branches to the old block.
381   BranchInst *BI = BranchInst::Create(BB, NewBB);
382   
383   LoopInfo *LI = P ? P->getAnalysisIfAvailable<LoopInfo>() : 0;
384   Loop *L = LI ? LI->getLoopFor(BB) : 0;
385   bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
386
387   // Move the edges from Preds to point to NewBB instead of BB.
388   // While here, if we need to preserve loop analyses, collect
389   // some information about how this split will affect loops.
390   bool HasLoopExit = false;
391   bool IsLoopEntry = !!L;
392   bool SplitMakesNewLoopHeader = false;
393   for (unsigned i = 0; i != NumPreds; ++i) {
394     // This is slightly more strict than necessary; the minimum requirement
395     // is that there be no more than one indirectbr branching to BB. And
396     // all BlockAddress uses would need to be updated.
397     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
398            "Cannot split an edge from an IndirectBrInst");
399
400     Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
401
402     if (LI) {
403       // If we need to preserve LCSSA, determine if any of
404       // the preds is a loop exit.
405       if (PreserveLCSSA)
406         if (Loop *PL = LI->getLoopFor(Preds[i]))
407           if (!PL->contains(BB))
408             HasLoopExit = true;
409       // If we need to preserve LoopInfo, note whether any of the
410       // preds crosses an interesting loop boundary.
411       if (L) {
412         if (L->contains(Preds[i]))
413           IsLoopEntry = false;
414         else
415           SplitMakesNewLoopHeader = true;
416       }
417     }
418   }
419
420   // Update dominator tree and dominator frontier if available.
421   DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
422   if (DT)
423     DT->splitBlock(NewBB);
424   if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
425     DF->splitBlock(NewBB);
426
427   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
428   // node becomes an incoming value for BB's phi node.  However, if the Preds
429   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
430   // account for the newly created predecessor.
431   if (NumPreds == 0) {
432     // Insert dummy values as the incoming value.
433     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
434       cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
435     return NewBB;
436   }
437
438   AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
439
440   if (L) {
441     if (IsLoopEntry) {
442       // Add the new block to the nearest enclosing loop (and not an
443       // adjacent loop). To find this, examine each of the predecessors and
444       // determine which loops enclose them, and select the most-nested loop
445       // which contains the loop containing the block being split.
446       Loop *InnermostPredLoop = 0;
447       for (unsigned i = 0; i != NumPreds; ++i)
448         if (Loop *PredLoop = LI->getLoopFor(Preds[i])) {
449           // Seek a loop which actually contains the block being split (to
450           // avoid adjacent loops).
451           while (PredLoop && !PredLoop->contains(BB))
452             PredLoop = PredLoop->getParentLoop();
453           // Select the most-nested of these loops which contains the block.
454           if (PredLoop &&
455               PredLoop->contains(BB) &&
456               (!InnermostPredLoop ||
457                InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
458             InnermostPredLoop = PredLoop;
459         }
460       if (InnermostPredLoop)
461         InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
462     } else {
463       L->addBasicBlockToLoop(NewBB, LI->getBase());
464       if (SplitMakesNewLoopHeader)
465         L->moveToHeader(NewBB);
466     }
467   }
468   
469   // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
470   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
471     PHINode *PN = cast<PHINode>(I++);
472     
473     // Check to see if all of the values coming in are the same.  If so, we
474     // don't need to create a new PHI node, unless it's needed for LCSSA.
475     Value *InVal = 0;
476     if (!HasLoopExit) {
477       InVal = PN->getIncomingValueForBlock(Preds[0]);
478       for (unsigned i = 1; i != NumPreds; ++i)
479         if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
480           InVal = 0;
481           break;
482         }
483     }
484
485     if (InVal) {
486       // If all incoming values for the new PHI would be the same, just don't
487       // make a new PHI.  Instead, just remove the incoming values from the old
488       // PHI.
489       for (unsigned i = 0; i != NumPreds; ++i)
490         PN->removeIncomingValue(Preds[i], false);
491     } else {
492       // If the values coming into the block are not the same, we need a PHI.
493       // Create the new PHI node, insert it into NewBB at the end of the block
494       PHINode *NewPHI =
495         PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
496       if (AA) AA->copyValue(PN, NewPHI);
497       
498       // Move all of the PHI values for 'Preds' to the new PHI.
499       for (unsigned i = 0; i != NumPreds; ++i) {
500         Value *V = PN->removeIncomingValue(Preds[i], false);
501         NewPHI->addIncoming(V, Preds[i]);
502       }
503       InVal = NewPHI;
504     }
505     
506     // Add an incoming value to the PHI node in the loop for the preheader
507     // edge.
508     PN->addIncoming(InVal, NewBB);
509   }
510   
511   return NewBB;
512 }
513
514 /// FindFunctionBackedges - Analyze the specified function to find all of the
515 /// loop backedges in the function and return them.  This is a relatively cheap
516 /// (compared to computing dominators and loop info) analysis.
517 ///
518 /// The output is added to Result, as pairs of <from,to> edge info.
519 void llvm::FindFunctionBackedges(const Function &F,
520      SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
521   const BasicBlock *BB = &F.getEntryBlock();
522   if (succ_begin(BB) == succ_end(BB))
523     return;
524   
525   SmallPtrSet<const BasicBlock*, 8> Visited;
526   SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
527   SmallPtrSet<const BasicBlock*, 8> InStack;
528   
529   Visited.insert(BB);
530   VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
531   InStack.insert(BB);
532   do {
533     std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
534     const BasicBlock *ParentBB = Top.first;
535     succ_const_iterator &I = Top.second;
536     
537     bool FoundNew = false;
538     while (I != succ_end(ParentBB)) {
539       BB = *I++;
540       if (Visited.insert(BB)) {
541         FoundNew = true;
542         break;
543       }
544       // Successor is in VisitStack, it's a back edge.
545       if (InStack.count(BB))
546         Result.push_back(std::make_pair(ParentBB, BB));
547     }
548     
549     if (FoundNew) {
550       // Go down one level if there is a unvisited successor.
551       InStack.insert(BB);
552       VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
553     } else {
554       // Go up one level.
555       InStack.erase(VisitStack.pop_back_val().first);
556     }
557   } while (!VisitStack.empty());
558   
559   
560 }