Some internal refactoring to make it easier to cache results.
[oota-llvm.git] / lib / Analysis / MemoryDependenceAnalysis.cpp
1 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation  --*- C++ -*-===//
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 file implements an analysis that determines, for a given memory
11 // operation, what preceding memory operations it depends on.  It builds on 
12 // alias analysis information, and tries to provide a lazy, caching interface to
13 // a common kind of alias information query.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "memdep"
18 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Function.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Target/TargetData.h"
29 using namespace llvm;
30
31 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
32 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
33 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
34 char MemoryDependenceAnalysis::ID = 0;
35   
36 // Register this pass...
37 static RegisterPass<MemoryDependenceAnalysis> X("memdep",
38                                      "Memory Dependence Analysis", false, true);
39
40 /// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
41 ///
42 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
43   AU.setPreservesAll();
44   AU.addRequiredTransitive<AliasAnalysis>();
45   AU.addRequiredTransitive<TargetData>();
46 }
47
48 bool MemoryDependenceAnalysis::runOnFunction(Function &) {
49   AA = &getAnalysis<AliasAnalysis>();
50   TD = &getAnalysis<TargetData>();
51   return false;
52 }
53
54
55 /// getCallSiteDependencyFrom - Private helper for finding the local
56 /// dependencies of a call site.
57 MemDepResult MemoryDependenceAnalysis::
58 getCallSiteDependencyFrom(CallSite CS, BasicBlock::iterator ScanIt,
59                           BasicBlock *BB) {
60   // Walk backwards through the block, looking for dependencies
61   while (ScanIt != BB->begin()) {
62     Instruction *Inst = --ScanIt;
63     
64     // If this inst is a memory op, get the pointer it accessed
65     Value *Pointer = 0;
66     uint64_t PointerSize = 0;
67     if (StoreInst *S = dyn_cast<StoreInst>(Inst)) {
68       Pointer = S->getPointerOperand();
69       PointerSize = TD->getTypeStoreSize(S->getOperand(0)->getType());
70     } else if (VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
71       Pointer = V->getOperand(0);
72       PointerSize = TD->getTypeStoreSize(V->getType());
73     } else if (FreeInst *F = dyn_cast<FreeInst>(Inst)) {
74       Pointer = F->getPointerOperand();
75       
76       // FreeInsts erase the entire structure
77       PointerSize = ~0UL;
78     } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
79       CallSite InstCS = CallSite::get(Inst);
80       // If these two calls do not interfere, look past it.
81       if (AA->getModRefInfo(CS, InstCS) == AliasAnalysis::NoModRef)
82         continue;
83       
84       // FIXME: If this is a ref/ref result, we should ignore it!
85       //  X = strlen(P);
86       //  Y = strlen(Q);
87       //  Z = strlen(P);  // Z = X
88       
89       // If they interfere, we generally return clobber.  However, if they are
90       // calls to the same read-only functions we return Def.
91       if (!AA->onlyReadsMemory(CS) || CS.getCalledFunction() == 0 ||
92           CS.getCalledFunction() != InstCS.getCalledFunction())
93         return MemDepResult::getClobber(Inst);
94       return MemDepResult::getDef(Inst);
95     } else {
96       // Non-memory instruction.
97       continue;
98     }
99     
100     if (AA->getModRefInfo(CS, Pointer, PointerSize) != AliasAnalysis::NoModRef)
101       return MemDepResult::getClobber(Inst);
102   }
103   
104   // No dependence found.  If this is the entry block of the function, it is a
105   // clobber, otherwise it is non-local.
106   if (BB != &BB->getParent()->getEntryBlock())
107     return MemDepResult::getNonLocal();
108   return MemDepResult::getClobber(ScanIt);
109 }
110
111 /// getPointerDependencyFrom - Return the instruction on which a memory
112 /// location depends.  If isLoad is true, this routine ignore may-aliases with
113 /// read-only operations.
114 MemDepResult MemoryDependenceAnalysis::
115 getPointerDependencyFrom(Value *MemPtr, uint64_t MemSize, bool isLoad,
116                          BasicBlock::iterator ScanIt, BasicBlock *BB) {
117
118   // Walk backwards through the basic block, looking for dependencies
119   while (ScanIt != BB->begin()) {
120     Instruction *Inst = --ScanIt;
121
122     // Values depend on loads if the pointers are must aliased.  This means that
123     // a load depends on another must aliased load from the same value.
124     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
125       Value *Pointer = LI->getPointerOperand();
126       uint64_t PointerSize = TD->getTypeStoreSize(LI->getType());
127       
128       // If we found a pointer, check if it could be the same as our pointer.
129       AliasAnalysis::AliasResult R =
130         AA->alias(Pointer, PointerSize, MemPtr, MemSize);
131       if (R == AliasAnalysis::NoAlias)
132         continue;
133       
134       // May-alias loads don't depend on each other without a dependence.
135       if (isLoad && R == AliasAnalysis::MayAlias)
136         continue;
137       return MemDepResult::getDef(Inst);
138     }
139     
140     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
141       Value *Pointer = SI->getPointerOperand();
142       uint64_t PointerSize = TD->getTypeStoreSize(SI->getOperand(0)->getType());
143
144       // If we found a pointer, check if it could be the same as our pointer.
145       AliasAnalysis::AliasResult R =
146         AA->alias(Pointer, PointerSize, MemPtr, MemSize);
147       
148       if (R == AliasAnalysis::NoAlias)
149         continue;
150       if (R == AliasAnalysis::MayAlias)
151         return MemDepResult::getClobber(Inst);
152       return MemDepResult::getDef(Inst);
153     }
154
155     // If this is an allocation, and if we know that the accessed pointer is to
156     // the allocation, return Def.  This means that there is no dependence and
157     // the access can be optimized based on that.  For example, a load could
158     // turn into undef.
159     if (AllocationInst *AI = dyn_cast<AllocationInst>(Inst)) {
160       Value *AccessPtr = MemPtr->getUnderlyingObject();
161       
162       if (AccessPtr == AI ||
163           AA->alias(AI, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
164         return MemDepResult::getDef(AI);
165       continue;
166     }
167     
168     // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
169     // FIXME: If this is a load, we should ignore readonly calls!
170     if (AA->getModRefInfo(Inst, MemPtr, MemSize) == AliasAnalysis::NoModRef)
171       continue;
172     
173     // Otherwise, there is a dependence.
174     return MemDepResult::getClobber(Inst);
175   }
176   
177   // No dependence found.  If this is the entry block of the function, it is a
178   // clobber, otherwise it is non-local.
179   if (BB != &BB->getParent()->getEntryBlock())
180     return MemDepResult::getNonLocal();
181   return MemDepResult::getClobber(ScanIt);
182 }
183
184 /// getDependency - Return the instruction on which a memory operation
185 /// depends.
186 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
187   Instruction *ScanPos = QueryInst;
188   
189   // Check for a cached result
190   MemDepResult &LocalCache = LocalDeps[QueryInst];
191   
192   // If the cached entry is non-dirty, just return it.  Note that this depends
193   // on MemDepResult's default constructing to 'dirty'.
194   if (!LocalCache.isDirty())
195     return LocalCache;
196     
197   // Otherwise, if we have a dirty entry, we know we can start the scan at that
198   // instruction, which may save us some work.
199   if (Instruction *Inst = LocalCache.getInst()) {
200     ScanPos = Inst;
201    
202     SmallPtrSet<Instruction*, 4> &InstMap = ReverseLocalDeps[Inst];
203     InstMap.erase(QueryInst);
204     if (InstMap.empty())
205       ReverseLocalDeps.erase(Inst);
206   }
207   
208   BasicBlock *QueryParent = QueryInst->getParent();
209   
210   Value *MemPtr = 0;
211   uint64_t MemSize = 0;
212   
213   // Do the scan.
214   if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
215     // No dependence found.  If this is the entry block of the function, it is a
216     // clobber, otherwise it is non-local.
217     if (QueryParent != &QueryParent->getParent()->getEntryBlock())
218       LocalCache = MemDepResult::getNonLocal();
219     else
220       LocalCache = MemDepResult::getClobber(QueryInst);
221   } else if (StoreInst *SI = dyn_cast<StoreInst>(QueryInst)) {
222     // If this is a volatile store, don't mess around with it.  Just return the
223     // previous instruction as a clobber.
224     if (SI->isVolatile())
225       LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
226     else {
227       MemPtr = SI->getPointerOperand();
228       MemSize = TD->getTypeStoreSize(SI->getOperand(0)->getType());
229     }
230   } else if (LoadInst *LI = dyn_cast<LoadInst>(QueryInst)) {
231     // If this is a volatile load, don't mess around with it.  Just return the
232     // previous instruction as a clobber.
233     if (LI->isVolatile())
234       LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
235     else {
236       MemPtr = LI->getPointerOperand();
237       MemSize = TD->getTypeStoreSize(LI->getType());
238     }
239   } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
240     LocalCache = getCallSiteDependencyFrom(CallSite::get(QueryInst), ScanPos,
241                                            QueryParent);
242   } else if (FreeInst *FI = dyn_cast<FreeInst>(QueryInst)) {
243     MemPtr = FI->getPointerOperand();
244     // FreeInsts erase the entire structure, not just a field.
245     MemSize = ~0UL;
246   } else {
247     // Non-memory instruction.
248     LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
249   }
250   
251   // If we need to do a pointer scan, make it happen.
252   if (MemPtr)
253     LocalCache = getPointerDependencyFrom(MemPtr, MemSize, 
254                                           isa<LoadInst>(QueryInst),
255                                           ScanPos, QueryParent);
256   
257   // Remember the result!
258   if (Instruction *I = LocalCache.getInst())
259     ReverseLocalDeps[I].insert(QueryInst);
260   
261   return LocalCache;
262 }
263
264 /// getNonLocalDependency - Perform a full dependency query for the
265 /// specified instruction, returning the set of blocks that the value is
266 /// potentially live across.  The returned set of results will include a
267 /// "NonLocal" result for all blocks where the value is live across.
268 ///
269 /// This method assumes the instruction returns a "nonlocal" dependency
270 /// within its own block.
271 ///
272 const MemoryDependenceAnalysis::NonLocalDepInfo &
273 MemoryDependenceAnalysis::getNonLocalDependency(Instruction *QueryInst) {
274   // FIXME: Make this only be for callsites in the future.
275   assert(isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst) ||
276          isa<LoadInst>(QueryInst) || isa<StoreInst>(QueryInst));
277   assert(getDependency(QueryInst).isNonLocal() &&
278      "getNonLocalDependency should only be used on insts with non-local deps!");
279   PerInstNLInfo &CacheP = NonLocalDeps[QueryInst];
280   NonLocalDepInfo &Cache = CacheP.first;
281
282   /// DirtyBlocks - This is the set of blocks that need to be recomputed.  In
283   /// the cached case, this can happen due to instructions being deleted etc. In
284   /// the uncached case, this starts out as the set of predecessors we care
285   /// about.
286   SmallVector<BasicBlock*, 32> DirtyBlocks;
287   
288   if (!Cache.empty()) {
289     // Okay, we have a cache entry.  If we know it is not dirty, just return it
290     // with no computation.
291     if (!CacheP.second) {
292       NumCacheNonLocal++;
293       return Cache;
294     }
295     
296     // If we already have a partially computed set of results, scan them to
297     // determine what is dirty, seeding our initial DirtyBlocks worklist.
298     for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
299        I != E; ++I)
300       if (I->second.isDirty())
301         DirtyBlocks.push_back(I->first);
302     
303     // Sort the cache so that we can do fast binary search lookups below.
304     std::sort(Cache.begin(), Cache.end());
305     
306     ++NumCacheDirtyNonLocal;
307     //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
308     //     << Cache.size() << " cached: " << *QueryInst;
309   } else {
310     // Seed DirtyBlocks with each of the preds of QueryInst's block.
311     BasicBlock *QueryBB = QueryInst->getParent();
312     DirtyBlocks.append(pred_begin(QueryBB), pred_end(QueryBB));
313     NumUncacheNonLocal++;
314   }
315   
316   // Visited checked first, vector in sorted order.
317   SmallPtrSet<BasicBlock*, 64> Visited;
318   
319   unsigned NumSortedEntries = Cache.size();
320   
321   // Iterate while we still have blocks to update.
322   while (!DirtyBlocks.empty()) {
323     BasicBlock *DirtyBB = DirtyBlocks.back();
324     DirtyBlocks.pop_back();
325     
326     // Already processed this block?
327     if (!Visited.insert(DirtyBB))
328       continue;
329     
330     // Do a binary search to see if we already have an entry for this block in
331     // the cache set.  If so, find it.
332     NonLocalDepInfo::iterator Entry = 
333       std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
334                        std::make_pair(DirtyBB, MemDepResult()));
335     if (Entry != Cache.begin() && (&*Entry)[-1].first == DirtyBB)
336       --Entry;
337     
338     MemDepResult *ExistingResult = 0;
339     if (Entry != Cache.begin()+NumSortedEntries && 
340         Entry->first == DirtyBB) {
341       // If we already have an entry, and if it isn't already dirty, the block
342       // is done.
343       if (!Entry->second.isDirty())
344         continue;
345       
346       // Otherwise, remember this slot so we can update the value.
347       ExistingResult = &Entry->second;
348     }
349     
350     // If the dirty entry has a pointer, start scanning from it so we don't have
351     // to rescan the entire block.
352     BasicBlock::iterator ScanPos = DirtyBB->end();
353     if (ExistingResult) {
354       if (Instruction *Inst = ExistingResult->getInst()) {
355         ScanPos = Inst;
356       
357         // We're removing QueryInst's use of Inst.
358         SmallPtrSet<Instruction*, 4> &InstMap = ReverseNonLocalDeps[Inst];
359         InstMap.erase(QueryInst);
360         if (InstMap.empty()) ReverseNonLocalDeps.erase(Inst);
361       }
362     }
363     
364     // Find out if this block has a local dependency for QueryInst.
365     MemDepResult Dep;
366     
367     Value *MemPtr = 0;
368     uint64_t MemSize = 0;
369
370     if (ScanPos == DirtyBB->begin()) {
371       // No dependence found.  If this is the entry block of the function, it is a
372       // clobber, otherwise it is non-local.
373       if (DirtyBB != &DirtyBB->getParent()->getEntryBlock())
374         Dep = MemDepResult::getNonLocal();
375       else
376         Dep = MemDepResult::getClobber(ScanPos);
377     } else if (StoreInst *SI = dyn_cast<StoreInst>(QueryInst)) {
378       // If this is a volatile store, don't mess around with it.  Just return the
379       // previous instruction as a clobber.
380       if (SI->isVolatile())
381         Dep = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
382       else {
383         MemPtr = SI->getPointerOperand();
384         MemSize = TD->getTypeStoreSize(SI->getOperand(0)->getType());
385       }
386     } else if (LoadInst *LI = dyn_cast<LoadInst>(QueryInst)) {
387       // If this is a volatile load, don't mess around with it.  Just return the
388       // previous instruction as a clobber.
389       if (LI->isVolatile())
390         Dep = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
391       else {
392         MemPtr = LI->getPointerOperand();
393         MemSize = TD->getTypeStoreSize(LI->getType());
394       }
395     } else {
396       assert(isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst));
397       Dep = getCallSiteDependencyFrom(CallSite::get(QueryInst), ScanPos,
398                                       DirtyBB);
399     }
400     
401     if (MemPtr)
402       Dep = getPointerDependencyFrom(MemPtr, MemSize, isa<LoadInst>(QueryInst),
403                                      ScanPos, DirtyBB);
404     
405     // If we had a dirty entry for the block, update it.  Otherwise, just add
406     // a new entry.
407     if (ExistingResult)
408       *ExistingResult = Dep;
409     else
410       Cache.push_back(std::make_pair(DirtyBB, Dep));
411     
412     // If the block has a dependency (i.e. it isn't completely transparent to
413     // the value), remember the association!
414     if (!Dep.isNonLocal()) {
415       // Keep the ReverseNonLocalDeps map up to date so we can efficiently
416       // update this when we remove instructions.
417       if (Instruction *Inst = Dep.getInst())
418         ReverseNonLocalDeps[Inst].insert(QueryInst);
419     } else {
420     
421       // If the block *is* completely transparent to the load, we need to check
422       // the predecessors of this block.  Add them to our worklist.
423       DirtyBlocks.append(pred_begin(DirtyBB), pred_end(DirtyBB));
424     }
425   }
426   
427   return Cache;
428 }
429
430 /// getNonLocalPointerDependency - Perform a full dependency query for an
431 /// access to the specified (non-volatile) memory location, returning the
432 /// set of instructions that either define or clobber the value.
433 ///
434 /// This method assumes the pointer has a "NonLocal" dependency within its
435 /// own block.
436 ///
437 void MemoryDependenceAnalysis::
438 getNonLocalPointerDependency(Value *Pointer, bool isLoad, BasicBlock *FromBB,
439                              SmallVectorImpl<NonLocalDepEntry> &Result) {
440   Result.clear();
441   
442   // We know that the pointer value is live into FromBB find the def/clobbers
443   // from presecessors.
444
445   const Type *EltTy = cast<PointerType>(Pointer->getType())->getElementType();
446   uint64_t PointeeSize = TD->getTypeStoreSize(EltTy);
447   
448   // While we have blocks to analyze, get their values.
449   SmallPtrSet<BasicBlock*, 64> Visited;
450   
451   for (pred_iterator PI = pred_begin(FromBB), E = pred_end(FromBB); PI != E;
452        ++PI) {
453     // TODO: PHI TRANSLATE.
454     getNonLocalPointerDepInternal(Pointer, PointeeSize, isLoad, *PI,
455                                   Result, Visited);
456   }
457 }
458
459 void MemoryDependenceAnalysis::
460 getNonLocalPointerDepInternal(Value *Pointer, uint64_t PointeeSize,
461                               bool isLoad, BasicBlock *StartBB,
462                               SmallVectorImpl<NonLocalDepEntry> &Result,
463                               SmallPtrSet<BasicBlock*, 64> &Visited) {
464   SmallVector<BasicBlock*, 32> Worklist;
465   Worklist.push_back(StartBB);
466   
467   while (!Worklist.empty()) {
468     BasicBlock *BB = Worklist.pop_back_val();
469     
470     // Analyze the dependency of *Pointer in FromBB.  See if we already have
471     // been here.
472     if (!Visited.insert(BB))
473       continue;
474     
475     // FIXME: CACHE!
476     
477     MemDepResult Dep =
478       getPointerDependencyFrom(Pointer, PointeeSize, isLoad, BB->end(), BB);
479     
480     // If we got a Def or Clobber, add this to the list of results.
481     if (!Dep.isNonLocal()) {
482       Result.push_back(NonLocalDepEntry(BB, Dep));
483       continue;
484     }
485     
486     // Otherwise, we have to process all the predecessors of this block to scan
487     // them as well.
488     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
489       // TODO: PHI TRANSLATE.
490       Worklist.push_back(*PI);
491     }
492   }
493 }
494
495
496 /// removeInstruction - Remove an instruction from the dependence analysis,
497 /// updating the dependence of instructions that previously depended on it.
498 /// This method attempts to keep the cache coherent using the reverse map.
499 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
500   // Walk through the Non-local dependencies, removing this one as the value
501   // for any cached queries.
502   NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
503   if (NLDI != NonLocalDeps.end()) {
504     NonLocalDepInfo &BlockMap = NLDI->second.first;
505     for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
506          DI != DE; ++DI)
507       if (Instruction *Inst = DI->second.getInst())
508         ReverseNonLocalDeps[Inst].erase(RemInst);
509     NonLocalDeps.erase(NLDI);
510   }
511
512   // If we have a cached local dependence query for this instruction, remove it.
513   //
514   LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
515   if (LocalDepEntry != LocalDeps.end()) {
516     // Remove us from DepInst's reverse set now that the local dep info is gone.
517     if (Instruction *Inst = LocalDepEntry->second.getInst()) {
518       SmallPtrSet<Instruction*, 4> &RLD = ReverseLocalDeps[Inst];
519       RLD.erase(RemInst);
520       if (RLD.empty())
521         ReverseLocalDeps.erase(Inst);
522     }
523
524     // Remove this local dependency info.
525     LocalDeps.erase(LocalDepEntry);
526   }    
527   
528   // Loop over all of the things that depend on the instruction we're removing.
529   // 
530   SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
531   
532   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
533   if (ReverseDepIt != ReverseLocalDeps.end()) {
534     SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
535     // RemInst can't be the terminator if it has stuff depending on it.
536     assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
537            "Nothing can locally depend on a terminator");
538     
539     // Anything that was locally dependent on RemInst is now going to be
540     // dependent on the instruction after RemInst.  It will have the dirty flag
541     // set so it will rescan.  This saves having to scan the entire block to get
542     // to this point.
543     Instruction *NewDepInst = next(BasicBlock::iterator(RemInst));
544                         
545     for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
546          E = ReverseDeps.end(); I != E; ++I) {
547       Instruction *InstDependingOnRemInst = *I;
548       assert(InstDependingOnRemInst != RemInst &&
549              "Already removed our local dep info");
550                         
551       LocalDeps[InstDependingOnRemInst] = MemDepResult::getDirty(NewDepInst);
552       
553       // Make sure to remember that new things depend on NewDepInst.
554       ReverseDepsToAdd.push_back(std::make_pair(NewDepInst, 
555                                                 InstDependingOnRemInst));
556     }
557     
558     ReverseLocalDeps.erase(ReverseDepIt);
559
560     // Add new reverse deps after scanning the set, to avoid invalidating the
561     // 'ReverseDeps' reference.
562     while (!ReverseDepsToAdd.empty()) {
563       ReverseLocalDeps[ReverseDepsToAdd.back().first]
564         .insert(ReverseDepsToAdd.back().second);
565       ReverseDepsToAdd.pop_back();
566     }
567   }
568   
569   ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
570   if (ReverseDepIt != ReverseNonLocalDeps.end()) {
571     SmallPtrSet<Instruction*, 4>& set = ReverseDepIt->second;
572     for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
573          I != E; ++I) {
574       assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
575       
576       PerInstNLInfo &INLD = NonLocalDeps[*I];
577       // The information is now dirty!
578       INLD.second = true;
579       
580       for (NonLocalDepInfo::iterator DI = INLD.first.begin(), 
581            DE = INLD.first.end(); DI != DE; ++DI) {
582         if (DI->second.getInst() != RemInst) continue;
583         
584         // Convert to a dirty entry for the subsequent instruction.
585         Instruction *NextI = 0;
586         if (!RemInst->isTerminator()) {
587           NextI = next(BasicBlock::iterator(RemInst));
588           ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
589         }
590         DI->second = MemDepResult::getDirty(NextI);
591       }
592     }
593
594     ReverseNonLocalDeps.erase(ReverseDepIt);
595
596     // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
597     while (!ReverseDepsToAdd.empty()) {
598       ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
599         .insert(ReverseDepsToAdd.back().second);
600       ReverseDepsToAdd.pop_back();
601     }
602   }
603   
604   assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
605   AA->deleteValue(RemInst);
606   DEBUG(verifyRemoved(RemInst));
607 }
608
609 /// verifyRemoved - Verify that the specified instruction does not occur
610 /// in our internal data structures.
611 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
612   for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
613        E = LocalDeps.end(); I != E; ++I) {
614     assert(I->first != D && "Inst occurs in data structures");
615     assert(I->second.getInst() != D &&
616            "Inst occurs in data structures");
617   }
618   
619   for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
620        E = NonLocalDeps.end(); I != E; ++I) {
621     assert(I->first != D && "Inst occurs in data structures");
622     const PerInstNLInfo &INLD = I->second;
623     for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
624          EE = INLD.first.end(); II  != EE; ++II)
625       assert(II->second.getInst() != D && "Inst occurs in data structures");
626   }
627   
628   for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
629        E = ReverseLocalDeps.end(); I != E; ++I) {
630     assert(I->first != D && "Inst occurs in data structures");
631     for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
632          EE = I->second.end(); II != EE; ++II)
633       assert(*II != D && "Inst occurs in data structures");
634   }
635   
636   for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
637        E = ReverseNonLocalDeps.end();
638        I != E; ++I) {
639     assert(I->first != D && "Inst occurs in data structures");
640     for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
641          EE = I->second.end(); II != EE; ++II)
642       assert(*II != D && "Inst occurs in data structures");
643   }
644 }