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