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