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