cb3260990ae7c72a757ca354b5ae5a542054278c
[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/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Function.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/InstructionSimplify.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/PHITransAddr.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/PredIteratorCache.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Target/TargetData.h"
34 using namespace llvm;
35
36 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
37 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
38 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
39
40 STATISTIC(NumCacheNonLocalPtr,
41           "Number of fully cached non-local ptr responses");
42 STATISTIC(NumCacheDirtyNonLocalPtr,
43           "Number of cached, but dirty, non-local ptr responses");
44 STATISTIC(NumUncacheNonLocalPtr,
45           "Number of uncached non-local ptr responses");
46 STATISTIC(NumCacheCompleteNonLocalPtr,
47           "Number of block queries that were completely cached");
48
49 char MemoryDependenceAnalysis::ID = 0;
50   
51 // Register this pass...
52 INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep",
53                 "Memory Dependence Analysis", false, true)
54 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
55 INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep",
56                       "Memory Dependence Analysis", false, true)
57
58 MemoryDependenceAnalysis::MemoryDependenceAnalysis()
59 : FunctionPass(ID), PredCache(0) {
60   initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry());
61 }
62 MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
63 }
64
65 /// Clean up memory in between runs
66 void MemoryDependenceAnalysis::releaseMemory() {
67   LocalDeps.clear();
68   NonLocalDeps.clear();
69   NonLocalPointerDeps.clear();
70   ReverseLocalDeps.clear();
71   ReverseNonLocalDeps.clear();
72   ReverseNonLocalPtrDeps.clear();
73   PredCache->clear();
74 }
75
76
77
78 /// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
79 ///
80 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
81   AU.setPreservesAll();
82   AU.addRequiredTransitive<AliasAnalysis>();
83 }
84
85 bool MemoryDependenceAnalysis::runOnFunction(Function &) {
86   AA = &getAnalysis<AliasAnalysis>();
87   TD = getAnalysisIfAvailable<TargetData>();
88   if (PredCache == 0)
89     PredCache.reset(new PredIteratorCache());
90   return false;
91 }
92
93 /// RemoveFromReverseMap - This is a helper function that removes Val from
94 /// 'Inst's set in ReverseMap.  If the set becomes empty, remove Inst's entry.
95 template <typename KeyTy>
96 static void RemoveFromReverseMap(DenseMap<Instruction*, 
97                                  SmallPtrSet<KeyTy, 4> > &ReverseMap,
98                                  Instruction *Inst, KeyTy Val) {
99   typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator
100   InstIt = ReverseMap.find(Inst);
101   assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
102   bool Found = InstIt->second.erase(Val);
103   assert(Found && "Invalid reverse map!"); (void)Found;
104   if (InstIt->second.empty())
105     ReverseMap.erase(InstIt);
106 }
107
108 /// GetLocation - If the given instruction references a specific memory
109 /// location, fill in Loc with the details, otherwise set Loc.Ptr to null.
110 /// Return a ModRefInfo value describing the general behavior of the
111 /// instruction.
112 static
113 AliasAnalysis::ModRefResult GetLocation(const Instruction *Inst,
114                                         AliasAnalysis::Location &Loc,
115                                         AliasAnalysis *AA) {
116   if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
117     if (LI->isVolatile()) {
118       Loc = AliasAnalysis::Location();
119       return AliasAnalysis::ModRef;
120     }
121     Loc = AA->getLocation(LI);
122     return AliasAnalysis::Ref;
123   }
124
125   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
126     if (SI->isVolatile()) {
127       Loc = AliasAnalysis::Location();
128       return AliasAnalysis::ModRef;
129     }
130     Loc = AA->getLocation(SI);
131     return AliasAnalysis::Mod;
132   }
133
134   if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
135     Loc = AA->getLocation(V);
136     return AliasAnalysis::ModRef;
137   }
138
139   if (const CallInst *CI = isFreeCall(Inst)) {
140     // calls to free() deallocate the entire structure
141     Loc = AliasAnalysis::Location(CI->getArgOperand(0));
142     return AliasAnalysis::Mod;
143   }
144
145   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
146     switch (II->getIntrinsicID()) {
147     case Intrinsic::lifetime_start:
148     case Intrinsic::lifetime_end:
149     case Intrinsic::invariant_start:
150       Loc = AliasAnalysis::Location(II->getArgOperand(1),
151                                     cast<ConstantInt>(II->getArgOperand(0))
152                                       ->getZExtValue(),
153                                     II->getMetadata(LLVMContext::MD_tbaa));
154       // These intrinsics don't really modify the memory, but returning Mod
155       // will allow them to be handled conservatively.
156       return AliasAnalysis::Mod;
157     case Intrinsic::invariant_end:
158       Loc = AliasAnalysis::Location(II->getArgOperand(2),
159                                     cast<ConstantInt>(II->getArgOperand(1))
160                                       ->getZExtValue(),
161                                     II->getMetadata(LLVMContext::MD_tbaa));
162       // These intrinsics don't really modify the memory, but returning Mod
163       // will allow them to be handled conservatively.
164       return AliasAnalysis::Mod;
165     default:
166       break;
167     }
168
169   // Otherwise, just do the coarse-grained thing that always works.
170   if (Inst->mayWriteToMemory())
171     return AliasAnalysis::ModRef;
172   if (Inst->mayReadFromMemory())
173     return AliasAnalysis::Ref;
174   return AliasAnalysis::NoModRef;
175 }
176
177 /// getCallSiteDependencyFrom - Private helper for finding the local
178 /// dependencies of a call site.
179 MemDepResult MemoryDependenceAnalysis::
180 getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
181                           BasicBlock::iterator ScanIt, BasicBlock *BB) {
182   // Walk backwards through the block, looking for dependencies
183   while (ScanIt != BB->begin()) {
184     Instruction *Inst = --ScanIt;
185     
186     // If this inst is a memory op, get the pointer it accessed
187     AliasAnalysis::Location Loc;
188     AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA);
189     if (Loc.Ptr) {
190       // A simple instruction.
191       if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef)
192         return MemDepResult::getClobber(Inst);
193       continue;
194     }
195
196     if (CallSite InstCS = cast<Value>(Inst)) {
197       // Debug intrinsics don't cause dependences.
198       if (isa<DbgInfoIntrinsic>(Inst)) continue;
199       // If these two calls do not interfere, look past it.
200       switch (AA->getModRefInfo(CS, InstCS)) {
201       case AliasAnalysis::NoModRef:
202         // If the two calls are the same, return InstCS as a Def, so that
203         // CS can be found redundant and eliminated.
204         if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) &&
205             CS.getInstruction()->isIdenticalToWhenDefined(Inst))
206           return MemDepResult::getDef(Inst);
207
208         // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
209         // keep scanning.
210         break;
211       default:
212         return MemDepResult::getClobber(Inst);
213       }
214     }
215   }
216   
217   // No dependence found.  If this is the entry block of the function, it is a
218   // clobber, otherwise it is non-local.
219   if (BB != &BB->getParent()->getEntryBlock())
220     return MemDepResult::getNonLocal();
221   return MemDepResult::getClobber(ScanIt);
222 }
223
224 /// getPointerDependencyFrom - Return the instruction on which a memory
225 /// location depends.  If isLoad is true, this routine ignores may-aliases with
226 /// read-only operations.  If isLoad is false, this routine ignores may-aliases
227 /// with reads from read-only locations.
228 MemDepResult MemoryDependenceAnalysis::
229 getPointerDependencyFrom(const AliasAnalysis::Location &MemLoc, bool isLoad, 
230                          BasicBlock::iterator ScanIt, BasicBlock *BB) {
231
232   // Walk backwards through the basic block, looking for dependencies.
233   while (ScanIt != BB->begin()) {
234     Instruction *Inst = --ScanIt;
235
236     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
237       // Debug intrinsics don't (and can't) cause dependences.
238       if (isa<DbgInfoIntrinsic>(II)) continue;
239       
240       // If we reach a lifetime begin or end marker, then the query ends here
241       // because the value is undefined.
242       if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
243         // FIXME: This only considers queries directly on the invariant-tagged
244         // pointer, not on query pointers that are indexed off of them.  It'd
245         // be nice to handle that at some point.
246         AliasAnalysis::AliasResult R =
247           AA->alias(AliasAnalysis::Location(II->getArgOperand(1)), MemLoc);
248         if (R == AliasAnalysis::MustAlias)
249           return MemDepResult::getDef(II);
250         continue;
251       }
252     }
253
254     // Values depend on loads if the pointers are must aliased.  This means that
255     // a load depends on another must aliased load from the same value.
256     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
257       AliasAnalysis::Location LoadLoc = AA->getLocation(LI);
258       
259       // If we found a pointer, check if it could be the same as our pointer.
260       AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc);
261       if (R == AliasAnalysis::NoAlias)
262         continue;
263       
264       if (isLoad) {
265         // Must aliased loads are defs of each other.
266         if (R == AliasAnalysis::MustAlias)
267           return MemDepResult::getDef(Inst);
268
269         // If we have a partial alias, then return this as a clobber for the
270         // client to handle.
271         if (R == AliasAnalysis::PartialAlias)
272           return MemDepResult::getClobber(Inst);
273         
274         // Random may-alias loads don't depend on each other without a
275         // dependence.
276         continue;
277       }
278
279       // Stores don't alias loads from read-only memory.
280       if (AA->pointsToConstantMemory(LoadLoc))
281         continue;
282
283       // Stores depend on may/must aliased loads.
284       return MemDepResult::getDef(Inst);
285     }
286     
287     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
288       // If alias analysis can tell that this store is guaranteed to not modify
289       // the query pointer, ignore it.  Use getModRefInfo to handle cases where
290       // the query pointer points to constant memory etc.
291       if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
292         continue;
293
294       // Ok, this store might clobber the query pointer.  Check to see if it is
295       // a must alias: in this case, we want to return this as a def.
296       AliasAnalysis::Location StoreLoc = AA->getLocation(SI);
297       
298       // If we found a pointer, check if it could be the same as our pointer.
299       AliasAnalysis::AliasResult R = AA->alias(StoreLoc, MemLoc);
300       
301       if (R == AliasAnalysis::NoAlias)
302         continue;
303       if (R == AliasAnalysis::MustAlias)
304         return MemDepResult::getDef(Inst);
305       return MemDepResult::getClobber(Inst);
306     }
307
308     // If this is an allocation, and if we know that the accessed pointer is to
309     // the allocation, return Def.  This means that there is no dependence and
310     // the access can be optimized based on that.  For example, a load could
311     // turn into undef.
312     // Note: Only determine this to be a malloc if Inst is the malloc call, not
313     // a subsequent bitcast of the malloc call result.  There can be stores to
314     // the malloced memory between the malloc call and its bitcast uses, and we
315     // need to continue scanning until the malloc call.
316     if (isa<AllocaInst>(Inst) ||
317         (isa<CallInst>(Inst) && extractMallocCall(Inst))) {
318       const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, TD);
319       
320       if (AccessPtr == Inst ||
321           AA->alias(Inst, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
322         return MemDepResult::getDef(Inst);
323       continue;
324     }
325
326     // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
327     switch (AA->getModRefInfo(Inst, MemLoc)) {
328     case AliasAnalysis::NoModRef:
329       // If the call has no effect on the queried pointer, just ignore it.
330       continue;
331     case AliasAnalysis::Mod:
332       return MemDepResult::getClobber(Inst);
333     case AliasAnalysis::Ref:
334       // If the call is known to never store to the pointer, and if this is a
335       // load query, we can safely ignore it (scan past it).
336       if (isLoad)
337         continue;
338     default:
339       // Otherwise, there is a potential dependence.  Return a clobber.
340       return MemDepResult::getClobber(Inst);
341     }
342   }
343   
344   // No dependence found.  If this is the entry block of the function, it is a
345   // clobber, otherwise it is non-local.
346   if (BB != &BB->getParent()->getEntryBlock())
347     return MemDepResult::getNonLocal();
348   return MemDepResult::getClobber(ScanIt);
349 }
350
351 /// getDependency - Return the instruction on which a memory operation
352 /// depends.
353 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
354   Instruction *ScanPos = QueryInst;
355   
356   // Check for a cached result
357   MemDepResult &LocalCache = LocalDeps[QueryInst];
358   
359   // If the cached entry is non-dirty, just return it.  Note that this depends
360   // on MemDepResult's default constructing to 'dirty'.
361   if (!LocalCache.isDirty())
362     return LocalCache;
363     
364   // Otherwise, if we have a dirty entry, we know we can start the scan at that
365   // instruction, which may save us some work.
366   if (Instruction *Inst = LocalCache.getInst()) {
367     ScanPos = Inst;
368    
369     RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
370   }
371   
372   BasicBlock *QueryParent = QueryInst->getParent();
373   
374   // Do the scan.
375   if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
376     // No dependence found.  If this is the entry block of the function, it is a
377     // clobber, otherwise it is non-local.
378     if (QueryParent != &QueryParent->getParent()->getEntryBlock())
379       LocalCache = MemDepResult::getNonLocal();
380     else
381       LocalCache = MemDepResult::getClobber(QueryInst);
382   } else {
383     AliasAnalysis::Location MemLoc;
384     AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
385     if (MemLoc.Ptr) {
386       // If we can do a pointer scan, make it happen.
387       bool isLoad = !(MR & AliasAnalysis::Mod);
388       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
389         isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_end;
390
391       LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
392                                             QueryParent);
393     } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
394       CallSite QueryCS(QueryInst);
395       bool isReadOnly = AA->onlyReadsMemory(QueryCS);
396       LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
397                                              QueryParent);
398     } else
399       // Non-memory instruction.
400       LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
401   }
402   
403   // Remember the result!
404   if (Instruction *I = LocalCache.getInst())
405     ReverseLocalDeps[I].insert(QueryInst);
406   
407   return LocalCache;
408 }
409
410 #ifndef NDEBUG
411 /// AssertSorted - This method is used when -debug is specified to verify that
412 /// cache arrays are properly kept sorted.
413 static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
414                          int Count = -1) {
415   if (Count == -1) Count = Cache.size();
416   if (Count == 0) return;
417
418   for (unsigned i = 1; i != unsigned(Count); ++i)
419     assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
420 }
421 #endif
422
423 /// getNonLocalCallDependency - Perform a full dependency query for the
424 /// specified call, returning the set of blocks that the value is
425 /// potentially live across.  The returned set of results will include a
426 /// "NonLocal" result for all blocks where the value is live across.
427 ///
428 /// This method assumes the instruction returns a "NonLocal" dependency
429 /// within its own block.
430 ///
431 /// This returns a reference to an internal data structure that may be
432 /// invalidated on the next non-local query or when an instruction is
433 /// removed.  Clients must copy this data if they want it around longer than
434 /// that.
435 const MemoryDependenceAnalysis::NonLocalDepInfo &
436 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
437   assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
438  "getNonLocalCallDependency should only be used on calls with non-local deps!");
439   PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
440   NonLocalDepInfo &Cache = CacheP.first;
441
442   /// DirtyBlocks - This is the set of blocks that need to be recomputed.  In
443   /// the cached case, this can happen due to instructions being deleted etc. In
444   /// the uncached case, this starts out as the set of predecessors we care
445   /// about.
446   SmallVector<BasicBlock*, 32> DirtyBlocks;
447   
448   if (!Cache.empty()) {
449     // Okay, we have a cache entry.  If we know it is not dirty, just return it
450     // with no computation.
451     if (!CacheP.second) {
452       ++NumCacheNonLocal;
453       return Cache;
454     }
455     
456     // If we already have a partially computed set of results, scan them to
457     // determine what is dirty, seeding our initial DirtyBlocks worklist.
458     for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
459        I != E; ++I)
460       if (I->getResult().isDirty())
461         DirtyBlocks.push_back(I->getBB());
462     
463     // Sort the cache so that we can do fast binary search lookups below.
464     std::sort(Cache.begin(), Cache.end());
465     
466     ++NumCacheDirtyNonLocal;
467     //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
468     //     << Cache.size() << " cached: " << *QueryInst;
469   } else {
470     // Seed DirtyBlocks with each of the preds of QueryInst's block.
471     BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
472     for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
473       DirtyBlocks.push_back(*PI);
474     ++NumUncacheNonLocal;
475   }
476   
477   // isReadonlyCall - If this is a read-only call, we can be more aggressive.
478   bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
479
480   SmallPtrSet<BasicBlock*, 64> Visited;
481   
482   unsigned NumSortedEntries = Cache.size();
483   DEBUG(AssertSorted(Cache));
484   
485   // Iterate while we still have blocks to update.
486   while (!DirtyBlocks.empty()) {
487     BasicBlock *DirtyBB = DirtyBlocks.back();
488     DirtyBlocks.pop_back();
489     
490     // Already processed this block?
491     if (!Visited.insert(DirtyBB))
492       continue;
493     
494     // Do a binary search to see if we already have an entry for this block in
495     // the cache set.  If so, find it.
496     DEBUG(AssertSorted(Cache, NumSortedEntries));
497     NonLocalDepInfo::iterator Entry = 
498       std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
499                        NonLocalDepEntry(DirtyBB));
500     if (Entry != Cache.begin() && prior(Entry)->getBB() == DirtyBB)
501       --Entry;
502     
503     NonLocalDepEntry *ExistingResult = 0;
504     if (Entry != Cache.begin()+NumSortedEntries && 
505         Entry->getBB() == DirtyBB) {
506       // If we already have an entry, and if it isn't already dirty, the block
507       // is done.
508       if (!Entry->getResult().isDirty())
509         continue;
510       
511       // Otherwise, remember this slot so we can update the value.
512       ExistingResult = &*Entry;
513     }
514     
515     // If the dirty entry has a pointer, start scanning from it so we don't have
516     // to rescan the entire block.
517     BasicBlock::iterator ScanPos = DirtyBB->end();
518     if (ExistingResult) {
519       if (Instruction *Inst = ExistingResult->getResult().getInst()) {
520         ScanPos = Inst;
521         // We're removing QueryInst's use of Inst.
522         RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
523                              QueryCS.getInstruction());
524       }
525     }
526     
527     // Find out if this block has a local dependency for QueryInst.
528     MemDepResult Dep;
529     
530     if (ScanPos != DirtyBB->begin()) {
531       Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
532     } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
533       // No dependence found.  If this is the entry block of the function, it is
534       // a clobber, otherwise it is non-local.
535       Dep = MemDepResult::getNonLocal();
536     } else {
537       Dep = MemDepResult::getClobber(ScanPos);
538     }
539     
540     // If we had a dirty entry for the block, update it.  Otherwise, just add
541     // a new entry.
542     if (ExistingResult)
543       ExistingResult->setResult(Dep);
544     else
545       Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
546     
547     // If the block has a dependency (i.e. it isn't completely transparent to
548     // the value), remember the association!
549     if (!Dep.isNonLocal()) {
550       // Keep the ReverseNonLocalDeps map up to date so we can efficiently
551       // update this when we remove instructions.
552       if (Instruction *Inst = Dep.getInst())
553         ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
554     } else {
555     
556       // If the block *is* completely transparent to the load, we need to check
557       // the predecessors of this block.  Add them to our worklist.
558       for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
559         DirtyBlocks.push_back(*PI);
560     }
561   }
562   
563   return Cache;
564 }
565
566 /// getNonLocalPointerDependency - Perform a full dependency query for an
567 /// access to the specified (non-volatile) memory location, returning the
568 /// set of instructions that either define or clobber the value.
569 ///
570 /// This method assumes the pointer has a "NonLocal" dependency within its
571 /// own block.
572 ///
573 void MemoryDependenceAnalysis::
574 getNonLocalPointerDependency(const AliasAnalysis::Location &Loc, bool isLoad,
575                              BasicBlock *FromBB,
576                              SmallVectorImpl<NonLocalDepResult> &Result) {
577   assert(Loc.Ptr->getType()->isPointerTy() &&
578          "Can't get pointer deps of a non-pointer!");
579   Result.clear();
580   
581   PHITransAddr Address(const_cast<Value *>(Loc.Ptr), TD);
582   
583   // This is the set of blocks we've inspected, and the pointer we consider in
584   // each block.  Because of critical edges, we currently bail out if querying
585   // a block with multiple different pointers.  This can happen during PHI
586   // translation.
587   DenseMap<BasicBlock*, Value*> Visited;
588   if (!getNonLocalPointerDepFromBB(Address, Loc, isLoad, FromBB,
589                                    Result, Visited, true))
590     return;
591   Result.clear();
592   Result.push_back(NonLocalDepResult(FromBB,
593                                      MemDepResult::getClobber(FromBB->begin()),
594                                      const_cast<Value *>(Loc.Ptr)));
595 }
596
597 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
598 /// Pointer/PointeeSize using either cached information in Cache or by doing a
599 /// lookup (which may use dirty cache info if available).  If we do a lookup,
600 /// add the result to the cache.
601 MemDepResult MemoryDependenceAnalysis::
602 GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc,
603                         bool isLoad, BasicBlock *BB,
604                         NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
605   
606   // Do a binary search to see if we already have an entry for this block in
607   // the cache set.  If so, find it.
608   NonLocalDepInfo::iterator Entry =
609     std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
610                      NonLocalDepEntry(BB));
611   if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
612     --Entry;
613   
614   NonLocalDepEntry *ExistingResult = 0;
615   if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
616     ExistingResult = &*Entry;
617   
618   // If we have a cached entry, and it is non-dirty, use it as the value for
619   // this dependency.
620   if (ExistingResult && !ExistingResult->getResult().isDirty()) {
621     ++NumCacheNonLocalPtr;
622     return ExistingResult->getResult();
623   }    
624   
625   // Otherwise, we have to scan for the value.  If we have a dirty cache
626   // entry, start scanning from its position, otherwise we scan from the end
627   // of the block.
628   BasicBlock::iterator ScanPos = BB->end();
629   if (ExistingResult && ExistingResult->getResult().getInst()) {
630     assert(ExistingResult->getResult().getInst()->getParent() == BB &&
631            "Instruction invalidated?");
632     ++NumCacheDirtyNonLocalPtr;
633     ScanPos = ExistingResult->getResult().getInst();
634     
635     // Eliminating the dirty entry from 'Cache', so update the reverse info.
636     ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
637     RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
638   } else {
639     ++NumUncacheNonLocalPtr;
640   }
641   
642   // Scan the block for the dependency.
643   MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB);
644   
645   // If we had a dirty entry for the block, update it.  Otherwise, just add
646   // a new entry.
647   if (ExistingResult)
648     ExistingResult->setResult(Dep);
649   else
650     Cache->push_back(NonLocalDepEntry(BB, Dep));
651   
652   // If the block has a dependency (i.e. it isn't completely transparent to
653   // the value), remember the reverse association because we just added it
654   // to Cache!
655   if (Dep.isNonLocal())
656     return Dep;
657   
658   // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
659   // update MemDep when we remove instructions.
660   Instruction *Inst = Dep.getInst();
661   assert(Inst && "Didn't depend on anything?");
662   ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
663   ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
664   return Dep;
665 }
666
667 /// SortNonLocalDepInfoCache - Sort the a NonLocalDepInfo cache, given a certain
668 /// number of elements in the array that are already properly ordered.  This is
669 /// optimized for the case when only a few entries are added.
670 static void 
671 SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
672                          unsigned NumSortedEntries) {
673   switch (Cache.size() - NumSortedEntries) {
674   case 0:
675     // done, no new entries.
676     break;
677   case 2: {
678     // Two new entries, insert the last one into place.
679     NonLocalDepEntry Val = Cache.back();
680     Cache.pop_back();
681     MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
682       std::upper_bound(Cache.begin(), Cache.end()-1, Val);
683     Cache.insert(Entry, Val);
684     // FALL THROUGH.
685   }
686   case 1:
687     // One new entry, Just insert the new value at the appropriate position.
688     if (Cache.size() != 1) {
689       NonLocalDepEntry Val = Cache.back();
690       Cache.pop_back();
691       MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
692         std::upper_bound(Cache.begin(), Cache.end(), Val);
693       Cache.insert(Entry, Val);
694     }
695     break;
696   default:
697     // Added many values, do a full scale sort.
698     std::sort(Cache.begin(), Cache.end());
699     break;
700   }
701 }
702
703 /// getNonLocalPointerDepFromBB - Perform a dependency query based on
704 /// pointer/pointeesize starting at the end of StartBB.  Add any clobber/def
705 /// results to the results vector and keep track of which blocks are visited in
706 /// 'Visited'.
707 ///
708 /// This has special behavior for the first block queries (when SkipFirstBlock
709 /// is true).  In this special case, it ignores the contents of the specified
710 /// block and starts returning dependence info for its predecessors.
711 ///
712 /// This function returns false on success, or true to indicate that it could
713 /// not compute dependence information for some reason.  This should be treated
714 /// as a clobber dependence on the first instruction in the predecessor block.
715 bool MemoryDependenceAnalysis::
716 getNonLocalPointerDepFromBB(const PHITransAddr &Pointer,
717                             const AliasAnalysis::Location &Loc,
718                             bool isLoad, BasicBlock *StartBB,
719                             SmallVectorImpl<NonLocalDepResult> &Result,
720                             DenseMap<BasicBlock*, Value*> &Visited,
721                             bool SkipFirstBlock) {
722   
723   // Look up the cached info for Pointer.
724   ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
725
726   // Set up a temporary NLPI value. If the map doesn't yet have an entry for
727   // CacheKey, this value will be inserted as the associated value. Otherwise,
728   // it'll be ignored, and we'll have to check to see if the cached size and
729   // tbaa tag are consistent with the current query.
730   NonLocalPointerInfo InitialNLPI;
731   InitialNLPI.Size = Loc.Size;
732   InitialNLPI.TBAATag = Loc.TBAATag;
733
734   // Get the NLPI for CacheKey, inserting one into the map if it doesn't
735   // already have one.
736   std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair = 
737     NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
738   NonLocalPointerInfo *CacheInfo = &Pair.first->second;
739
740   // If we already have a cache entry for this CacheKey, we may need to do some
741   // work to reconcile the cache entry and the current query.
742   if (!Pair.second) {
743     if (CacheInfo->Size < Loc.Size) {
744       // The query's Size is greater than the cached one. Throw out the
745       // cached data and procede with the query at the greater size.
746       CacheInfo->Pair = BBSkipFirstBlockPair();
747       CacheInfo->Size = Loc.Size;
748       for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
749            DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
750         if (Instruction *Inst = DI->getResult().getInst())
751           RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
752       CacheInfo->NonLocalDeps.clear();
753     } else if (CacheInfo->Size > Loc.Size) {
754       // This query's Size is less than the cached one. Conservatively restart
755       // the query using the greater size.
756       return getNonLocalPointerDepFromBB(Pointer,
757                                          Loc.getWithNewSize(CacheInfo->Size),
758                                          isLoad, StartBB, Result, Visited,
759                                          SkipFirstBlock);
760     }
761
762     // If the query's TBAATag is inconsistent with the cached one,
763     // conservatively throw out the cached data and restart the query with
764     // no tag if needed.
765     if (CacheInfo->TBAATag != Loc.TBAATag) {
766       if (CacheInfo->TBAATag) {
767         CacheInfo->Pair = BBSkipFirstBlockPair();
768         CacheInfo->TBAATag = 0;
769         for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
770              DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
771           if (Instruction *Inst = DI->getResult().getInst())
772             RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
773         CacheInfo->NonLocalDeps.clear();
774       }
775       if (Loc.TBAATag)
776         return getNonLocalPointerDepFromBB(Pointer, Loc.getWithoutTBAATag(),
777                                            isLoad, StartBB, Result, Visited,
778                                            SkipFirstBlock);
779     }
780   }
781
782   NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
783
784   // If we have valid cached information for exactly the block we are
785   // investigating, just return it with no recomputation.
786   if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
787     // We have a fully cached result for this query then we can just return the
788     // cached results and populate the visited set.  However, we have to verify
789     // that we don't already have conflicting results for these blocks.  Check
790     // to ensure that if a block in the results set is in the visited set that
791     // it was for the same pointer query.
792     if (!Visited.empty()) {
793       for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
794            I != E; ++I) {
795         DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
796         if (VI == Visited.end() || VI->second == Pointer.getAddr())
797           continue;
798         
799         // We have a pointer mismatch in a block.  Just return clobber, saying
800         // that something was clobbered in this result.  We could also do a
801         // non-fully cached query, but there is little point in doing this.
802         return true;
803       }
804     }
805     
806     Value *Addr = Pointer.getAddr();
807     for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
808          I != E; ++I) {
809       Visited.insert(std::make_pair(I->getBB(), Addr));
810       if (!I->getResult().isNonLocal())
811         Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
812     }
813     ++NumCacheCompleteNonLocalPtr;
814     return false;
815   }
816   
817   // Otherwise, either this is a new block, a block with an invalid cache
818   // pointer or one that we're about to invalidate by putting more info into it
819   // than its valid cache info.  If empty, the result will be valid cache info,
820   // otherwise it isn't.
821   if (Cache->empty())
822     CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
823   else
824     CacheInfo->Pair = BBSkipFirstBlockPair();
825   
826   SmallVector<BasicBlock*, 32> Worklist;
827   Worklist.push_back(StartBB);
828   
829   // Keep track of the entries that we know are sorted.  Previously cached
830   // entries will all be sorted.  The entries we add we only sort on demand (we
831   // don't insert every element into its sorted position).  We know that we
832   // won't get any reuse from currently inserted values, because we don't
833   // revisit blocks after we insert info for them.
834   unsigned NumSortedEntries = Cache->size();
835   DEBUG(AssertSorted(*Cache));
836   
837   while (!Worklist.empty()) {
838     BasicBlock *BB = Worklist.pop_back_val();
839     
840     // Skip the first block if we have it.
841     if (!SkipFirstBlock) {
842       // Analyze the dependency of *Pointer in FromBB.  See if we already have
843       // been here.
844       assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
845
846       // Get the dependency info for Pointer in BB.  If we have cached
847       // information, we will use it, otherwise we compute it.
848       DEBUG(AssertSorted(*Cache, NumSortedEntries));
849       MemDepResult Dep = GetNonLocalInfoForBlock(Loc, isLoad, BB, Cache,
850                                                  NumSortedEntries);
851       
852       // If we got a Def or Clobber, add this to the list of results.
853       if (!Dep.isNonLocal()) {
854         Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
855         continue;
856       }
857     }
858     
859     // If 'Pointer' is an instruction defined in this block, then we need to do
860     // phi translation to change it into a value live in the predecessor block.
861     // If not, we just add the predecessors to the worklist and scan them with
862     // the same Pointer.
863     if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
864       SkipFirstBlock = false;
865       for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
866         // Verify that we haven't looked at this block yet.
867         std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
868           InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr()));
869         if (InsertRes.second) {
870           // First time we've looked at *PI.
871           Worklist.push_back(*PI);
872           continue;
873         }
874         
875         // If we have seen this block before, but it was with a different
876         // pointer then we have a phi translation failure and we have to treat
877         // this as a clobber.
878         if (InsertRes.first->second != Pointer.getAddr())
879           goto PredTranslationFailure;
880       }
881       continue;
882     }
883     
884     // We do need to do phi translation, if we know ahead of time we can't phi
885     // translate this value, don't even try.
886     if (!Pointer.IsPotentiallyPHITranslatable())
887       goto PredTranslationFailure;
888     
889     // We may have added values to the cache list before this PHI translation.
890     // If so, we haven't done anything to ensure that the cache remains sorted.
891     // Sort it now (if needed) so that recursive invocations of
892     // getNonLocalPointerDepFromBB and other routines that could reuse the cache
893     // value will only see properly sorted cache arrays.
894     if (Cache && NumSortedEntries != Cache->size()) {
895       SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
896       NumSortedEntries = Cache->size();
897     }
898     Cache = 0;
899     
900     for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
901       BasicBlock *Pred = *PI;
902       
903       // Get the PHI translated pointer in this predecessor.  This can fail if
904       // not translatable, in which case the getAddr() returns null.
905       PHITransAddr PredPointer(Pointer);
906       PredPointer.PHITranslateValue(BB, Pred, 0);
907
908       Value *PredPtrVal = PredPointer.getAddr();
909       
910       // Check to see if we have already visited this pred block with another
911       // pointer.  If so, we can't do this lookup.  This failure can occur
912       // with PHI translation when a critical edge exists and the PHI node in
913       // the successor translates to a pointer value different than the
914       // pointer the block was first analyzed with.
915       std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
916         InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
917
918       if (!InsertRes.second) {
919         // If the predecessor was visited with PredPtr, then we already did
920         // the analysis and can ignore it.
921         if (InsertRes.first->second == PredPtrVal)
922           continue;
923         
924         // Otherwise, the block was previously analyzed with a different
925         // pointer.  We can't represent the result of this case, so we just
926         // treat this as a phi translation failure.
927         goto PredTranslationFailure;
928       }
929       
930       // If PHI translation was unable to find an available pointer in this
931       // predecessor, then we have to assume that the pointer is clobbered in
932       // that predecessor.  We can still do PRE of the load, which would insert
933       // a computation of the pointer in this predecessor.
934       if (PredPtrVal == 0) {
935         // Add the entry to the Result list.
936         NonLocalDepResult Entry(Pred,
937                                 MemDepResult::getClobber(Pred->getTerminator()),
938                                 PredPtrVal);
939         Result.push_back(Entry);
940
941         // Since we had a phi translation failure, the cache for CacheKey won't
942         // include all of the entries that we need to immediately satisfy future
943         // queries.  Mark this in NonLocalPointerDeps by setting the
944         // BBSkipFirstBlockPair pointer to null.  This requires reuse of the
945         // cached value to do more work but not miss the phi trans failure.
946         NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
947         NLPI.Pair = BBSkipFirstBlockPair();
948         continue;
949       }
950
951       // FIXME: it is entirely possible that PHI translating will end up with
952       // the same value.  Consider PHI translating something like:
953       // X = phi [x, bb1], [y, bb2].  PHI translating for bb1 doesn't *need*
954       // to recurse here, pedantically speaking.
955       
956       // If we have a problem phi translating, fall through to the code below
957       // to handle the failure condition.
958       if (getNonLocalPointerDepFromBB(PredPointer,
959                                       Loc.getWithNewPtr(PredPointer.getAddr()),
960                                       isLoad, Pred,
961                                       Result, Visited))
962         goto PredTranslationFailure;
963     }
964     
965     // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
966     CacheInfo = &NonLocalPointerDeps[CacheKey];
967     Cache = &CacheInfo->NonLocalDeps;
968     NumSortedEntries = Cache->size();
969     
970     // Since we did phi translation, the "Cache" set won't contain all of the
971     // results for the query.  This is ok (we can still use it to accelerate
972     // specific block queries) but we can't do the fastpath "return all
973     // results from the set"  Clear out the indicator for this.
974     CacheInfo->Pair = BBSkipFirstBlockPair();
975     SkipFirstBlock = false;
976     continue;
977
978   PredTranslationFailure:
979     
980     if (Cache == 0) {
981       // Refresh the CacheInfo/Cache pointer if it got invalidated.
982       CacheInfo = &NonLocalPointerDeps[CacheKey];
983       Cache = &CacheInfo->NonLocalDeps;
984       NumSortedEntries = Cache->size();
985     }
986     
987     // Since we failed phi translation, the "Cache" set won't contain all of the
988     // results for the query.  This is ok (we can still use it to accelerate
989     // specific block queries) but we can't do the fastpath "return all
990     // results from the set".  Clear out the indicator for this.
991     CacheInfo->Pair = BBSkipFirstBlockPair();
992     
993     // If *nothing* works, mark the pointer as being clobbered by the first
994     // instruction in this block.
995     //
996     // If this is the magic first block, return this as a clobber of the whole
997     // incoming value.  Since we can't phi translate to one of the predecessors,
998     // we have to bail out.
999     if (SkipFirstBlock)
1000       return true;
1001     
1002     for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
1003       assert(I != Cache->rend() && "Didn't find current block??");
1004       if (I->getBB() != BB)
1005         continue;
1006       
1007       assert(I->getResult().isNonLocal() &&
1008              "Should only be here with transparent block");
1009       I->setResult(MemDepResult::getClobber(BB->begin()));
1010       ReverseNonLocalPtrDeps[BB->begin()].insert(CacheKey);
1011       Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
1012                                          Pointer.getAddr()));
1013       break;
1014     }
1015   }
1016
1017   // Okay, we're done now.  If we added new values to the cache, re-sort it.
1018   SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1019   DEBUG(AssertSorted(*Cache));
1020   return false;
1021 }
1022
1023 /// RemoveCachedNonLocalPointerDependencies - If P exists in
1024 /// CachedNonLocalPointerInfo, remove it.
1025 void MemoryDependenceAnalysis::
1026 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
1027   CachedNonLocalPointerInfo::iterator It = 
1028     NonLocalPointerDeps.find(P);
1029   if (It == NonLocalPointerDeps.end()) return;
1030   
1031   // Remove all of the entries in the BB->val map.  This involves removing
1032   // instructions from the reverse map.
1033   NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1034   
1035   for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1036     Instruction *Target = PInfo[i].getResult().getInst();
1037     if (Target == 0) continue;  // Ignore non-local dep results.
1038     assert(Target->getParent() == PInfo[i].getBB());
1039     
1040     // Eliminating the dirty entry from 'Cache', so update the reverse info.
1041     RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1042   }
1043   
1044   // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1045   NonLocalPointerDeps.erase(It);
1046 }
1047
1048
1049 /// invalidateCachedPointerInfo - This method is used to invalidate cached
1050 /// information about the specified pointer, because it may be too
1051 /// conservative in memdep.  This is an optional call that can be used when
1052 /// the client detects an equivalence between the pointer and some other
1053 /// value and replaces the other value with ptr. This can make Ptr available
1054 /// in more places that cached info does not necessarily keep.
1055 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
1056   // If Ptr isn't really a pointer, just ignore it.
1057   if (!Ptr->getType()->isPointerTy()) return;
1058   // Flush store info for the pointer.
1059   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1060   // Flush load info for the pointer.
1061   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1062 }
1063
1064 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
1065 /// This needs to be done when the CFG changes, e.g., due to splitting
1066 /// critical edges.
1067 void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
1068   PredCache->clear();
1069 }
1070
1071 /// removeInstruction - Remove an instruction from the dependence analysis,
1072 /// updating the dependence of instructions that previously depended on it.
1073 /// This method attempts to keep the cache coherent using the reverse map.
1074 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
1075   // Walk through the Non-local dependencies, removing this one as the value
1076   // for any cached queries.
1077   NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1078   if (NLDI != NonLocalDeps.end()) {
1079     NonLocalDepInfo &BlockMap = NLDI->second.first;
1080     for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
1081          DI != DE; ++DI)
1082       if (Instruction *Inst = DI->getResult().getInst())
1083         RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1084     NonLocalDeps.erase(NLDI);
1085   }
1086
1087   // If we have a cached local dependence query for this instruction, remove it.
1088   //
1089   LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1090   if (LocalDepEntry != LocalDeps.end()) {
1091     // Remove us from DepInst's reverse set now that the local dep info is gone.
1092     if (Instruction *Inst = LocalDepEntry->second.getInst())
1093       RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1094
1095     // Remove this local dependency info.
1096     LocalDeps.erase(LocalDepEntry);
1097   }
1098   
1099   // If we have any cached pointer dependencies on this instruction, remove
1100   // them.  If the instruction has non-pointer type, then it can't be a pointer
1101   // base.
1102   
1103   // Remove it from both the load info and the store info.  The instruction
1104   // can't be in either of these maps if it is non-pointer.
1105   if (RemInst->getType()->isPointerTy()) {
1106     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1107     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1108   }
1109   
1110   // Loop over all of the things that depend on the instruction we're removing.
1111   // 
1112   SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
1113
1114   // If we find RemInst as a clobber or Def in any of the maps for other values,
1115   // we need to replace its entry with a dirty version of the instruction after
1116   // it.  If RemInst is a terminator, we use a null dirty value.
1117   //
1118   // Using a dirty version of the instruction after RemInst saves having to scan
1119   // the entire block to get to this point.
1120   MemDepResult NewDirtyVal;
1121   if (!RemInst->isTerminator())
1122     NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
1123   
1124   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1125   if (ReverseDepIt != ReverseLocalDeps.end()) {
1126     SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
1127     // RemInst can't be the terminator if it has local stuff depending on it.
1128     assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
1129            "Nothing can locally depend on a terminator");
1130     
1131     for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
1132          E = ReverseDeps.end(); I != E; ++I) {
1133       Instruction *InstDependingOnRemInst = *I;
1134       assert(InstDependingOnRemInst != RemInst &&
1135              "Already removed our local dep info");
1136                         
1137       LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1138       
1139       // Make sure to remember that new things depend on NewDepInst.
1140       assert(NewDirtyVal.getInst() && "There is no way something else can have "
1141              "a local dep on this if it is a terminator!");
1142       ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(), 
1143                                                 InstDependingOnRemInst));
1144     }
1145     
1146     ReverseLocalDeps.erase(ReverseDepIt);
1147
1148     // Add new reverse deps after scanning the set, to avoid invalidating the
1149     // 'ReverseDeps' reference.
1150     while (!ReverseDepsToAdd.empty()) {
1151       ReverseLocalDeps[ReverseDepsToAdd.back().first]
1152         .insert(ReverseDepsToAdd.back().second);
1153       ReverseDepsToAdd.pop_back();
1154     }
1155   }
1156   
1157   ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1158   if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1159     SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
1160     for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
1161          I != E; ++I) {
1162       assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
1163       
1164       PerInstNLInfo &INLD = NonLocalDeps[*I];
1165       // The information is now dirty!
1166       INLD.second = true;
1167       
1168       for (NonLocalDepInfo::iterator DI = INLD.first.begin(), 
1169            DE = INLD.first.end(); DI != DE; ++DI) {
1170         if (DI->getResult().getInst() != RemInst) continue;
1171         
1172         // Convert to a dirty entry for the subsequent instruction.
1173         DI->setResult(NewDirtyVal);
1174         
1175         if (Instruction *NextI = NewDirtyVal.getInst())
1176           ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
1177       }
1178     }
1179
1180     ReverseNonLocalDeps.erase(ReverseDepIt);
1181
1182     // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1183     while (!ReverseDepsToAdd.empty()) {
1184       ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
1185         .insert(ReverseDepsToAdd.back().second);
1186       ReverseDepsToAdd.pop_back();
1187     }
1188   }
1189   
1190   // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1191   // value in the NonLocalPointerDeps info.
1192   ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1193     ReverseNonLocalPtrDeps.find(RemInst);
1194   if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1195     SmallPtrSet<ValueIsLoadPair, 4> &Set = ReversePtrDepIt->second;
1196     SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
1197     
1198     for (SmallPtrSet<ValueIsLoadPair, 4>::iterator I = Set.begin(),
1199          E = Set.end(); I != E; ++I) {
1200       ValueIsLoadPair P = *I;
1201       assert(P.getPointer() != RemInst &&
1202              "Already removed NonLocalPointerDeps info for RemInst");
1203       
1204       NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1205       
1206       // The cache is not valid for any specific block anymore.
1207       NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1208       
1209       // Update any entries for RemInst to use the instruction after it.
1210       for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
1211            DI != DE; ++DI) {
1212         if (DI->getResult().getInst() != RemInst) continue;
1213         
1214         // Convert to a dirty entry for the subsequent instruction.
1215         DI->setResult(NewDirtyVal);
1216         
1217         if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1218           ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1219       }
1220       
1221       // Re-sort the NonLocalDepInfo.  Changing the dirty entry to its
1222       // subsequent value may invalidate the sortedness.
1223       std::sort(NLPDI.begin(), NLPDI.end());
1224     }
1225     
1226     ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1227     
1228     while (!ReversePtrDepsToAdd.empty()) {
1229       ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
1230         .insert(ReversePtrDepsToAdd.back().second);
1231       ReversePtrDepsToAdd.pop_back();
1232     }
1233   }
1234   
1235   
1236   assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1237   AA->deleteValue(RemInst);
1238   DEBUG(verifyRemoved(RemInst));
1239 }
1240 /// verifyRemoved - Verify that the specified instruction does not occur
1241 /// in our internal data structures.
1242 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
1243   for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
1244        E = LocalDeps.end(); I != E; ++I) {
1245     assert(I->first != D && "Inst occurs in data structures");
1246     assert(I->second.getInst() != D &&
1247            "Inst occurs in data structures");
1248   }
1249   
1250   for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
1251        E = NonLocalPointerDeps.end(); I != E; ++I) {
1252     assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
1253     const NonLocalDepInfo &Val = I->second.NonLocalDeps;
1254     for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
1255          II != E; ++II)
1256       assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
1257   }
1258   
1259   for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
1260        E = NonLocalDeps.end(); I != E; ++I) {
1261     assert(I->first != D && "Inst occurs in data structures");
1262     const PerInstNLInfo &INLD = I->second;
1263     for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
1264          EE = INLD.first.end(); II  != EE; ++II)
1265       assert(II->getResult().getInst() != D && "Inst occurs in data structures");
1266   }
1267   
1268   for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
1269        E = ReverseLocalDeps.end(); I != E; ++I) {
1270     assert(I->first != D && "Inst occurs in data structures");
1271     for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1272          EE = I->second.end(); II != EE; ++II)
1273       assert(*II != D && "Inst occurs in data structures");
1274   }
1275   
1276   for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
1277        E = ReverseNonLocalDeps.end();
1278        I != E; ++I) {
1279     assert(I->first != D && "Inst occurs in data structures");
1280     for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1281          EE = I->second.end(); II != EE; ++II)
1282       assert(*II != D && "Inst occurs in data structures");
1283   }
1284   
1285   for (ReverseNonLocalPtrDepTy::const_iterator
1286        I = ReverseNonLocalPtrDeps.begin(),
1287        E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
1288     assert(I->first != D && "Inst occurs in rev NLPD map");
1289     
1290     for (SmallPtrSet<ValueIsLoadPair, 4>::const_iterator II = I->second.begin(),
1291          E = I->second.end(); II != E; ++II)
1292       assert(*II != ValueIsLoadPair(D, false) &&
1293              *II != ValueIsLoadPair(D, true) &&
1294              "Inst occurs in ReverseNonLocalPtrDeps map");
1295   }
1296   
1297 }