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