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