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