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