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