teach GVN to widen integer loads when they are overaligned, when doing an
[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 we have a partial alias, then return this as a clobber for the
378         // client to handle.
379         if (R == AliasAnalysis::PartialAlias)
380           return MemDepResult::getClobber(Inst);
381         
382         // Random may-alias loads don't depend on each other without a
383         // dependence.
384         continue;
385       }
386
387       // Stores don't depend on other no-aliased accesses.
388       if (R == AliasAnalysis::NoAlias)
389         continue;
390
391       // Stores don't alias loads from read-only memory.
392       if (AA->pointsToConstantMemory(LoadLoc))
393         continue;
394
395       // Stores depend on may/must aliased loads.
396       return MemDepResult::getDef(Inst);
397     }
398     
399     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
400       // If alias analysis can tell that this store is guaranteed to not modify
401       // the query pointer, ignore it.  Use getModRefInfo to handle cases where
402       // the query pointer points to constant memory etc.
403       if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
404         continue;
405
406       // Ok, this store might clobber the query pointer.  Check to see if it is
407       // a must alias: in this case, we want to return this as a def.
408       AliasAnalysis::Location StoreLoc = AA->getLocation(SI);
409       
410       // If we found a pointer, check if it could be the same as our pointer.
411       AliasAnalysis::AliasResult R = AA->alias(StoreLoc, MemLoc);
412       
413       if (R == AliasAnalysis::NoAlias)
414         continue;
415       if (R == AliasAnalysis::MustAlias)
416         return MemDepResult::getDef(Inst);
417       return MemDepResult::getClobber(Inst);
418     }
419
420     // If this is an allocation, and if we know that the accessed pointer is to
421     // the allocation, return Def.  This means that there is no dependence and
422     // the access can be optimized based on that.  For example, a load could
423     // turn into undef.
424     // Note: Only determine this to be a malloc if Inst is the malloc call, not
425     // a subsequent bitcast of the malloc call result.  There can be stores to
426     // the malloced memory between the malloc call and its bitcast uses, and we
427     // need to continue scanning until the malloc call.
428     if (isa<AllocaInst>(Inst) ||
429         (isa<CallInst>(Inst) && extractMallocCall(Inst))) {
430       const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, TD);
431       
432       if (AccessPtr == Inst || AA->isMustAlias(Inst, AccessPtr))
433         return MemDepResult::getDef(Inst);
434       continue;
435     }
436
437     // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
438     switch (AA->getModRefInfo(Inst, MemLoc)) {
439     case AliasAnalysis::NoModRef:
440       // If the call has no effect on the queried pointer, just ignore it.
441       continue;
442     case AliasAnalysis::Mod:
443       return MemDepResult::getClobber(Inst);
444     case AliasAnalysis::Ref:
445       // If the call is known to never store to the pointer, and if this is a
446       // load query, we can safely ignore it (scan past it).
447       if (isLoad)
448         continue;
449     default:
450       // Otherwise, there is a potential dependence.  Return a clobber.
451       return MemDepResult::getClobber(Inst);
452     }
453   }
454   
455   // No dependence found.  If this is the entry block of the function, it is a
456   // clobber, otherwise it is non-local.
457   if (BB != &BB->getParent()->getEntryBlock())
458     return MemDepResult::getNonLocal();
459   return MemDepResult::getClobber(ScanIt);
460 }
461
462 /// getDependency - Return the instruction on which a memory operation
463 /// depends.
464 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
465   Instruction *ScanPos = QueryInst;
466   
467   // Check for a cached result
468   MemDepResult &LocalCache = LocalDeps[QueryInst];
469   
470   // If the cached entry is non-dirty, just return it.  Note that this depends
471   // on MemDepResult's default constructing to 'dirty'.
472   if (!LocalCache.isDirty())
473     return LocalCache;
474     
475   // Otherwise, if we have a dirty entry, we know we can start the scan at that
476   // instruction, which may save us some work.
477   if (Instruction *Inst = LocalCache.getInst()) {
478     ScanPos = Inst;
479    
480     RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
481   }
482   
483   BasicBlock *QueryParent = QueryInst->getParent();
484   
485   // Do the scan.
486   if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
487     // No dependence found.  If this is the entry block of the function, it is a
488     // clobber, otherwise it is non-local.
489     if (QueryParent != &QueryParent->getParent()->getEntryBlock())
490       LocalCache = MemDepResult::getNonLocal();
491     else
492       LocalCache = MemDepResult::getClobber(QueryInst);
493   } else {
494     AliasAnalysis::Location MemLoc;
495     AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
496     if (MemLoc.Ptr) {
497       // If we can do a pointer scan, make it happen.
498       bool isLoad = !(MR & AliasAnalysis::Mod);
499       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
500         isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_end;
501
502       LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
503                                             QueryParent);
504     } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
505       CallSite QueryCS(QueryInst);
506       bool isReadOnly = AA->onlyReadsMemory(QueryCS);
507       LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
508                                              QueryParent);
509     } else
510       // Non-memory instruction.
511       LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
512   }
513   
514   // Remember the result!
515   if (Instruction *I = LocalCache.getInst())
516     ReverseLocalDeps[I].insert(QueryInst);
517   
518   return LocalCache;
519 }
520
521 #ifndef NDEBUG
522 /// AssertSorted - This method is used when -debug is specified to verify that
523 /// cache arrays are properly kept sorted.
524 static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
525                          int Count = -1) {
526   if (Count == -1) Count = Cache.size();
527   if (Count == 0) return;
528
529   for (unsigned i = 1; i != unsigned(Count); ++i)
530     assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
531 }
532 #endif
533
534 /// getNonLocalCallDependency - Perform a full dependency query for the
535 /// specified call, returning the set of blocks that the value is
536 /// potentially live across.  The returned set of results will include a
537 /// "NonLocal" result for all blocks where the value is live across.
538 ///
539 /// This method assumes the instruction returns a "NonLocal" dependency
540 /// within its own block.
541 ///
542 /// This returns a reference to an internal data structure that may be
543 /// invalidated on the next non-local query or when an instruction is
544 /// removed.  Clients must copy this data if they want it around longer than
545 /// that.
546 const MemoryDependenceAnalysis::NonLocalDepInfo &
547 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
548   assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
549  "getNonLocalCallDependency should only be used on calls with non-local deps!");
550   PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
551   NonLocalDepInfo &Cache = CacheP.first;
552
553   /// DirtyBlocks - This is the set of blocks that need to be recomputed.  In
554   /// the cached case, this can happen due to instructions being deleted etc. In
555   /// the uncached case, this starts out as the set of predecessors we care
556   /// about.
557   SmallVector<BasicBlock*, 32> DirtyBlocks;
558   
559   if (!Cache.empty()) {
560     // Okay, we have a cache entry.  If we know it is not dirty, just return it
561     // with no computation.
562     if (!CacheP.second) {
563       ++NumCacheNonLocal;
564       return Cache;
565     }
566     
567     // If we already have a partially computed set of results, scan them to
568     // determine what is dirty, seeding our initial DirtyBlocks worklist.
569     for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
570        I != E; ++I)
571       if (I->getResult().isDirty())
572         DirtyBlocks.push_back(I->getBB());
573     
574     // Sort the cache so that we can do fast binary search lookups below.
575     std::sort(Cache.begin(), Cache.end());
576     
577     ++NumCacheDirtyNonLocal;
578     //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
579     //     << Cache.size() << " cached: " << *QueryInst;
580   } else {
581     // Seed DirtyBlocks with each of the preds of QueryInst's block.
582     BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
583     for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
584       DirtyBlocks.push_back(*PI);
585     ++NumUncacheNonLocal;
586   }
587   
588   // isReadonlyCall - If this is a read-only call, we can be more aggressive.
589   bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
590
591   SmallPtrSet<BasicBlock*, 64> Visited;
592   
593   unsigned NumSortedEntries = Cache.size();
594   DEBUG(AssertSorted(Cache));
595   
596   // Iterate while we still have blocks to update.
597   while (!DirtyBlocks.empty()) {
598     BasicBlock *DirtyBB = DirtyBlocks.back();
599     DirtyBlocks.pop_back();
600     
601     // Already processed this block?
602     if (!Visited.insert(DirtyBB))
603       continue;
604     
605     // Do a binary search to see if we already have an entry for this block in
606     // the cache set.  If so, find it.
607     DEBUG(AssertSorted(Cache, NumSortedEntries));
608     NonLocalDepInfo::iterator Entry = 
609       std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
610                        NonLocalDepEntry(DirtyBB));
611     if (Entry != Cache.begin() && prior(Entry)->getBB() == DirtyBB)
612       --Entry;
613     
614     NonLocalDepEntry *ExistingResult = 0;
615     if (Entry != Cache.begin()+NumSortedEntries && 
616         Entry->getBB() == DirtyBB) {
617       // If we already have an entry, and if it isn't already dirty, the block
618       // is done.
619       if (!Entry->getResult().isDirty())
620         continue;
621       
622       // Otherwise, remember this slot so we can update the value.
623       ExistingResult = &*Entry;
624     }
625     
626     // If the dirty entry has a pointer, start scanning from it so we don't have
627     // to rescan the entire block.
628     BasicBlock::iterator ScanPos = DirtyBB->end();
629     if (ExistingResult) {
630       if (Instruction *Inst = ExistingResult->getResult().getInst()) {
631         ScanPos = Inst;
632         // We're removing QueryInst's use of Inst.
633         RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
634                              QueryCS.getInstruction());
635       }
636     }
637     
638     // Find out if this block has a local dependency for QueryInst.
639     MemDepResult Dep;
640     
641     if (ScanPos != DirtyBB->begin()) {
642       Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
643     } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
644       // No dependence found.  If this is the entry block of the function, it is
645       // a clobber, otherwise it is non-local.
646       Dep = MemDepResult::getNonLocal();
647     } else {
648       Dep = MemDepResult::getClobber(ScanPos);
649     }
650     
651     // If we had a dirty entry for the block, update it.  Otherwise, just add
652     // a new entry.
653     if (ExistingResult)
654       ExistingResult->setResult(Dep);
655     else
656       Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
657     
658     // If the block has a dependency (i.e. it isn't completely transparent to
659     // the value), remember the association!
660     if (!Dep.isNonLocal()) {
661       // Keep the ReverseNonLocalDeps map up to date so we can efficiently
662       // update this when we remove instructions.
663       if (Instruction *Inst = Dep.getInst())
664         ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
665     } else {
666     
667       // If the block *is* completely transparent to the load, we need to check
668       // the predecessors of this block.  Add them to our worklist.
669       for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
670         DirtyBlocks.push_back(*PI);
671     }
672   }
673   
674   return Cache;
675 }
676
677 /// getNonLocalPointerDependency - Perform a full dependency query for an
678 /// access to the specified (non-volatile) memory location, returning the
679 /// set of instructions that either define or clobber the value.
680 ///
681 /// This method assumes the pointer has a "NonLocal" dependency within its
682 /// own block.
683 ///
684 void MemoryDependenceAnalysis::
685 getNonLocalPointerDependency(const AliasAnalysis::Location &Loc, bool isLoad,
686                              BasicBlock *FromBB,
687                              SmallVectorImpl<NonLocalDepResult> &Result) {
688   assert(Loc.Ptr->getType()->isPointerTy() &&
689          "Can't get pointer deps of a non-pointer!");
690   Result.clear();
691   
692   PHITransAddr Address(const_cast<Value *>(Loc.Ptr), TD);
693   
694   // This is the set of blocks we've inspected, and the pointer we consider in
695   // each block.  Because of critical edges, we currently bail out if querying
696   // a block with multiple different pointers.  This can happen during PHI
697   // translation.
698   DenseMap<BasicBlock*, Value*> Visited;
699   if (!getNonLocalPointerDepFromBB(Address, Loc, isLoad, FromBB,
700                                    Result, Visited, true))
701     return;
702   Result.clear();
703   Result.push_back(NonLocalDepResult(FromBB,
704                                      MemDepResult::getClobber(FromBB->begin()),
705                                      const_cast<Value *>(Loc.Ptr)));
706 }
707
708 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
709 /// Pointer/PointeeSize using either cached information in Cache or by doing a
710 /// lookup (which may use dirty cache info if available).  If we do a lookup,
711 /// add the result to the cache.
712 MemDepResult MemoryDependenceAnalysis::
713 GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc,
714                         bool isLoad, BasicBlock *BB,
715                         NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
716   
717   // Do a binary search to see if we already have an entry for this block in
718   // the cache set.  If so, find it.
719   NonLocalDepInfo::iterator Entry =
720     std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
721                      NonLocalDepEntry(BB));
722   if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
723     --Entry;
724   
725   NonLocalDepEntry *ExistingResult = 0;
726   if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
727     ExistingResult = &*Entry;
728   
729   // If we have a cached entry, and it is non-dirty, use it as the value for
730   // this dependency.
731   if (ExistingResult && !ExistingResult->getResult().isDirty()) {
732     ++NumCacheNonLocalPtr;
733     return ExistingResult->getResult();
734   }    
735   
736   // Otherwise, we have to scan for the value.  If we have a dirty cache
737   // entry, start scanning from its position, otherwise we scan from the end
738   // of the block.
739   BasicBlock::iterator ScanPos = BB->end();
740   if (ExistingResult && ExistingResult->getResult().getInst()) {
741     assert(ExistingResult->getResult().getInst()->getParent() == BB &&
742            "Instruction invalidated?");
743     ++NumCacheDirtyNonLocalPtr;
744     ScanPos = ExistingResult->getResult().getInst();
745     
746     // Eliminating the dirty entry from 'Cache', so update the reverse info.
747     ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
748     RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
749   } else {
750     ++NumUncacheNonLocalPtr;
751   }
752   
753   // Scan the block for the dependency.
754   MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB);
755   
756   // If we had a dirty entry for the block, update it.  Otherwise, just add
757   // a new entry.
758   if (ExistingResult)
759     ExistingResult->setResult(Dep);
760   else
761     Cache->push_back(NonLocalDepEntry(BB, Dep));
762   
763   // If the block has a dependency (i.e. it isn't completely transparent to
764   // the value), remember the reverse association because we just added it
765   // to Cache!
766   if (Dep.isNonLocal())
767     return Dep;
768   
769   // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
770   // update MemDep when we remove instructions.
771   Instruction *Inst = Dep.getInst();
772   assert(Inst && "Didn't depend on anything?");
773   ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
774   ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
775   return Dep;
776 }
777
778 /// SortNonLocalDepInfoCache - Sort the a NonLocalDepInfo cache, given a certain
779 /// number of elements in the array that are already properly ordered.  This is
780 /// optimized for the case when only a few entries are added.
781 static void 
782 SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
783                          unsigned NumSortedEntries) {
784   switch (Cache.size() - NumSortedEntries) {
785   case 0:
786     // done, no new entries.
787     break;
788   case 2: {
789     // Two new entries, insert the last one into place.
790     NonLocalDepEntry Val = Cache.back();
791     Cache.pop_back();
792     MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
793       std::upper_bound(Cache.begin(), Cache.end()-1, Val);
794     Cache.insert(Entry, Val);
795     // FALL THROUGH.
796   }
797   case 1:
798     // One new entry, Just insert the new value at the appropriate position.
799     if (Cache.size() != 1) {
800       NonLocalDepEntry Val = Cache.back();
801       Cache.pop_back();
802       MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
803         std::upper_bound(Cache.begin(), Cache.end(), Val);
804       Cache.insert(Entry, Val);
805     }
806     break;
807   default:
808     // Added many values, do a full scale sort.
809     std::sort(Cache.begin(), Cache.end());
810     break;
811   }
812 }
813
814 /// getNonLocalPointerDepFromBB - Perform a dependency query based on
815 /// pointer/pointeesize starting at the end of StartBB.  Add any clobber/def
816 /// results to the results vector and keep track of which blocks are visited in
817 /// 'Visited'.
818 ///
819 /// This has special behavior for the first block queries (when SkipFirstBlock
820 /// is true).  In this special case, it ignores the contents of the specified
821 /// block and starts returning dependence info for its predecessors.
822 ///
823 /// This function returns false on success, or true to indicate that it could
824 /// not compute dependence information for some reason.  This should be treated
825 /// as a clobber dependence on the first instruction in the predecessor block.
826 bool MemoryDependenceAnalysis::
827 getNonLocalPointerDepFromBB(const PHITransAddr &Pointer,
828                             const AliasAnalysis::Location &Loc,
829                             bool isLoad, BasicBlock *StartBB,
830                             SmallVectorImpl<NonLocalDepResult> &Result,
831                             DenseMap<BasicBlock*, Value*> &Visited,
832                             bool SkipFirstBlock) {
833   
834   // Look up the cached info for Pointer.
835   ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
836
837   // Set up a temporary NLPI value. If the map doesn't yet have an entry for
838   // CacheKey, this value will be inserted as the associated value. Otherwise,
839   // it'll be ignored, and we'll have to check to see if the cached size and
840   // tbaa tag are consistent with the current query.
841   NonLocalPointerInfo InitialNLPI;
842   InitialNLPI.Size = Loc.Size;
843   InitialNLPI.TBAATag = Loc.TBAATag;
844
845   // Get the NLPI for CacheKey, inserting one into the map if it doesn't
846   // already have one.
847   std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair = 
848     NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
849   NonLocalPointerInfo *CacheInfo = &Pair.first->second;
850
851   // If we already have a cache entry for this CacheKey, we may need to do some
852   // work to reconcile the cache entry and the current query.
853   if (!Pair.second) {
854     if (CacheInfo->Size < Loc.Size) {
855       // The query's Size is greater than the cached one. Throw out the
856       // cached data and procede with the query at the greater size.
857       CacheInfo->Pair = BBSkipFirstBlockPair();
858       CacheInfo->Size = Loc.Size;
859       for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
860            DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
861         if (Instruction *Inst = DI->getResult().getInst())
862           RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
863       CacheInfo->NonLocalDeps.clear();
864     } else if (CacheInfo->Size > Loc.Size) {
865       // This query's Size is less than the cached one. Conservatively restart
866       // the query using the greater size.
867       return getNonLocalPointerDepFromBB(Pointer,
868                                          Loc.getWithNewSize(CacheInfo->Size),
869                                          isLoad, StartBB, Result, Visited,
870                                          SkipFirstBlock);
871     }
872
873     // If the query's TBAATag is inconsistent with the cached one,
874     // conservatively throw out the cached data and restart the query with
875     // no tag if needed.
876     if (CacheInfo->TBAATag != Loc.TBAATag) {
877       if (CacheInfo->TBAATag) {
878         CacheInfo->Pair = BBSkipFirstBlockPair();
879         CacheInfo->TBAATag = 0;
880         for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
881              DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
882           if (Instruction *Inst = DI->getResult().getInst())
883             RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
884         CacheInfo->NonLocalDeps.clear();
885       }
886       if (Loc.TBAATag)
887         return getNonLocalPointerDepFromBB(Pointer, Loc.getWithoutTBAATag(),
888                                            isLoad, StartBB, Result, Visited,
889                                            SkipFirstBlock);
890     }
891   }
892
893   NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
894
895   // If we have valid cached information for exactly the block we are
896   // investigating, just return it with no recomputation.
897   if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
898     // We have a fully cached result for this query then we can just return the
899     // cached results and populate the visited set.  However, we have to verify
900     // that we don't already have conflicting results for these blocks.  Check
901     // to ensure that if a block in the results set is in the visited set that
902     // it was for the same pointer query.
903     if (!Visited.empty()) {
904       for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
905            I != E; ++I) {
906         DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
907         if (VI == Visited.end() || VI->second == Pointer.getAddr())
908           continue;
909         
910         // We have a pointer mismatch in a block.  Just return clobber, saying
911         // that something was clobbered in this result.  We could also do a
912         // non-fully cached query, but there is little point in doing this.
913         return true;
914       }
915     }
916     
917     Value *Addr = Pointer.getAddr();
918     for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
919          I != E; ++I) {
920       Visited.insert(std::make_pair(I->getBB(), Addr));
921       if (!I->getResult().isNonLocal())
922         Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
923     }
924     ++NumCacheCompleteNonLocalPtr;
925     return false;
926   }
927   
928   // Otherwise, either this is a new block, a block with an invalid cache
929   // pointer or one that we're about to invalidate by putting more info into it
930   // than its valid cache info.  If empty, the result will be valid cache info,
931   // otherwise it isn't.
932   if (Cache->empty())
933     CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
934   else
935     CacheInfo->Pair = BBSkipFirstBlockPair();
936   
937   SmallVector<BasicBlock*, 32> Worklist;
938   Worklist.push_back(StartBB);
939   
940   // Keep track of the entries that we know are sorted.  Previously cached
941   // entries will all be sorted.  The entries we add we only sort on demand (we
942   // don't insert every element into its sorted position).  We know that we
943   // won't get any reuse from currently inserted values, because we don't
944   // revisit blocks after we insert info for them.
945   unsigned NumSortedEntries = Cache->size();
946   DEBUG(AssertSorted(*Cache));
947   
948   while (!Worklist.empty()) {
949     BasicBlock *BB = Worklist.pop_back_val();
950     
951     // Skip the first block if we have it.
952     if (!SkipFirstBlock) {
953       // Analyze the dependency of *Pointer in FromBB.  See if we already have
954       // been here.
955       assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
956
957       // Get the dependency info for Pointer in BB.  If we have cached
958       // information, we will use it, otherwise we compute it.
959       DEBUG(AssertSorted(*Cache, NumSortedEntries));
960       MemDepResult Dep = GetNonLocalInfoForBlock(Loc, isLoad, BB, Cache,
961                                                  NumSortedEntries);
962       
963       // If we got a Def or Clobber, add this to the list of results.
964       if (!Dep.isNonLocal()) {
965         Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
966         continue;
967       }
968     }
969     
970     // If 'Pointer' is an instruction defined in this block, then we need to do
971     // phi translation to change it into a value live in the predecessor block.
972     // If not, we just add the predecessors to the worklist and scan them with
973     // the same Pointer.
974     if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
975       SkipFirstBlock = false;
976       for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
977         // Verify that we haven't looked at this block yet.
978         std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
979           InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr()));
980         if (InsertRes.second) {
981           // First time we've looked at *PI.
982           Worklist.push_back(*PI);
983           continue;
984         }
985         
986         // If we have seen this block before, but it was with a different
987         // pointer then we have a phi translation failure and we have to treat
988         // this as a clobber.
989         if (InsertRes.first->second != Pointer.getAddr())
990           goto PredTranslationFailure;
991       }
992       continue;
993     }
994     
995     // We do need to do phi translation, if we know ahead of time we can't phi
996     // translate this value, don't even try.
997     if (!Pointer.IsPotentiallyPHITranslatable())
998       goto PredTranslationFailure;
999     
1000     // We may have added values to the cache list before this PHI translation.
1001     // If so, we haven't done anything to ensure that the cache remains sorted.
1002     // Sort it now (if needed) so that recursive invocations of
1003     // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1004     // value will only see properly sorted cache arrays.
1005     if (Cache && NumSortedEntries != Cache->size()) {
1006       SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1007       NumSortedEntries = Cache->size();
1008     }
1009     Cache = 0;
1010     
1011     for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
1012       BasicBlock *Pred = *PI;
1013       
1014       // Get the PHI translated pointer in this predecessor.  This can fail if
1015       // not translatable, in which case the getAddr() returns null.
1016       PHITransAddr PredPointer(Pointer);
1017       PredPointer.PHITranslateValue(BB, Pred, 0);
1018
1019       Value *PredPtrVal = PredPointer.getAddr();
1020       
1021       // Check to see if we have already visited this pred block with another
1022       // pointer.  If so, we can't do this lookup.  This failure can occur
1023       // with PHI translation when a critical edge exists and the PHI node in
1024       // the successor translates to a pointer value different than the
1025       // pointer the block was first analyzed with.
1026       std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
1027         InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
1028
1029       if (!InsertRes.second) {
1030         // If the predecessor was visited with PredPtr, then we already did
1031         // the analysis and can ignore it.
1032         if (InsertRes.first->second == PredPtrVal)
1033           continue;
1034         
1035         // Otherwise, the block was previously analyzed with a different
1036         // pointer.  We can't represent the result of this case, so we just
1037         // treat this as a phi translation failure.
1038         goto PredTranslationFailure;
1039       }
1040       
1041       // If PHI translation was unable to find an available pointer in this
1042       // predecessor, then we have to assume that the pointer is clobbered in
1043       // that predecessor.  We can still do PRE of the load, which would insert
1044       // a computation of the pointer in this predecessor.
1045       if (PredPtrVal == 0) {
1046         // Add the entry to the Result list.
1047         NonLocalDepResult Entry(Pred,
1048                                 MemDepResult::getClobber(Pred->getTerminator()),
1049                                 PredPtrVal);
1050         Result.push_back(Entry);
1051
1052         // Since we had a phi translation failure, the cache for CacheKey won't
1053         // include all of the entries that we need to immediately satisfy future
1054         // queries.  Mark this in NonLocalPointerDeps by setting the
1055         // BBSkipFirstBlockPair pointer to null.  This requires reuse of the
1056         // cached value to do more work but not miss the phi trans failure.
1057         NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1058         NLPI.Pair = BBSkipFirstBlockPair();
1059         continue;
1060       }
1061
1062       // FIXME: it is entirely possible that PHI translating will end up with
1063       // the same value.  Consider PHI translating something like:
1064       // X = phi [x, bb1], [y, bb2].  PHI translating for bb1 doesn't *need*
1065       // to recurse here, pedantically speaking.
1066       
1067       // If we have a problem phi translating, fall through to the code below
1068       // to handle the failure condition.
1069       if (getNonLocalPointerDepFromBB(PredPointer,
1070                                       Loc.getWithNewPtr(PredPointer.getAddr()),
1071                                       isLoad, Pred,
1072                                       Result, Visited))
1073         goto PredTranslationFailure;
1074     }
1075     
1076     // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1077     CacheInfo = &NonLocalPointerDeps[CacheKey];
1078     Cache = &CacheInfo->NonLocalDeps;
1079     NumSortedEntries = Cache->size();
1080     
1081     // Since we did phi translation, the "Cache" set won't contain all of the
1082     // results for the query.  This is ok (we can still use it to accelerate
1083     // specific block queries) but we can't do the fastpath "return all
1084     // results from the set"  Clear out the indicator for this.
1085     CacheInfo->Pair = BBSkipFirstBlockPair();
1086     SkipFirstBlock = false;
1087     continue;
1088
1089   PredTranslationFailure:
1090     
1091     if (Cache == 0) {
1092       // Refresh the CacheInfo/Cache pointer if it got invalidated.
1093       CacheInfo = &NonLocalPointerDeps[CacheKey];
1094       Cache = &CacheInfo->NonLocalDeps;
1095       NumSortedEntries = Cache->size();
1096     }
1097     
1098     // Since we failed phi translation, the "Cache" set won't contain all of the
1099     // results for the query.  This is ok (we can still use it to accelerate
1100     // specific block queries) but we can't do the fastpath "return all
1101     // results from the set".  Clear out the indicator for this.
1102     CacheInfo->Pair = BBSkipFirstBlockPair();
1103     
1104     // If *nothing* works, mark the pointer as being clobbered by the first
1105     // instruction in this block.
1106     //
1107     // If this is the magic first block, return this as a clobber of the whole
1108     // incoming value.  Since we can't phi translate to one of the predecessors,
1109     // we have to bail out.
1110     if (SkipFirstBlock)
1111       return true;
1112     
1113     for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
1114       assert(I != Cache->rend() && "Didn't find current block??");
1115       if (I->getBB() != BB)
1116         continue;
1117       
1118       assert(I->getResult().isNonLocal() &&
1119              "Should only be here with transparent block");
1120       I->setResult(MemDepResult::getClobber(BB->begin()));
1121       ReverseNonLocalPtrDeps[BB->begin()].insert(CacheKey);
1122       Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
1123                                          Pointer.getAddr()));
1124       break;
1125     }
1126   }
1127
1128   // Okay, we're done now.  If we added new values to the cache, re-sort it.
1129   SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1130   DEBUG(AssertSorted(*Cache));
1131   return false;
1132 }
1133
1134 /// RemoveCachedNonLocalPointerDependencies - If P exists in
1135 /// CachedNonLocalPointerInfo, remove it.
1136 void MemoryDependenceAnalysis::
1137 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
1138   CachedNonLocalPointerInfo::iterator It = 
1139     NonLocalPointerDeps.find(P);
1140   if (It == NonLocalPointerDeps.end()) return;
1141   
1142   // Remove all of the entries in the BB->val map.  This involves removing
1143   // instructions from the reverse map.
1144   NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1145   
1146   for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1147     Instruction *Target = PInfo[i].getResult().getInst();
1148     if (Target == 0) continue;  // Ignore non-local dep results.
1149     assert(Target->getParent() == PInfo[i].getBB());
1150     
1151     // Eliminating the dirty entry from 'Cache', so update the reverse info.
1152     RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1153   }
1154   
1155   // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1156   NonLocalPointerDeps.erase(It);
1157 }
1158
1159
1160 /// invalidateCachedPointerInfo - This method is used to invalidate cached
1161 /// information about the specified pointer, because it may be too
1162 /// conservative in memdep.  This is an optional call that can be used when
1163 /// the client detects an equivalence between the pointer and some other
1164 /// value and replaces the other value with ptr. This can make Ptr available
1165 /// in more places that cached info does not necessarily keep.
1166 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
1167   // If Ptr isn't really a pointer, just ignore it.
1168   if (!Ptr->getType()->isPointerTy()) return;
1169   // Flush store info for the pointer.
1170   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1171   // Flush load info for the pointer.
1172   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1173 }
1174
1175 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
1176 /// This needs to be done when the CFG changes, e.g., due to splitting
1177 /// critical edges.
1178 void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
1179   PredCache->clear();
1180 }
1181
1182 /// removeInstruction - Remove an instruction from the dependence analysis,
1183 /// updating the dependence of instructions that previously depended on it.
1184 /// This method attempts to keep the cache coherent using the reverse map.
1185 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
1186   // Walk through the Non-local dependencies, removing this one as the value
1187   // for any cached queries.
1188   NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1189   if (NLDI != NonLocalDeps.end()) {
1190     NonLocalDepInfo &BlockMap = NLDI->second.first;
1191     for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
1192          DI != DE; ++DI)
1193       if (Instruction *Inst = DI->getResult().getInst())
1194         RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1195     NonLocalDeps.erase(NLDI);
1196   }
1197
1198   // If we have a cached local dependence query for this instruction, remove it.
1199   //
1200   LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1201   if (LocalDepEntry != LocalDeps.end()) {
1202     // Remove us from DepInst's reverse set now that the local dep info is gone.
1203     if (Instruction *Inst = LocalDepEntry->second.getInst())
1204       RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1205
1206     // Remove this local dependency info.
1207     LocalDeps.erase(LocalDepEntry);
1208   }
1209   
1210   // If we have any cached pointer dependencies on this instruction, remove
1211   // them.  If the instruction has non-pointer type, then it can't be a pointer
1212   // base.
1213   
1214   // Remove it from both the load info and the store info.  The instruction
1215   // can't be in either of these maps if it is non-pointer.
1216   if (RemInst->getType()->isPointerTy()) {
1217     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1218     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1219   }
1220   
1221   // Loop over all of the things that depend on the instruction we're removing.
1222   // 
1223   SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
1224
1225   // If we find RemInst as a clobber or Def in any of the maps for other values,
1226   // we need to replace its entry with a dirty version of the instruction after
1227   // it.  If RemInst is a terminator, we use a null dirty value.
1228   //
1229   // Using a dirty version of the instruction after RemInst saves having to scan
1230   // the entire block to get to this point.
1231   MemDepResult NewDirtyVal;
1232   if (!RemInst->isTerminator())
1233     NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
1234   
1235   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1236   if (ReverseDepIt != ReverseLocalDeps.end()) {
1237     SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
1238     // RemInst can't be the terminator if it has local stuff depending on it.
1239     assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
1240            "Nothing can locally depend on a terminator");
1241     
1242     for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
1243          E = ReverseDeps.end(); I != E; ++I) {
1244       Instruction *InstDependingOnRemInst = *I;
1245       assert(InstDependingOnRemInst != RemInst &&
1246              "Already removed our local dep info");
1247                         
1248       LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1249       
1250       // Make sure to remember that new things depend on NewDepInst.
1251       assert(NewDirtyVal.getInst() && "There is no way something else can have "
1252              "a local dep on this if it is a terminator!");
1253       ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(), 
1254                                                 InstDependingOnRemInst));
1255     }
1256     
1257     ReverseLocalDeps.erase(ReverseDepIt);
1258
1259     // Add new reverse deps after scanning the set, to avoid invalidating the
1260     // 'ReverseDeps' reference.
1261     while (!ReverseDepsToAdd.empty()) {
1262       ReverseLocalDeps[ReverseDepsToAdd.back().first]
1263         .insert(ReverseDepsToAdd.back().second);
1264       ReverseDepsToAdd.pop_back();
1265     }
1266   }
1267   
1268   ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1269   if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1270     SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
1271     for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
1272          I != E; ++I) {
1273       assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
1274       
1275       PerInstNLInfo &INLD = NonLocalDeps[*I];
1276       // The information is now dirty!
1277       INLD.second = true;
1278       
1279       for (NonLocalDepInfo::iterator DI = INLD.first.begin(), 
1280            DE = INLD.first.end(); DI != DE; ++DI) {
1281         if (DI->getResult().getInst() != RemInst) continue;
1282         
1283         // Convert to a dirty entry for the subsequent instruction.
1284         DI->setResult(NewDirtyVal);
1285         
1286         if (Instruction *NextI = NewDirtyVal.getInst())
1287           ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
1288       }
1289     }
1290
1291     ReverseNonLocalDeps.erase(ReverseDepIt);
1292
1293     // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1294     while (!ReverseDepsToAdd.empty()) {
1295       ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
1296         .insert(ReverseDepsToAdd.back().second);
1297       ReverseDepsToAdd.pop_back();
1298     }
1299   }
1300   
1301   // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1302   // value in the NonLocalPointerDeps info.
1303   ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1304     ReverseNonLocalPtrDeps.find(RemInst);
1305   if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1306     SmallPtrSet<ValueIsLoadPair, 4> &Set = ReversePtrDepIt->second;
1307     SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
1308     
1309     for (SmallPtrSet<ValueIsLoadPair, 4>::iterator I = Set.begin(),
1310          E = Set.end(); I != E; ++I) {
1311       ValueIsLoadPair P = *I;
1312       assert(P.getPointer() != RemInst &&
1313              "Already removed NonLocalPointerDeps info for RemInst");
1314       
1315       NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1316       
1317       // The cache is not valid for any specific block anymore.
1318       NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1319       
1320       // Update any entries for RemInst to use the instruction after it.
1321       for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
1322            DI != DE; ++DI) {
1323         if (DI->getResult().getInst() != RemInst) continue;
1324         
1325         // Convert to a dirty entry for the subsequent instruction.
1326         DI->setResult(NewDirtyVal);
1327         
1328         if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1329           ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1330       }
1331       
1332       // Re-sort the NonLocalDepInfo.  Changing the dirty entry to its
1333       // subsequent value may invalidate the sortedness.
1334       std::sort(NLPDI.begin(), NLPDI.end());
1335     }
1336     
1337     ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1338     
1339     while (!ReversePtrDepsToAdd.empty()) {
1340       ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
1341         .insert(ReversePtrDepsToAdd.back().second);
1342       ReversePtrDepsToAdd.pop_back();
1343     }
1344   }
1345   
1346   
1347   assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1348   AA->deleteValue(RemInst);
1349   DEBUG(verifyRemoved(RemInst));
1350 }
1351 /// verifyRemoved - Verify that the specified instruction does not occur
1352 /// in our internal data structures.
1353 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
1354   for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
1355        E = LocalDeps.end(); I != E; ++I) {
1356     assert(I->first != D && "Inst occurs in data structures");
1357     assert(I->second.getInst() != D &&
1358            "Inst occurs in data structures");
1359   }
1360   
1361   for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
1362        E = NonLocalPointerDeps.end(); I != E; ++I) {
1363     assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
1364     const NonLocalDepInfo &Val = I->second.NonLocalDeps;
1365     for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
1366          II != E; ++II)
1367       assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
1368   }
1369   
1370   for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
1371        E = NonLocalDeps.end(); I != E; ++I) {
1372     assert(I->first != D && "Inst occurs in data structures");
1373     const PerInstNLInfo &INLD = I->second;
1374     for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
1375          EE = INLD.first.end(); II  != EE; ++II)
1376       assert(II->getResult().getInst() != D && "Inst occurs in data structures");
1377   }
1378   
1379   for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
1380        E = ReverseLocalDeps.end(); I != E; ++I) {
1381     assert(I->first != D && "Inst occurs in data structures");
1382     for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1383          EE = I->second.end(); II != EE; ++II)
1384       assert(*II != D && "Inst occurs in data structures");
1385   }
1386   
1387   for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
1388        E = ReverseNonLocalDeps.end();
1389        I != E; ++I) {
1390     assert(I->first != D && "Inst occurs in data structures");
1391     for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1392          EE = I->second.end(); II != EE; ++II)
1393       assert(*II != D && "Inst occurs in data structures");
1394   }
1395   
1396   for (ReverseNonLocalPtrDepTy::const_iterator
1397        I = ReverseNonLocalPtrDeps.begin(),
1398        E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
1399     assert(I->first != D && "Inst occurs in rev NLPD map");
1400     
1401     for (SmallPtrSet<ValueIsLoadPair, 4>::const_iterator II = I->second.begin(),
1402          E = I->second.end(); II != E; ++II)
1403       assert(*II != ValueIsLoadPair(D, false) &&
1404              *II != ValueIsLoadPair(D, true) &&
1405              "Inst occurs in ReverseNonLocalPtrDeps map");
1406   }
1407   
1408 }