More LLVMContext-ification.
[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/LLVMContext.h"
20 #include "llvm/Constant.h"
21 #include "llvm/Type.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 #include "llvm/Support/ValueHandle.h"
28 #include <algorithm>
29 using namespace llvm;
30
31 /// DeleteDeadBlock - Delete the specified block, which must have no
32 /// predecessors.
33 void llvm::DeleteDeadBlock(BasicBlock *BB) {
34   assert((pred_begin(BB) == pred_end(BB) ||
35          // Can delete self loop.
36          BB->getSinglePredecessor() == BB) && "Block is not dead!");
37   TerminatorInst *BBTerm = BB->getTerminator();
38   
39   // Loop through all of our successors and make sure they know that one
40   // of their predecessors is going away.
41   for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
42     BBTerm->getSuccessor(i)->removePredecessor(BB);
43   
44   // Zap all the instructions in the block.
45   while (!BB->empty()) {
46     Instruction &I = BB->back();
47     // If this instruction is used, replace uses with an arbitrary value.
48     // Because control flow can't get here, we don't care what we replace the
49     // value with.  Note that since this block is unreachable, and all values
50     // contained within it must dominate their uses, that all uses will
51     // eventually be removed (they are themselves dead).
52     if (!I.use_empty())
53       I.replaceAllUsesWith(BB->getContext()->getUndef(I.getType()));
54     BB->getInstList().pop_back();
55   }
56   
57   // Zap the block!
58   BB->eraseFromParent();
59 }
60
61 /// FoldSingleEntryPHINodes - We know that BB has one predecessor.  If there are
62 /// any single-entry PHI nodes in it, fold them away.  This handles the case
63 /// when all entries to the PHI nodes in a block are guaranteed equal, such as
64 /// when the block has exactly one predecessor.
65 void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
66   if (!isa<PHINode>(BB->begin()))
67     return;
68   
69   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
70     if (PN->getIncomingValue(0) != PN)
71       PN->replaceAllUsesWith(PN->getIncomingValue(0));
72     else
73       PN->replaceAllUsesWith(BB->getContext()->getUndef(PN->getType()));
74     PN->eraseFromParent();
75   }
76 }
77
78
79 /// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
80 /// is dead. Also recursively delete any operands that become dead as
81 /// a result. This includes tracing the def-use list from the PHI to see if
82 /// it is ultimately unused or if it reaches an unused cycle.
83 void llvm::DeleteDeadPHIs(BasicBlock *BB) {
84   // Recursively deleting a PHI may cause multiple PHIs to be deleted
85   // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
86   SmallVector<WeakVH, 8> PHIs;
87   for (BasicBlock::iterator I = BB->begin();
88        PHINode *PN = dyn_cast<PHINode>(I); ++I)
89     PHIs.push_back(PN);
90
91   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
92     if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
93       RecursivelyDeleteDeadPHINode(PN);
94 }
95
96 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
97 /// if possible.  The return value indicates success or failure.
98 bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
99   pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
100   // Can't merge the entry block.
101   if (pred_begin(BB) == pred_end(BB)) return false;
102   
103   BasicBlock *PredBB = *PI++;
104   for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
105     if (*PI != PredBB) {
106       PredBB = 0;       // There are multiple different predecessors...
107       break;
108     }
109   
110   // Can't merge if there are multiple predecessors.
111   if (!PredBB) return false;
112   // Don't break self-loops.
113   if (PredBB == BB) return false;
114   // Don't break invokes.
115   if (isa<InvokeInst>(PredBB->getTerminator())) return false;
116   
117   succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
118   BasicBlock* OnlySucc = BB;
119   for (; SI != SE; ++SI)
120     if (*SI != OnlySucc) {
121       OnlySucc = 0;     // There are multiple distinct successors!
122       break;
123     }
124   
125   // Can't merge if there are multiple successors.
126   if (!OnlySucc) return false;
127
128   // Can't merge if there is PHI loop.
129   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
130     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
131       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
132         if (PN->getIncomingValue(i) == PN)
133           return false;
134     } else
135       break;
136   }
137
138   // Begin by getting rid of unneeded PHIs.
139   while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
140     PN->replaceAllUsesWith(PN->getIncomingValue(0));
141     BB->getInstList().pop_front();  // Delete the phi node...
142   }
143   
144   // Delete the unconditional branch from the predecessor...
145   PredBB->getInstList().pop_back();
146   
147   // Move all definitions in the successor to the predecessor...
148   PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
149   
150   // Make all PHI nodes that referred to BB now refer to Pred as their
151   // source...
152   BB->replaceAllUsesWith(PredBB);
153   
154   // Inherit predecessors name if it exists.
155   if (!PredBB->hasName())
156     PredBB->takeName(BB);
157   
158   // Finally, erase the old block and update dominator info.
159   if (P) {
160     if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
161       DomTreeNode* DTN = DT->getNode(BB);
162       DomTreeNode* PredDTN = DT->getNode(PredBB);
163   
164       if (DTN) {
165         SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
166         for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
167              DE = Children.end(); DI != DE; ++DI)
168           DT->changeImmediateDominator(*DI, PredDTN);
169
170         DT->eraseNode(BB);
171       }
172     }
173   }
174   
175   BB->eraseFromParent();
176   
177   
178   return true;
179 }
180
181 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
182 /// with a value, then remove and delete the original instruction.
183 ///
184 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
185                                 BasicBlock::iterator &BI, Value *V) {
186   Instruction &I = *BI;
187   // Replaces all of the uses of the instruction with uses of the value
188   I.replaceAllUsesWith(V);
189
190   // Make sure to propagate a name if there is one already.
191   if (I.hasName() && !V->hasName())
192     V->takeName(&I);
193
194   // Delete the unnecessary instruction now...
195   BI = BIL.erase(BI);
196 }
197
198
199 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
200 /// instruction specified by I.  The original instruction is deleted and BI is
201 /// updated to point to the new instruction.
202 ///
203 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
204                                BasicBlock::iterator &BI, Instruction *I) {
205   assert(I->getParent() == 0 &&
206          "ReplaceInstWithInst: Instruction already inserted into basic block!");
207
208   // Insert the new instruction into the basic block...
209   BasicBlock::iterator New = BIL.insert(BI, I);
210
211   // Replace all uses of the old instruction, and delete it.
212   ReplaceInstWithValue(BIL, BI, I);
213
214   // Move BI back to point to the newly inserted instruction
215   BI = New;
216 }
217
218 /// ReplaceInstWithInst - Replace the instruction specified by From with the
219 /// instruction specified by To.
220 ///
221 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
222   BasicBlock::iterator BI(From);
223   ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
224 }
225
226 /// RemoveSuccessor - Change the specified terminator instruction such that its
227 /// successor SuccNum no longer exists.  Because this reduces the outgoing
228 /// degree of the current basic block, the actual terminator instruction itself
229 /// may have to be changed.  In the case where the last successor of the block 
230 /// is deleted, a return instruction is inserted in its place which can cause a
231 /// surprising change in program behavior if it is not expected.
232 ///
233 void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
234   assert(SuccNum < TI->getNumSuccessors() &&
235          "Trying to remove a nonexistant successor!");
236
237   // If our old successor block contains any PHI nodes, remove the entry in the
238   // PHI nodes that comes from this branch...
239   //
240   BasicBlock *BB = TI->getParent();
241   TI->getSuccessor(SuccNum)->removePredecessor(BB);
242
243   TerminatorInst *NewTI = 0;
244   switch (TI->getOpcode()) {
245   case Instruction::Br:
246     // If this is a conditional branch... convert to unconditional branch.
247     if (TI->getNumSuccessors() == 2) {
248       cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
249     } else {                    // Otherwise convert to a return instruction...
250       Value *RetVal = 0;
251
252       // Create a value to return... if the function doesn't return null...
253       if (BB->getParent()->getReturnType() != Type::VoidTy)
254         RetVal = TI->getParent()->getContext()->getNullValue(
255                    BB->getParent()->getReturnType());
256
257       // Create the return...
258       NewTI = ReturnInst::Create(RetVal);
259     }
260     break;
261
262   case Instruction::Invoke:    // Should convert to call
263   case Instruction::Switch:    // Should remove entry
264   default:
265   case Instruction::Ret:       // Cannot happen, has no successors!
266     assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
267     abort();
268   }
269
270   if (NewTI)   // If it's a different instruction, replace.
271     ReplaceInstWithInst(TI, NewTI);
272 }
273
274 /// SplitEdge -  Split the edge connecting specified block. Pass P must 
275 /// not be NULL. 
276 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
277   TerminatorInst *LatchTerm = BB->getTerminator();
278   unsigned SuccNum = 0;
279 #ifndef NDEBUG
280   unsigned e = LatchTerm->getNumSuccessors();
281 #endif
282   for (unsigned i = 0; ; ++i) {
283     assert(i != e && "Didn't find edge?");
284     if (LatchTerm->getSuccessor(i) == Succ) {
285       SuccNum = i;
286       break;
287     }
288   }
289   
290   // If this is a critical edge, let SplitCriticalEdge do it.
291   if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
292     return LatchTerm->getSuccessor(SuccNum);
293
294   // If the edge isn't critical, then BB has a single successor or Succ has a
295   // single pred.  Split the block.
296   BasicBlock::iterator SplitPoint;
297   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
298     // If the successor only has a single pred, split the top of the successor
299     // block.
300     assert(SP == BB && "CFG broken");
301     SP = NULL;
302     return SplitBlock(Succ, Succ->begin(), P);
303   } else {
304     // Otherwise, if BB has a single successor, split it at the bottom of the
305     // block.
306     assert(BB->getTerminator()->getNumSuccessors() == 1 &&
307            "Should have a single succ!"); 
308     return SplitBlock(BB, BB->getTerminator(), P);
309   }
310 }
311
312 /// SplitBlock - Split the specified block at the specified instruction - every
313 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
314 /// to a new block.  The two blocks are joined by an unconditional branch and
315 /// the loop info is updated.
316 ///
317 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
318   BasicBlock::iterator SplitIt = SplitPt;
319   while (isa<PHINode>(SplitIt))
320     ++SplitIt;
321   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
322
323   // The new block lives in whichever loop the old one did.
324   if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
325     if (Loop *L = LI->getLoopFor(Old))
326       L->addBasicBlockToLoop(New, LI->getBase());
327
328   if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>())
329     {
330       // Old dominates New. New node domiantes all other nodes dominated by Old.
331       DomTreeNode *OldNode = DT->getNode(Old);
332       std::vector<DomTreeNode *> Children;
333       for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
334            I != E; ++I) 
335         Children.push_back(*I);
336
337       DomTreeNode *NewNode =   DT->addNewBlock(New,Old);
338
339       for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
340              E = Children.end(); I != E; ++I) 
341         DT->changeImmediateDominator(*I, NewNode);
342     }
343
344   if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
345     DF->splitBlock(Old);
346     
347   return New;
348 }
349
350
351 /// SplitBlockPredecessors - This method transforms BB by introducing a new
352 /// basic block into the function, and moving some of the predecessors of BB to
353 /// be predecessors of the new block.  The new predecessors are indicated by the
354 /// Preds array, which has NumPreds elements in it.  The new block is given a
355 /// suffix of 'Suffix'.
356 ///
357 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
358 /// DominanceFrontier, but no other analyses.
359 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 
360                                          BasicBlock *const *Preds,
361                                          unsigned NumPreds, const char *Suffix,
362                                          Pass *P) {
363   // Create new basic block, insert right before the original block.
364   BasicBlock *NewBB =
365     BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
366   
367   // The new block unconditionally branches to the old block.
368   BranchInst *BI = BranchInst::Create(BB, NewBB);
369   
370   // Move the edges from Preds to point to NewBB instead of BB.
371   for (unsigned i = 0; i != NumPreds; ++i)
372     Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
373   
374   // Update dominator tree and dominator frontier if available.
375   DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
376   if (DT)
377     DT->splitBlock(NewBB);
378   if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
379     DF->splitBlock(NewBB);
380   AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
381   
382   
383   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
384   // node becomes an incoming value for BB's phi node.  However, if the Preds
385   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
386   // account for the newly created predecessor.
387   if (NumPreds == 0) {
388     // Insert dummy values as the incoming value.
389     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
390       cast<PHINode>(I)->addIncoming(BB->getContext()->getUndef(I->getType()), 
391                                     NewBB);
392     return NewBB;
393   }
394   
395   // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
396   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
397     PHINode *PN = cast<PHINode>(I++);
398     
399     // Check to see if all of the values coming in are the same.  If so, we
400     // don't need to create a new PHI node.
401     Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
402     for (unsigned i = 1; i != NumPreds; ++i)
403       if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
404         InVal = 0;
405         break;
406       }
407     
408     if (InVal) {
409       // If all incoming values for the new PHI would be the same, just don't
410       // make a new PHI.  Instead, just remove the incoming values from the old
411       // PHI.
412       for (unsigned i = 0; i != NumPreds; ++i)
413         PN->removeIncomingValue(Preds[i], false);
414     } else {
415       // If the values coming into the block are not the same, we need a PHI.
416       // Create the new PHI node, insert it into NewBB at the end of the block
417       PHINode *NewPHI =
418         PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
419       if (AA) AA->copyValue(PN, NewPHI);
420       
421       // Move all of the PHI values for 'Preds' to the new PHI.
422       for (unsigned i = 0; i != NumPreds; ++i) {
423         Value *V = PN->removeIncomingValue(Preds[i], false);
424         NewPHI->addIncoming(V, Preds[i]);
425       }
426       InVal = NewPHI;
427     }
428     
429     // Add an incoming value to the PHI node in the loop for the preheader
430     // edge.
431     PN->addIncoming(InVal, NewBB);
432     
433     // Check to see if we can eliminate this phi node.
434     if (Value *V = PN->hasConstantValue(DT != 0)) {
435       Instruction *I = dyn_cast<Instruction>(V);
436       if (!I || DT == 0 || DT->dominates(I, PN)) {
437         PN->replaceAllUsesWith(V);
438         if (AA) AA->deleteValue(PN);
439         PN->eraseFromParent();
440       }
441     }
442   }
443   
444   return NewBB;
445 }
446
447 /// FindFunctionBackedges - Analyze the specified function to find all of the
448 /// loop backedges in the function and return them.  This is a relatively cheap
449 /// (compared to computing dominators and loop info) analysis.
450 ///
451 /// The output is added to Result, as pairs of <from,to> edge info.
452 void llvm::FindFunctionBackedges(const Function &F,
453      SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
454   const BasicBlock *BB = &F.getEntryBlock();
455   if (succ_begin(BB) == succ_end(BB))
456     return;
457   
458   SmallPtrSet<const BasicBlock*, 8> Visited;
459   SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
460   SmallPtrSet<const BasicBlock*, 8> InStack;
461   
462   Visited.insert(BB);
463   VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
464   InStack.insert(BB);
465   do {
466     std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
467     const BasicBlock *ParentBB = Top.first;
468     succ_const_iterator &I = Top.second;
469     
470     bool FoundNew = false;
471     while (I != succ_end(ParentBB)) {
472       BB = *I++;
473       if (Visited.insert(BB)) {
474         FoundNew = true;
475         break;
476       }
477       // Successor is in VisitStack, it's a back edge.
478       if (InStack.count(BB))
479         Result.push_back(std::make_pair(ParentBB, BB));
480     }
481     
482     if (FoundNew) {
483       // Go down one level if there is a unvisited successor.
484       InStack.insert(BB);
485       VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
486     } else {
487       // Go up one level.
488       InStack.erase(VisitStack.pop_back_val().first);
489     }
490   } while (!VisitStack.empty());
491   
492   
493 }
494
495
496
497 /// AreEquivalentAddressValues - Test if A and B will obviously have the same
498 /// value. This includes recognizing that %t0 and %t1 will have the same
499 /// value in code like this:
500 ///   %t0 = getelementptr \@a, 0, 3
501 ///   store i32 0, i32* %t0
502 ///   %t1 = getelementptr \@a, 0, 3
503 ///   %t2 = load i32* %t1
504 ///
505 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
506   // Test if the values are trivially equivalent.
507   if (A == B) return true;
508   
509   // Test if the values come form identical arithmetic instructions.
510   if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
511       isa<PHINode>(A) || isa<GetElementPtrInst>(A))
512     if (const Instruction *BI = dyn_cast<Instruction>(B))
513       if (cast<Instruction>(A)->isIdenticalTo(BI))
514         return true;
515   
516   // Otherwise they may not be equivalent.
517   return false;
518 }
519
520 /// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
521 /// instruction before ScanFrom) checking to see if we have the value at the
522 /// memory address *Ptr locally available within a small number of instructions.
523 /// If the value is available, return it.
524 ///
525 /// If not, return the iterator for the last validated instruction that the 
526 /// value would be live through.  If we scanned the entire block and didn't find
527 /// something that invalidates *Ptr or provides it, ScanFrom would be left at
528 /// begin() and this returns null.  ScanFrom could also be left 
529 ///
530 /// MaxInstsToScan specifies the maximum instructions to scan in the block.  If
531 /// it is set to 0, it will scan the whole block. You can also optionally
532 /// specify an alias analysis implementation, which makes this more precise.
533 Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
534                                       BasicBlock::iterator &ScanFrom,
535                                       unsigned MaxInstsToScan,
536                                       AliasAnalysis *AA) {
537   if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
538
539   // If we're using alias analysis to disambiguate get the size of *Ptr.
540   unsigned AccessSize = 0;
541   if (AA) {
542     const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
543     AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
544   }
545   
546   while (ScanFrom != ScanBB->begin()) {
547     // We must ignore debug info directives when counting (otherwise they
548     // would affect codegen).
549     Instruction *Inst = --ScanFrom;
550     if (isa<DbgInfoIntrinsic>(Inst))
551       continue;
552     // We skip pointer-to-pointer bitcasts, which are NOPs.
553     // It is necessary for correctness to skip those that feed into a
554     // llvm.dbg.declare, as these are not present when debugging is off.
555     if (isa<BitCastInst>(Inst) && isa<PointerType>(Inst->getType()))
556       continue;
557
558     // Restore ScanFrom to expected value in case next test succeeds
559     ScanFrom++;
560    
561     // Don't scan huge blocks.
562     if (MaxInstsToScan-- == 0) return 0;
563     
564     --ScanFrom;
565     // If this is a load of Ptr, the loaded value is available.
566     if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
567       if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
568         return LI;
569     
570     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
571       // If this is a store through Ptr, the value is available!
572       if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
573         return SI->getOperand(0);
574       
575       // If Ptr is an alloca and this is a store to a different alloca, ignore
576       // the store.  This is a trivial form of alias analysis that is important
577       // for reg2mem'd code.
578       if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
579           (isa<AllocaInst>(SI->getOperand(1)) ||
580            isa<GlobalVariable>(SI->getOperand(1))))
581         continue;
582       
583       // If we have alias analysis and it says the store won't modify the loaded
584       // value, ignore the store.
585       if (AA &&
586           (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
587         continue;
588       
589       // Otherwise the store that may or may not alias the pointer, bail out.
590       ++ScanFrom;
591       return 0;
592     }
593     
594     // If this is some other instruction that may clobber Ptr, bail out.
595     if (Inst->mayWriteToMemory()) {
596       // If alias analysis claims that it really won't modify the load,
597       // ignore it.
598       if (AA &&
599           (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
600         continue;
601       
602       // May modify the pointer, bail out.
603       ++ScanFrom;
604       return 0;
605     }
606   }
607   
608   // Got to the start of the block, we didn't find it, but are done for this
609   // block.
610   return 0;
611 }
612
613 /// CopyPrecedingStopPoint - If I is immediately preceded by a StopPoint,
614 /// make a copy of the stoppoint before InsertPos (presumably before copying
615 /// or moving I).
616 void llvm::CopyPrecedingStopPoint(Instruction *I, 
617                                   BasicBlock::iterator InsertPos) {
618   if (I != I->getParent()->begin()) {
619     BasicBlock::iterator BBI = I;  --BBI;
620     if (DbgStopPointInst *DSPI = dyn_cast<DbgStopPointInst>(BBI)) {
621       CallInst *newDSPI = DSPI->clone();
622       newDSPI->insertBefore(InsertPos);
623     }
624   }
625 }