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