1 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
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/AssumptionCache.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/MemoryBuiltins.h"
24 #include "llvm/Analysis/PHITransAddr.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/PredIteratorCache.h"
33 #include "llvm/Support/Debug.h"
36 #define DEBUG_TYPE "memdep"
38 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
39 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
40 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
42 STATISTIC(NumCacheNonLocalPtr,
43 "Number of fully cached non-local ptr responses");
44 STATISTIC(NumCacheDirtyNonLocalPtr,
45 "Number of cached, but dirty, non-local ptr responses");
46 STATISTIC(NumUncacheNonLocalPtr,
47 "Number of uncached non-local ptr responses");
48 STATISTIC(NumCacheCompleteNonLocalPtr,
49 "Number of block queries that were completely cached");
51 // Limit for the number of instructions to scan in a block.
52 static const unsigned int BlockScanLimit = 100;
54 // Limit on the number of memdep results to process.
55 static const unsigned int NumResultsLimit = 100;
57 char MemoryDependenceAnalysis::ID = 0;
59 // Register this pass...
60 INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep",
61 "Memory Dependence Analysis", false, true)
62 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
63 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
64 INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep",
65 "Memory Dependence Analysis", false, true)
67 MemoryDependenceAnalysis::MemoryDependenceAnalysis()
68 : FunctionPass(ID), PredCache() {
69 initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry());
71 MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
74 /// Clean up memory in between runs
75 void MemoryDependenceAnalysis::releaseMemory() {
78 NonLocalPointerDeps.clear();
79 ReverseLocalDeps.clear();
80 ReverseNonLocalDeps.clear();
81 ReverseNonLocalPtrDeps.clear();
85 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
87 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
89 AU.addRequired<AssumptionCacheTracker>();
90 AU.addRequiredTransitive<AliasAnalysis>();
93 bool MemoryDependenceAnalysis::runOnFunction(Function &F) {
94 AA = &getAnalysis<AliasAnalysis>();
95 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
96 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
97 DL = DLP ? &DLP->getDataLayout() : nullptr;
98 DominatorTreeWrapperPass *DTWP =
99 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
100 DT = DTWP ? &DTWP->getDomTree() : nullptr;
102 PredCache.reset(new PredIteratorCache());
106 /// RemoveFromReverseMap - This is a helper function that removes Val from
107 /// 'Inst's set in ReverseMap. If the set becomes empty, remove Inst's entry.
108 template <typename KeyTy>
109 static void RemoveFromReverseMap(DenseMap<Instruction*,
110 SmallPtrSet<KeyTy, 4> > &ReverseMap,
111 Instruction *Inst, KeyTy Val) {
112 typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator
113 InstIt = ReverseMap.find(Inst);
114 assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
115 bool Found = InstIt->second.erase(Val);
116 assert(Found && "Invalid reverse map!"); (void)Found;
117 if (InstIt->second.empty())
118 ReverseMap.erase(InstIt);
121 /// GetLocation - If the given instruction references a specific memory
122 /// location, fill in Loc with the details, otherwise set Loc.Ptr to null.
123 /// Return a ModRefInfo value describing the general behavior of the
126 AliasAnalysis::ModRefResult GetLocation(const Instruction *Inst,
127 AliasAnalysis::Location &Loc,
129 if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
130 if (LI->isUnordered()) {
131 Loc = AA->getLocation(LI);
132 return AliasAnalysis::Ref;
134 if (LI->getOrdering() == Monotonic) {
135 Loc = AA->getLocation(LI);
136 return AliasAnalysis::ModRef;
138 Loc = AliasAnalysis::Location();
139 return AliasAnalysis::ModRef;
142 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
143 if (SI->isUnordered()) {
144 Loc = AA->getLocation(SI);
145 return AliasAnalysis::Mod;
147 if (SI->getOrdering() == Monotonic) {
148 Loc = AA->getLocation(SI);
149 return AliasAnalysis::ModRef;
151 Loc = AliasAnalysis::Location();
152 return AliasAnalysis::ModRef;
155 if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
156 Loc = AA->getLocation(V);
157 return AliasAnalysis::ModRef;
160 if (const CallInst *CI = isFreeCall(Inst, AA->getTargetLibraryInfo())) {
161 // calls to free() deallocate the entire structure
162 Loc = AliasAnalysis::Location(CI->getArgOperand(0));
163 return AliasAnalysis::Mod;
166 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
169 switch (II->getIntrinsicID()) {
170 case Intrinsic::lifetime_start:
171 case Intrinsic::lifetime_end:
172 case Intrinsic::invariant_start:
173 II->getAAMetadata(AAInfo);
174 Loc = AliasAnalysis::Location(II->getArgOperand(1),
175 cast<ConstantInt>(II->getArgOperand(0))
176 ->getZExtValue(), AAInfo);
177 // These intrinsics don't really modify the memory, but returning Mod
178 // will allow them to be handled conservatively.
179 return AliasAnalysis::Mod;
180 case Intrinsic::invariant_end:
181 II->getAAMetadata(AAInfo);
182 Loc = AliasAnalysis::Location(II->getArgOperand(2),
183 cast<ConstantInt>(II->getArgOperand(1))
184 ->getZExtValue(), AAInfo);
185 // These intrinsics don't really modify the memory, but returning Mod
186 // will allow them to be handled conservatively.
187 return AliasAnalysis::Mod;
193 // Otherwise, just do the coarse-grained thing that always works.
194 if (Inst->mayWriteToMemory())
195 return AliasAnalysis::ModRef;
196 if (Inst->mayReadFromMemory())
197 return AliasAnalysis::Ref;
198 return AliasAnalysis::NoModRef;
201 /// getCallSiteDependencyFrom - Private helper for finding the local
202 /// dependencies of a call site.
203 MemDepResult MemoryDependenceAnalysis::
204 getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
205 BasicBlock::iterator ScanIt, BasicBlock *BB) {
206 unsigned Limit = BlockScanLimit;
208 // Walk backwards through the block, looking for dependencies
209 while (ScanIt != BB->begin()) {
210 // Limit the amount of scanning we do so we don't end up with quadratic
211 // running time on extreme testcases.
214 return MemDepResult::getUnknown();
216 Instruction *Inst = --ScanIt;
218 // If this inst is a memory op, get the pointer it accessed
219 AliasAnalysis::Location Loc;
220 AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA);
222 // A simple instruction.
223 if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef)
224 return MemDepResult::getClobber(Inst);
228 if (CallSite InstCS = cast<Value>(Inst)) {
229 // Debug intrinsics don't cause dependences.
230 if (isa<DbgInfoIntrinsic>(Inst)) continue;
231 // If these two calls do not interfere, look past it.
232 switch (AA->getModRefInfo(CS, InstCS)) {
233 case AliasAnalysis::NoModRef:
234 // If the two calls are the same, return InstCS as a Def, so that
235 // CS can be found redundant and eliminated.
236 if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) &&
237 CS.getInstruction()->isIdenticalToWhenDefined(Inst))
238 return MemDepResult::getDef(Inst);
240 // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
244 return MemDepResult::getClobber(Inst);
248 // If we could not obtain a pointer for the instruction and the instruction
249 // touches memory then assume that this is a dependency.
250 if (MR != AliasAnalysis::NoModRef)
251 return MemDepResult::getClobber(Inst);
254 // No dependence found. If this is the entry block of the function, it is
255 // unknown, otherwise it is non-local.
256 if (BB != &BB->getParent()->getEntryBlock())
257 return MemDepResult::getNonLocal();
258 return MemDepResult::getNonFuncLocal();
261 /// isLoadLoadClobberIfExtendedToFullWidth - Return true if LI is a load that
262 /// would fully overlap MemLoc if done as a wider legal integer load.
264 /// MemLocBase, MemLocOffset are lazily computed here the first time the
265 /// base/offs of memloc is needed.
267 isLoadLoadClobberIfExtendedToFullWidth(const AliasAnalysis::Location &MemLoc,
268 const Value *&MemLocBase,
271 const DataLayout *DL) {
272 // If we have no target data, we can't do this.
273 if (!DL) return false;
275 // If we haven't already computed the base/offset of MemLoc, do so now.
277 MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, DL);
279 unsigned Size = MemoryDependenceAnalysis::
280 getLoadLoadClobberFullWidthSize(MemLocBase, MemLocOffs, MemLoc.Size,
285 /// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that
286 /// looks at a memory location for a load (specified by MemLocBase, Offs,
287 /// and Size) and compares it against a load. If the specified load could
288 /// be safely widened to a larger integer load that is 1) still efficient,
289 /// 2) safe for the target, and 3) would provide the specified memory
290 /// location value, then this function returns the size in bytes of the
291 /// load width to use. If not, this returns zero.
292 unsigned MemoryDependenceAnalysis::
293 getLoadLoadClobberFullWidthSize(const Value *MemLocBase, int64_t MemLocOffs,
294 unsigned MemLocSize, const LoadInst *LI,
295 const DataLayout &DL) {
296 // We can only extend simple integer loads.
297 if (!isa<IntegerType>(LI->getType()) || !LI->isSimple()) return 0;
299 // Load widening is hostile to ThreadSanitizer: it may cause false positives
300 // or make the reports more cryptic (access sizes are wrong).
301 if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
304 // Get the base of this load.
306 const Value *LIBase =
307 GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, &DL);
309 // If the two pointers are not based on the same pointer, we can't tell that
311 if (LIBase != MemLocBase) return 0;
313 // Okay, the two values are based on the same pointer, but returned as
314 // no-alias. This happens when we have things like two byte loads at "P+1"
315 // and "P+3". Check to see if increasing the size of the "LI" load up to its
316 // alignment (or the largest native integer type) will allow us to load all
317 // the bits required by MemLoc.
319 // If MemLoc is before LI, then no widening of LI will help us out.
320 if (MemLocOffs < LIOffs) return 0;
322 // Get the alignment of the load in bytes. We assume that it is safe to load
323 // any legal integer up to this size without a problem. For example, if we're
324 // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
325 // widen it up to an i32 load. If it is known 2-byte aligned, we can widen it
327 unsigned LoadAlign = LI->getAlignment();
329 int64_t MemLocEnd = MemLocOffs+MemLocSize;
331 // If no amount of rounding up will let MemLoc fit into LI, then bail out.
332 if (LIOffs+LoadAlign < MemLocEnd) return 0;
334 // This is the size of the load to try. Start with the next larger power of
336 unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits()/8U;
337 NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
340 // If this load size is bigger than our known alignment or would not fit
341 // into a native integer register, then we fail.
342 if (NewLoadByteSize > LoadAlign ||
343 !DL.fitsInLegalInteger(NewLoadByteSize*8))
346 if (LIOffs + NewLoadByteSize > MemLocEnd &&
347 LI->getParent()->getParent()->hasFnAttribute(
348 Attribute::SanitizeAddress))
349 // We will be reading past the location accessed by the original program.
350 // While this is safe in a regular build, Address Safety analysis tools
351 // may start reporting false warnings. So, don't do widening.
354 // If a load of this width would include all of MemLoc, then we succeed.
355 if (LIOffs+NewLoadByteSize >= MemLocEnd)
356 return NewLoadByteSize;
358 NewLoadByteSize <<= 1;
362 static bool isVolatile(Instruction *Inst) {
363 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
364 return LI->isVolatile();
365 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
366 return SI->isVolatile();
367 else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst))
368 return AI->isVolatile();
373 /// getPointerDependencyFrom - Return the instruction on which a memory
374 /// location depends. If isLoad is true, this routine ignores may-aliases with
375 /// read-only operations. If isLoad is false, this routine ignores may-aliases
376 /// with reads from read-only locations. If possible, pass the query
377 /// instruction as well; this function may take advantage of the metadata
378 /// annotated to the query instruction to refine the result.
379 MemDepResult MemoryDependenceAnalysis::
380 getPointerDependencyFrom(const AliasAnalysis::Location &MemLoc, bool isLoad,
381 BasicBlock::iterator ScanIt, BasicBlock *BB,
382 Instruction *QueryInst) {
384 const Value *MemLocBase = nullptr;
385 int64_t MemLocOffset = 0;
386 unsigned Limit = BlockScanLimit;
387 bool isInvariantLoad = false;
389 // We must be careful with atomic accesses, as they may allow another thread
390 // to touch this location, cloberring it. We are conservative: if the
391 // QueryInst is not a simple (non-atomic) memory access, we automatically
392 // return getClobber.
393 // If it is simple, we know based on the results of
394 // "Compiler testing via a theory of sound optimisations in the C11/C++11
395 // memory model" in PLDI 2013, that a non-atomic location can only be
396 // clobbered between a pair of a release and an acquire action, with no
397 // access to the location in between.
398 // Here is an example for giving the general intuition behind this rule.
399 // In the following code:
401 // release action; [1]
402 // acquire action; [4]
404 // It is unsafe to replace %val by 0 because another thread may be running:
405 // acquire action; [2]
407 // release action; [3]
408 // with synchronization from 1 to 2 and from 3 to 4, resulting in %val
409 // being 42. A key property of this program however is that if either
410 // 1 or 4 were missing, there would be a race between the store of 42
411 // either the store of 0 or the load (making the whole progam racy).
412 // The paper mentionned above shows that the same property is respected
413 // by every program that can detect any optimisation of that kind: either
414 // it is racy (undefined) or there is a release followed by an acquire
415 // between the pair of accesses under consideration.
416 bool HasSeenAcquire = false;
418 if (isLoad && QueryInst) {
419 LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
420 if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr)
421 isInvariantLoad = true;
424 // Walk backwards through the basic block, looking for dependencies.
425 while (ScanIt != BB->begin()) {
426 Instruction *Inst = --ScanIt;
428 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
429 // Debug intrinsics don't (and can't) cause dependencies.
430 if (isa<DbgInfoIntrinsic>(II)) continue;
432 // Limit the amount of scanning we do so we don't end up with quadratic
433 // running time on extreme testcases.
436 return MemDepResult::getUnknown();
438 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
439 // If we reach a lifetime begin or end marker, then the query ends here
440 // because the value is undefined.
441 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
442 // FIXME: This only considers queries directly on the invariant-tagged
443 // pointer, not on query pointers that are indexed off of them. It'd
444 // be nice to handle that at some point (the right approach is to use
445 // GetPointerBaseWithConstantOffset).
446 if (AA->isMustAlias(AliasAnalysis::Location(II->getArgOperand(1)),
448 return MemDepResult::getDef(II);
453 // Values depend on loads if the pointers are must aliased. This means that
454 // a load depends on another must aliased load from the same value.
455 // One exception is atomic loads: a value can depend on an atomic load that it
456 // does not alias with when this atomic load indicates that another thread may
457 // be accessing the location.
458 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
460 // While volatile access cannot be eliminated, they do not have to clobber
461 // non-aliasing locations, as normal accesses, for example, can be safely
462 // reordered with volatile accesses.
463 if (LI->isVolatile()) {
465 // Original QueryInst *may* be volatile
466 return MemDepResult::getClobber(LI);
467 if (isVolatile(QueryInst))
468 // Ordering required if QueryInst is itself volatile
469 return MemDepResult::getClobber(LI);
470 // Otherwise, volatile doesn't imply any special ordering
473 // Atomic loads have complications involved.
474 // A Monotonic (or higher) load is OK if the query inst is itself not atomic.
475 // An Acquire (or higher) load sets the HasSeenAcquire flag, so that any
476 // release store will know to return getClobber.
477 // FIXME: This is overly conservative.
478 if (LI->isAtomic() && LI->getOrdering() > Unordered) {
480 return MemDepResult::getClobber(LI);
481 if (auto *QueryLI = dyn_cast<LoadInst>(QueryInst)) {
482 if (!QueryLI->isSimple())
483 return MemDepResult::getClobber(LI);
484 } else if (auto *QuerySI = dyn_cast<StoreInst>(QueryInst)) {
485 if (!QuerySI->isSimple())
486 return MemDepResult::getClobber(LI);
487 } else if (QueryInst->mayReadOrWriteMemory()) {
488 return MemDepResult::getClobber(LI);
491 if (isAtLeastAcquire(LI->getOrdering()))
492 HasSeenAcquire = true;
495 AliasAnalysis::Location LoadLoc = AA->getLocation(LI);
497 // If we found a pointer, check if it could be the same as our pointer.
498 AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc);
501 if (R == AliasAnalysis::NoAlias) {
502 // If this is an over-aligned integer load (for example,
503 // "load i8* %P, align 4") see if it would obviously overlap with the
504 // queried location if widened to a larger load (e.g. if the queried
505 // location is 1 byte at P+1). If so, return it as a load/load
506 // clobber result, allowing the client to decide to widen the load if
508 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType()))
509 if (LI->getAlignment()*8 > ITy->getPrimitiveSizeInBits() &&
510 isLoadLoadClobberIfExtendedToFullWidth(MemLoc, MemLocBase,
511 MemLocOffset, LI, DL))
512 return MemDepResult::getClobber(Inst);
517 // Must aliased loads are defs of each other.
518 if (R == AliasAnalysis::MustAlias)
519 return MemDepResult::getDef(Inst);
521 #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads
522 // in terms of clobbering loads, but since it does this by looking
523 // at the clobbering load directly, it doesn't know about any
524 // phi translation that may have happened along the way.
526 // If we have a partial alias, then return this as a clobber for the
528 if (R == AliasAnalysis::PartialAlias)
529 return MemDepResult::getClobber(Inst);
532 // Random may-alias loads don't depend on each other without a
537 // Stores don't depend on other no-aliased accesses.
538 if (R == AliasAnalysis::NoAlias)
541 // Stores don't alias loads from read-only memory.
542 if (AA->pointsToConstantMemory(LoadLoc))
545 // Stores depend on may/must aliased loads.
546 return MemDepResult::getDef(Inst);
549 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
550 // Atomic stores have complications involved.
551 // A Monotonic store is OK if the query inst is itself not atomic.
552 // A Release (or higher) store further requires that no acquire load
554 // FIXME: This is overly conservative.
555 if (!SI->isUnordered()) {
557 return MemDepResult::getClobber(SI);
558 if (auto *QueryLI = dyn_cast<LoadInst>(QueryInst)) {
559 if (!QueryLI->isSimple())
560 return MemDepResult::getClobber(SI);
561 } else if (auto *QuerySI = dyn_cast<StoreInst>(QueryInst)) {
562 if (!QuerySI->isSimple())
563 return MemDepResult::getClobber(SI);
564 } else if (QueryInst->mayReadOrWriteMemory()) {
565 return MemDepResult::getClobber(SI);
568 if (HasSeenAcquire && isAtLeastRelease(SI->getOrdering()))
569 return MemDepResult::getClobber(SI);
572 // FIXME: this is overly conservative.
573 // While volatile access cannot be eliminated, they do not have to clobber
574 // non-aliasing locations, as normal accesses can for example be reordered
575 // with volatile accesses.
576 if (SI->isVolatile())
577 return MemDepResult::getClobber(SI);
579 // If alias analysis can tell that this store is guaranteed to not modify
580 // the query pointer, ignore it. Use getModRefInfo to handle cases where
581 // the query pointer points to constant memory etc.
582 if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
585 // Ok, this store might clobber the query pointer. Check to see if it is
586 // a must alias: in this case, we want to return this as a def.
587 AliasAnalysis::Location StoreLoc = AA->getLocation(SI);
589 // If we found a pointer, check if it could be the same as our pointer.
590 AliasAnalysis::AliasResult R = AA->alias(StoreLoc, MemLoc);
592 if (R == AliasAnalysis::NoAlias)
594 if (R == AliasAnalysis::MustAlias)
595 return MemDepResult::getDef(Inst);
598 return MemDepResult::getClobber(Inst);
601 // If this is an allocation, and if we know that the accessed pointer is to
602 // the allocation, return Def. This means that there is no dependence and
603 // the access can be optimized based on that. For example, a load could
605 // Note: Only determine this to be a malloc if Inst is the malloc call, not
606 // a subsequent bitcast of the malloc call result. There can be stores to
607 // the malloced memory between the malloc call and its bitcast uses, and we
608 // need to continue scanning until the malloc call.
609 const TargetLibraryInfo *TLI = AA->getTargetLibraryInfo();
610 if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, TLI)) {
611 const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL);
613 if (AccessPtr == Inst || AA->isMustAlias(Inst, AccessPtr))
614 return MemDepResult::getDef(Inst);
615 // Be conservative if the accessed pointer may alias the allocation.
616 if (AA->alias(Inst, AccessPtr) != AliasAnalysis::NoAlias)
617 return MemDepResult::getClobber(Inst);
618 // If the allocation is not aliased and does not read memory (like
619 // strdup), it is safe to ignore.
620 if (isa<AllocaInst>(Inst) ||
621 isMallocLikeFn(Inst, TLI) || isCallocLikeFn(Inst, TLI))
625 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
626 AliasAnalysis::ModRefResult MR = AA->getModRefInfo(Inst, MemLoc);
627 // If necessary, perform additional analysis.
628 if (MR == AliasAnalysis::ModRef)
629 MR = AA->callCapturesBefore(Inst, MemLoc, DT);
631 case AliasAnalysis::NoModRef:
632 // If the call has no effect on the queried pointer, just ignore it.
634 case AliasAnalysis::Mod:
635 return MemDepResult::getClobber(Inst);
636 case AliasAnalysis::Ref:
637 // If the call is known to never store to the pointer, and if this is a
638 // load query, we can safely ignore it (scan past it).
642 // Otherwise, there is a potential dependence. Return a clobber.
643 return MemDepResult::getClobber(Inst);
647 // No dependence found. If this is the entry block of the function, it is
648 // unknown, otherwise it is non-local.
649 if (BB != &BB->getParent()->getEntryBlock())
650 return MemDepResult::getNonLocal();
651 return MemDepResult::getNonFuncLocal();
654 /// getDependency - Return the instruction on which a memory operation
656 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
657 Instruction *ScanPos = QueryInst;
659 // Check for a cached result
660 MemDepResult &LocalCache = LocalDeps[QueryInst];
662 // If the cached entry is non-dirty, just return it. Note that this depends
663 // on MemDepResult's default constructing to 'dirty'.
664 if (!LocalCache.isDirty())
667 // Otherwise, if we have a dirty entry, we know we can start the scan at that
668 // instruction, which may save us some work.
669 if (Instruction *Inst = LocalCache.getInst()) {
672 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
675 BasicBlock *QueryParent = QueryInst->getParent();
678 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
679 // No dependence found. If this is the entry block of the function, it is
680 // unknown, otherwise it is non-local.
681 if (QueryParent != &QueryParent->getParent()->getEntryBlock())
682 LocalCache = MemDepResult::getNonLocal();
684 LocalCache = MemDepResult::getNonFuncLocal();
686 AliasAnalysis::Location MemLoc;
687 AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
689 // If we can do a pointer scan, make it happen.
690 bool isLoad = !(MR & AliasAnalysis::Mod);
691 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
692 isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
694 LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
695 QueryParent, QueryInst);
696 } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
697 CallSite QueryCS(QueryInst);
698 bool isReadOnly = AA->onlyReadsMemory(QueryCS);
699 LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
702 // Non-memory instruction.
703 LocalCache = MemDepResult::getUnknown();
706 // Remember the result!
707 if (Instruction *I = LocalCache.getInst())
708 ReverseLocalDeps[I].insert(QueryInst);
714 /// AssertSorted - This method is used when -debug is specified to verify that
715 /// cache arrays are properly kept sorted.
716 static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
718 if (Count == -1) Count = Cache.size();
719 if (Count == 0) return;
721 for (unsigned i = 1; i != unsigned(Count); ++i)
722 assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
726 /// getNonLocalCallDependency - Perform a full dependency query for the
727 /// specified call, returning the set of blocks that the value is
728 /// potentially live across. The returned set of results will include a
729 /// "NonLocal" result for all blocks where the value is live across.
731 /// This method assumes the instruction returns a "NonLocal" dependency
732 /// within its own block.
734 /// This returns a reference to an internal data structure that may be
735 /// invalidated on the next non-local query or when an instruction is
736 /// removed. Clients must copy this data if they want it around longer than
738 const MemoryDependenceAnalysis::NonLocalDepInfo &
739 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
740 assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
741 "getNonLocalCallDependency should only be used on calls with non-local deps!");
742 PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
743 NonLocalDepInfo &Cache = CacheP.first;
745 /// DirtyBlocks - This is the set of blocks that need to be recomputed. In
746 /// the cached case, this can happen due to instructions being deleted etc. In
747 /// the uncached case, this starts out as the set of predecessors we care
749 SmallVector<BasicBlock*, 32> DirtyBlocks;
751 if (!Cache.empty()) {
752 // Okay, we have a cache entry. If we know it is not dirty, just return it
753 // with no computation.
754 if (!CacheP.second) {
759 // If we already have a partially computed set of results, scan them to
760 // determine what is dirty, seeding our initial DirtyBlocks worklist.
761 for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
763 if (I->getResult().isDirty())
764 DirtyBlocks.push_back(I->getBB());
766 // Sort the cache so that we can do fast binary search lookups below.
767 std::sort(Cache.begin(), Cache.end());
769 ++NumCacheDirtyNonLocal;
770 //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
771 // << Cache.size() << " cached: " << *QueryInst;
773 // Seed DirtyBlocks with each of the preds of QueryInst's block.
774 BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
775 for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
776 DirtyBlocks.push_back(*PI);
777 ++NumUncacheNonLocal;
780 // isReadonlyCall - If this is a read-only call, we can be more aggressive.
781 bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
783 SmallPtrSet<BasicBlock*, 64> Visited;
785 unsigned NumSortedEntries = Cache.size();
786 DEBUG(AssertSorted(Cache));
788 // Iterate while we still have blocks to update.
789 while (!DirtyBlocks.empty()) {
790 BasicBlock *DirtyBB = DirtyBlocks.back();
791 DirtyBlocks.pop_back();
793 // Already processed this block?
794 if (!Visited.insert(DirtyBB).second)
797 // Do a binary search to see if we already have an entry for this block in
798 // the cache set. If so, find it.
799 DEBUG(AssertSorted(Cache, NumSortedEntries));
800 NonLocalDepInfo::iterator Entry =
801 std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
802 NonLocalDepEntry(DirtyBB));
803 if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
806 NonLocalDepEntry *ExistingResult = nullptr;
807 if (Entry != Cache.begin()+NumSortedEntries &&
808 Entry->getBB() == DirtyBB) {
809 // If we already have an entry, and if it isn't already dirty, the block
811 if (!Entry->getResult().isDirty())
814 // Otherwise, remember this slot so we can update the value.
815 ExistingResult = &*Entry;
818 // If the dirty entry has a pointer, start scanning from it so we don't have
819 // to rescan the entire block.
820 BasicBlock::iterator ScanPos = DirtyBB->end();
821 if (ExistingResult) {
822 if (Instruction *Inst = ExistingResult->getResult().getInst()) {
824 // We're removing QueryInst's use of Inst.
825 RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
826 QueryCS.getInstruction());
830 // Find out if this block has a local dependency for QueryInst.
833 if (ScanPos != DirtyBB->begin()) {
834 Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
835 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
836 // No dependence found. If this is the entry block of the function, it is
837 // a clobber, otherwise it is unknown.
838 Dep = MemDepResult::getNonLocal();
840 Dep = MemDepResult::getNonFuncLocal();
843 // If we had a dirty entry for the block, update it. Otherwise, just add
846 ExistingResult->setResult(Dep);
848 Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
850 // If the block has a dependency (i.e. it isn't completely transparent to
851 // the value), remember the association!
852 if (!Dep.isNonLocal()) {
853 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
854 // update this when we remove instructions.
855 if (Instruction *Inst = Dep.getInst())
856 ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
859 // If the block *is* completely transparent to the load, we need to check
860 // the predecessors of this block. Add them to our worklist.
861 for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
862 DirtyBlocks.push_back(*PI);
869 /// getNonLocalPointerDependency - Perform a full dependency query for an
870 /// access to the specified (non-volatile) memory location, returning the
871 /// set of instructions that either define or clobber the value.
873 /// This method assumes the pointer has a "NonLocal" dependency within its
876 void MemoryDependenceAnalysis::
877 getNonLocalPointerDependency(Instruction *QueryInst,
878 SmallVectorImpl<NonLocalDepResult> &Result) {
880 auto getLocation = [](AliasAnalysis *AA, Instruction *Inst) {
881 if (auto *I = dyn_cast<LoadInst>(Inst))
882 return AA->getLocation(I);
883 else if (auto *I = dyn_cast<StoreInst>(Inst))
884 return AA->getLocation(I);
885 else if (auto *I = dyn_cast<VAArgInst>(Inst))
886 return AA->getLocation(I);
887 else if (auto *I = dyn_cast<AtomicCmpXchgInst>(Inst))
888 return AA->getLocation(I);
889 else if (auto *I = dyn_cast<AtomicRMWInst>(Inst))
890 return AA->getLocation(I);
892 llvm_unreachable("unsupported memory instruction");
895 const AliasAnalysis::Location Loc = getLocation(AA, QueryInst);
896 bool isLoad = isa<LoadInst>(QueryInst);
897 BasicBlock *FromBB = QueryInst->getParent();
900 assert(Loc.Ptr->getType()->isPointerTy() &&
901 "Can't get pointer deps of a non-pointer!");
904 // This routine does not expect to deal with volatile instructions.
905 // Doing so would require piping through the QueryInst all the way through.
906 // TODO: volatiles can't be elided, but they can be reordered with other
907 // non-volatile accesses.
909 // We currently give up on any instruction which is ordered, but we do handle
910 // atomic instructions which are unordered.
911 // TODO: Handle ordered instructions
912 auto isOrdered = [](Instruction *Inst) {
913 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
914 return !LI->isUnordered();
915 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
916 return !SI->isUnordered();
920 if (isVolatile(QueryInst) || isOrdered(QueryInst)) {
921 Result.push_back(NonLocalDepResult(FromBB,
922 MemDepResult::getUnknown(),
923 const_cast<Value *>(Loc.Ptr)));
928 PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, AC);
930 // This is the set of blocks we've inspected, and the pointer we consider in
931 // each block. Because of critical edges, we currently bail out if querying
932 // a block with multiple different pointers. This can happen during PHI
934 DenseMap<BasicBlock*, Value*> Visited;
935 if (!getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
936 Result, Visited, true))
939 Result.push_back(NonLocalDepResult(FromBB,
940 MemDepResult::getUnknown(),
941 const_cast<Value *>(Loc.Ptr)));
944 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
945 /// Pointer/PointeeSize using either cached information in Cache or by doing a
946 /// lookup (which may use dirty cache info if available). If we do a lookup,
947 /// add the result to the cache.
948 MemDepResult MemoryDependenceAnalysis::
949 GetNonLocalInfoForBlock(Instruction *QueryInst,
950 const AliasAnalysis::Location &Loc,
951 bool isLoad, BasicBlock *BB,
952 NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
954 // Do a binary search to see if we already have an entry for this block in
955 // the cache set. If so, find it.
956 NonLocalDepInfo::iterator Entry =
957 std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
958 NonLocalDepEntry(BB));
959 if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
962 NonLocalDepEntry *ExistingResult = nullptr;
963 if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
964 ExistingResult = &*Entry;
966 // If we have a cached entry, and it is non-dirty, use it as the value for
968 if (ExistingResult && !ExistingResult->getResult().isDirty()) {
969 ++NumCacheNonLocalPtr;
970 return ExistingResult->getResult();
973 // Otherwise, we have to scan for the value. If we have a dirty cache
974 // entry, start scanning from its position, otherwise we scan from the end
976 BasicBlock::iterator ScanPos = BB->end();
977 if (ExistingResult && ExistingResult->getResult().getInst()) {
978 assert(ExistingResult->getResult().getInst()->getParent() == BB &&
979 "Instruction invalidated?");
980 ++NumCacheDirtyNonLocalPtr;
981 ScanPos = ExistingResult->getResult().getInst();
983 // Eliminating the dirty entry from 'Cache', so update the reverse info.
984 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
985 RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
987 ++NumUncacheNonLocalPtr;
990 // Scan the block for the dependency.
991 MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB,
994 // If we had a dirty entry for the block, update it. Otherwise, just add
997 ExistingResult->setResult(Dep);
999 Cache->push_back(NonLocalDepEntry(BB, Dep));
1001 // If the block has a dependency (i.e. it isn't completely transparent to
1002 // the value), remember the reverse association because we just added it
1004 if (!Dep.isDef() && !Dep.isClobber())
1007 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
1008 // update MemDep when we remove instructions.
1009 Instruction *Inst = Dep.getInst();
1010 assert(Inst && "Didn't depend on anything?");
1011 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
1012 ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
1016 /// SortNonLocalDepInfoCache - Sort the NonLocalDepInfo cache, given a certain
1017 /// number of elements in the array that are already properly ordered. This is
1018 /// optimized for the case when only a few entries are added.
1020 SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
1021 unsigned NumSortedEntries) {
1022 switch (Cache.size() - NumSortedEntries) {
1024 // done, no new entries.
1027 // Two new entries, insert the last one into place.
1028 NonLocalDepEntry Val = Cache.back();
1030 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
1031 std::upper_bound(Cache.begin(), Cache.end()-1, Val);
1032 Cache.insert(Entry, Val);
1036 // One new entry, Just insert the new value at the appropriate position.
1037 if (Cache.size() != 1) {
1038 NonLocalDepEntry Val = Cache.back();
1040 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
1041 std::upper_bound(Cache.begin(), Cache.end(), Val);
1042 Cache.insert(Entry, Val);
1046 // Added many values, do a full scale sort.
1047 std::sort(Cache.begin(), Cache.end());
1052 /// getNonLocalPointerDepFromBB - Perform a dependency query based on
1053 /// pointer/pointeesize starting at the end of StartBB. Add any clobber/def
1054 /// results to the results vector and keep track of which blocks are visited in
1057 /// This has special behavior for the first block queries (when SkipFirstBlock
1058 /// is true). In this special case, it ignores the contents of the specified
1059 /// block and starts returning dependence info for its predecessors.
1061 /// This function returns false on success, or true to indicate that it could
1062 /// not compute dependence information for some reason. This should be treated
1063 /// as a clobber dependence on the first instruction in the predecessor block.
1064 bool MemoryDependenceAnalysis::
1065 getNonLocalPointerDepFromBB(Instruction *QueryInst,
1066 const PHITransAddr &Pointer,
1067 const AliasAnalysis::Location &Loc,
1068 bool isLoad, BasicBlock *StartBB,
1069 SmallVectorImpl<NonLocalDepResult> &Result,
1070 DenseMap<BasicBlock*, Value*> &Visited,
1071 bool SkipFirstBlock) {
1072 // Look up the cached info for Pointer.
1073 ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
1075 // Set up a temporary NLPI value. If the map doesn't yet have an entry for
1076 // CacheKey, this value will be inserted as the associated value. Otherwise,
1077 // it'll be ignored, and we'll have to check to see if the cached size and
1078 // aa tags are consistent with the current query.
1079 NonLocalPointerInfo InitialNLPI;
1080 InitialNLPI.Size = Loc.Size;
1081 InitialNLPI.AATags = Loc.AATags;
1083 // Get the NLPI for CacheKey, inserting one into the map if it doesn't
1084 // already have one.
1085 std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
1086 NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
1087 NonLocalPointerInfo *CacheInfo = &Pair.first->second;
1089 // If we already have a cache entry for this CacheKey, we may need to do some
1090 // work to reconcile the cache entry and the current query.
1092 if (CacheInfo->Size < Loc.Size) {
1093 // The query's Size is greater than the cached one. Throw out the
1094 // cached data and proceed with the query at the greater size.
1095 CacheInfo->Pair = BBSkipFirstBlockPair();
1096 CacheInfo->Size = Loc.Size;
1097 for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
1098 DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
1099 if (Instruction *Inst = DI->getResult().getInst())
1100 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1101 CacheInfo->NonLocalDeps.clear();
1102 } else if (CacheInfo->Size > Loc.Size) {
1103 // This query's Size is less than the cached one. Conservatively restart
1104 // the query using the greater size.
1105 return getNonLocalPointerDepFromBB(QueryInst, Pointer,
1106 Loc.getWithNewSize(CacheInfo->Size),
1107 isLoad, StartBB, Result, Visited,
1111 // If the query's AATags are inconsistent with the cached one,
1112 // conservatively throw out the cached data and restart the query with
1113 // no tag if needed.
1114 if (CacheInfo->AATags != Loc.AATags) {
1115 if (CacheInfo->AATags) {
1116 CacheInfo->Pair = BBSkipFirstBlockPair();
1117 CacheInfo->AATags = AAMDNodes();
1118 for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
1119 DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
1120 if (Instruction *Inst = DI->getResult().getInst())
1121 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1122 CacheInfo->NonLocalDeps.clear();
1125 return getNonLocalPointerDepFromBB(QueryInst,
1126 Pointer, Loc.getWithoutAATags(),
1127 isLoad, StartBB, Result, Visited,
1132 NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
1134 // If we have valid cached information for exactly the block we are
1135 // investigating, just return it with no recomputation.
1136 if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
1137 // We have a fully cached result for this query then we can just return the
1138 // cached results and populate the visited set. However, we have to verify
1139 // that we don't already have conflicting results for these blocks. Check
1140 // to ensure that if a block in the results set is in the visited set that
1141 // it was for the same pointer query.
1142 if (!Visited.empty()) {
1143 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
1145 DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
1146 if (VI == Visited.end() || VI->second == Pointer.getAddr())
1149 // We have a pointer mismatch in a block. Just return clobber, saying
1150 // that something was clobbered in this result. We could also do a
1151 // non-fully cached query, but there is little point in doing this.
1156 Value *Addr = Pointer.getAddr();
1157 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
1159 Visited.insert(std::make_pair(I->getBB(), Addr));
1160 if (I->getResult().isNonLocal()) {
1165 Result.push_back(NonLocalDepResult(I->getBB(),
1166 MemDepResult::getUnknown(),
1168 } else if (DT->isReachableFromEntry(I->getBB())) {
1169 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
1172 ++NumCacheCompleteNonLocalPtr;
1176 // Otherwise, either this is a new block, a block with an invalid cache
1177 // pointer or one that we're about to invalidate by putting more info into it
1178 // than its valid cache info. If empty, the result will be valid cache info,
1179 // otherwise it isn't.
1181 CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
1183 CacheInfo->Pair = BBSkipFirstBlockPair();
1185 SmallVector<BasicBlock*, 32> Worklist;
1186 Worklist.push_back(StartBB);
1188 // PredList used inside loop.
1189 SmallVector<std::pair<BasicBlock*, PHITransAddr>, 16> PredList;
1191 // Keep track of the entries that we know are sorted. Previously cached
1192 // entries will all be sorted. The entries we add we only sort on demand (we
1193 // don't insert every element into its sorted position). We know that we
1194 // won't get any reuse from currently inserted values, because we don't
1195 // revisit blocks after we insert info for them.
1196 unsigned NumSortedEntries = Cache->size();
1197 DEBUG(AssertSorted(*Cache));
1199 while (!Worklist.empty()) {
1200 BasicBlock *BB = Worklist.pop_back_val();
1202 // If we do process a large number of blocks it becomes very expensive and
1203 // likely it isn't worth worrying about
1204 if (Result.size() > NumResultsLimit) {
1206 // Sort it now (if needed) so that recursive invocations of
1207 // getNonLocalPointerDepFromBB and other routines that could reuse the
1208 // cache value will only see properly sorted cache arrays.
1209 if (Cache && NumSortedEntries != Cache->size()) {
1210 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1212 // Since we bail out, the "Cache" set won't contain all of the
1213 // results for the query. This is ok (we can still use it to accelerate
1214 // specific block queries) but we can't do the fastpath "return all
1215 // results from the set". Clear out the indicator for this.
1216 CacheInfo->Pair = BBSkipFirstBlockPair();
1220 // Skip the first block if we have it.
1221 if (!SkipFirstBlock) {
1222 // Analyze the dependency of *Pointer in FromBB. See if we already have
1224 assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
1226 // Get the dependency info for Pointer in BB. If we have cached
1227 // information, we will use it, otherwise we compute it.
1228 DEBUG(AssertSorted(*Cache, NumSortedEntries));
1229 MemDepResult Dep = GetNonLocalInfoForBlock(QueryInst,
1230 Loc, isLoad, BB, Cache,
1233 // If we got a Def or Clobber, add this to the list of results.
1234 if (!Dep.isNonLocal()) {
1236 Result.push_back(NonLocalDepResult(BB,
1237 MemDepResult::getUnknown(),
1238 Pointer.getAddr()));
1240 } else if (DT->isReachableFromEntry(BB)) {
1241 Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
1247 // If 'Pointer' is an instruction defined in this block, then we need to do
1248 // phi translation to change it into a value live in the predecessor block.
1249 // If not, we just add the predecessors to the worklist and scan them with
1250 // the same Pointer.
1251 if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
1252 SkipFirstBlock = false;
1253 SmallVector<BasicBlock*, 16> NewBlocks;
1254 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
1255 // Verify that we haven't looked at this block yet.
1256 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
1257 InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr()));
1258 if (InsertRes.second) {
1259 // First time we've looked at *PI.
1260 NewBlocks.push_back(*PI);
1264 // If we have seen this block before, but it was with a different
1265 // pointer then we have a phi translation failure and we have to treat
1266 // this as a clobber.
1267 if (InsertRes.first->second != Pointer.getAddr()) {
1268 // Make sure to clean up the Visited map before continuing on to
1269 // PredTranslationFailure.
1270 for (unsigned i = 0; i < NewBlocks.size(); i++)
1271 Visited.erase(NewBlocks[i]);
1272 goto PredTranslationFailure;
1275 Worklist.append(NewBlocks.begin(), NewBlocks.end());
1279 // We do need to do phi translation, if we know ahead of time we can't phi
1280 // translate this value, don't even try.
1281 if (!Pointer.IsPotentiallyPHITranslatable())
1282 goto PredTranslationFailure;
1284 // We may have added values to the cache list before this PHI translation.
1285 // If so, we haven't done anything to ensure that the cache remains sorted.
1286 // Sort it now (if needed) so that recursive invocations of
1287 // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1288 // value will only see properly sorted cache arrays.
1289 if (Cache && NumSortedEntries != Cache->size()) {
1290 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1291 NumSortedEntries = Cache->size();
1296 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
1297 BasicBlock *Pred = *PI;
1298 PredList.push_back(std::make_pair(Pred, Pointer));
1300 // Get the PHI translated pointer in this predecessor. This can fail if
1301 // not translatable, in which case the getAddr() returns null.
1302 PHITransAddr &PredPointer = PredList.back().second;
1303 PredPointer.PHITranslateValue(BB, Pred, nullptr);
1305 Value *PredPtrVal = PredPointer.getAddr();
1307 // Check to see if we have already visited this pred block with another
1308 // pointer. If so, we can't do this lookup. This failure can occur
1309 // with PHI translation when a critical edge exists and the PHI node in
1310 // the successor translates to a pointer value different than the
1311 // pointer the block was first analyzed with.
1312 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
1313 InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
1315 if (!InsertRes.second) {
1316 // We found the pred; take it off the list of preds to visit.
1317 PredList.pop_back();
1319 // If the predecessor was visited with PredPtr, then we already did
1320 // the analysis and can ignore it.
1321 if (InsertRes.first->second == PredPtrVal)
1324 // Otherwise, the block was previously analyzed with a different
1325 // pointer. We can't represent the result of this case, so we just
1326 // treat this as a phi translation failure.
1328 // Make sure to clean up the Visited map before continuing on to
1329 // PredTranslationFailure.
1330 for (unsigned i = 0, n = PredList.size(); i < n; ++i)
1331 Visited.erase(PredList[i].first);
1333 goto PredTranslationFailure;
1337 // Actually process results here; this need to be a separate loop to avoid
1338 // calling getNonLocalPointerDepFromBB for blocks we don't want to return
1339 // any results for. (getNonLocalPointerDepFromBB will modify our
1340 // datastructures in ways the code after the PredTranslationFailure label
1342 for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
1343 BasicBlock *Pred = PredList[i].first;
1344 PHITransAddr &PredPointer = PredList[i].second;
1345 Value *PredPtrVal = PredPointer.getAddr();
1347 bool CanTranslate = true;
1348 // If PHI translation was unable to find an available pointer in this
1349 // predecessor, then we have to assume that the pointer is clobbered in
1350 // that predecessor. We can still do PRE of the load, which would insert
1351 // a computation of the pointer in this predecessor.
1353 CanTranslate = false;
1355 // FIXME: it is entirely possible that PHI translating will end up with
1356 // the same value. Consider PHI translating something like:
1357 // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need*
1358 // to recurse here, pedantically speaking.
1360 // If getNonLocalPointerDepFromBB fails here, that means the cached
1361 // result conflicted with the Visited list; we have to conservatively
1362 // assume it is unknown, but this also does not block PRE of the load.
1363 if (!CanTranslate ||
1364 getNonLocalPointerDepFromBB(QueryInst, PredPointer,
1365 Loc.getWithNewPtr(PredPtrVal),
1368 // Add the entry to the Result list.
1369 NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
1370 Result.push_back(Entry);
1372 // Since we had a phi translation failure, the cache for CacheKey won't
1373 // include all of the entries that we need to immediately satisfy future
1374 // queries. Mark this in NonLocalPointerDeps by setting the
1375 // BBSkipFirstBlockPair pointer to null. This requires reuse of the
1376 // cached value to do more work but not miss the phi trans failure.
1377 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1378 NLPI.Pair = BBSkipFirstBlockPair();
1383 // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1384 CacheInfo = &NonLocalPointerDeps[CacheKey];
1385 Cache = &CacheInfo->NonLocalDeps;
1386 NumSortedEntries = Cache->size();
1388 // Since we did phi translation, the "Cache" set won't contain all of the
1389 // results for the query. This is ok (we can still use it to accelerate
1390 // specific block queries) but we can't do the fastpath "return all
1391 // results from the set" Clear out the indicator for this.
1392 CacheInfo->Pair = BBSkipFirstBlockPair();
1393 SkipFirstBlock = false;
1396 PredTranslationFailure:
1397 // The following code is "failure"; we can't produce a sane translation
1398 // for the given block. It assumes that we haven't modified any of
1399 // our datastructures while processing the current block.
1402 // Refresh the CacheInfo/Cache pointer if it got invalidated.
1403 CacheInfo = &NonLocalPointerDeps[CacheKey];
1404 Cache = &CacheInfo->NonLocalDeps;
1405 NumSortedEntries = Cache->size();
1408 // Since we failed phi translation, the "Cache" set won't contain all of the
1409 // results for the query. This is ok (we can still use it to accelerate
1410 // specific block queries) but we can't do the fastpath "return all
1411 // results from the set". Clear out the indicator for this.
1412 CacheInfo->Pair = BBSkipFirstBlockPair();
1414 // If *nothing* works, mark the pointer as unknown.
1416 // If this is the magic first block, return this as a clobber of the whole
1417 // incoming value. Since we can't phi translate to one of the predecessors,
1418 // we have to bail out.
1422 for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
1423 assert(I != Cache->rend() && "Didn't find current block??");
1424 if (I->getBB() != BB)
1427 assert((I->getResult().isNonLocal() || !DT->isReachableFromEntry(BB)) &&
1428 "Should only be here with transparent block");
1429 I->setResult(MemDepResult::getUnknown());
1430 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
1431 Pointer.getAddr()));
1436 // Okay, we're done now. If we added new values to the cache, re-sort it.
1437 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1438 DEBUG(AssertSorted(*Cache));
1442 /// RemoveCachedNonLocalPointerDependencies - If P exists in
1443 /// CachedNonLocalPointerInfo, remove it.
1444 void MemoryDependenceAnalysis::
1445 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
1446 CachedNonLocalPointerInfo::iterator It =
1447 NonLocalPointerDeps.find(P);
1448 if (It == NonLocalPointerDeps.end()) return;
1450 // Remove all of the entries in the BB->val map. This involves removing
1451 // instructions from the reverse map.
1452 NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1454 for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1455 Instruction *Target = PInfo[i].getResult().getInst();
1456 if (!Target) continue; // Ignore non-local dep results.
1457 assert(Target->getParent() == PInfo[i].getBB());
1459 // Eliminating the dirty entry from 'Cache', so update the reverse info.
1460 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1463 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1464 NonLocalPointerDeps.erase(It);
1468 /// invalidateCachedPointerInfo - This method is used to invalidate cached
1469 /// information about the specified pointer, because it may be too
1470 /// conservative in memdep. This is an optional call that can be used when
1471 /// the client detects an equivalence between the pointer and some other
1472 /// value and replaces the other value with ptr. This can make Ptr available
1473 /// in more places that cached info does not necessarily keep.
1474 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
1475 // If Ptr isn't really a pointer, just ignore it.
1476 if (!Ptr->getType()->isPointerTy()) return;
1477 // Flush store info for the pointer.
1478 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1479 // Flush load info for the pointer.
1480 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1483 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
1484 /// This needs to be done when the CFG changes, e.g., due to splitting
1486 void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
1490 /// removeInstruction - Remove an instruction from the dependence analysis,
1491 /// updating the dependence of instructions that previously depended on it.
1492 /// This method attempts to keep the cache coherent using the reverse map.
1493 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
1494 // Walk through the Non-local dependencies, removing this one as the value
1495 // for any cached queries.
1496 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1497 if (NLDI != NonLocalDeps.end()) {
1498 NonLocalDepInfo &BlockMap = NLDI->second.first;
1499 for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
1501 if (Instruction *Inst = DI->getResult().getInst())
1502 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1503 NonLocalDeps.erase(NLDI);
1506 // If we have a cached local dependence query for this instruction, remove it.
1508 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1509 if (LocalDepEntry != LocalDeps.end()) {
1510 // Remove us from DepInst's reverse set now that the local dep info is gone.
1511 if (Instruction *Inst = LocalDepEntry->second.getInst())
1512 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1514 // Remove this local dependency info.
1515 LocalDeps.erase(LocalDepEntry);
1518 // If we have any cached pointer dependencies on this instruction, remove
1519 // them. If the instruction has non-pointer type, then it can't be a pointer
1522 // Remove it from both the load info and the store info. The instruction
1523 // can't be in either of these maps if it is non-pointer.
1524 if (RemInst->getType()->isPointerTy()) {
1525 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1526 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1529 // Loop over all of the things that depend on the instruction we're removing.
1531 SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
1533 // If we find RemInst as a clobber or Def in any of the maps for other values,
1534 // we need to replace its entry with a dirty version of the instruction after
1535 // it. If RemInst is a terminator, we use a null dirty value.
1537 // Using a dirty version of the instruction after RemInst saves having to scan
1538 // the entire block to get to this point.
1539 MemDepResult NewDirtyVal;
1540 if (!RemInst->isTerminator())
1541 NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
1543 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1544 if (ReverseDepIt != ReverseLocalDeps.end()) {
1545 // RemInst can't be the terminator if it has local stuff depending on it.
1546 assert(!ReverseDepIt->second.empty() && !isa<TerminatorInst>(RemInst) &&
1547 "Nothing can locally depend on a terminator");
1549 for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
1550 assert(InstDependingOnRemInst != RemInst &&
1551 "Already removed our local dep info");
1553 LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1555 // Make sure to remember that new things depend on NewDepInst.
1556 assert(NewDirtyVal.getInst() && "There is no way something else can have "
1557 "a local dep on this if it is a terminator!");
1558 ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
1559 InstDependingOnRemInst));
1562 ReverseLocalDeps.erase(ReverseDepIt);
1564 // Add new reverse deps after scanning the set, to avoid invalidating the
1565 // 'ReverseDeps' reference.
1566 while (!ReverseDepsToAdd.empty()) {
1567 ReverseLocalDeps[ReverseDepsToAdd.back().first]
1568 .insert(ReverseDepsToAdd.back().second);
1569 ReverseDepsToAdd.pop_back();
1573 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1574 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1575 for (Instruction *I : ReverseDepIt->second) {
1576 assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
1578 PerInstNLInfo &INLD = NonLocalDeps[I];
1579 // The information is now dirty!
1582 for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
1583 DE = INLD.first.end(); DI != DE; ++DI) {
1584 if (DI->getResult().getInst() != RemInst) continue;
1586 // Convert to a dirty entry for the subsequent instruction.
1587 DI->setResult(NewDirtyVal);
1589 if (Instruction *NextI = NewDirtyVal.getInst())
1590 ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
1594 ReverseNonLocalDeps.erase(ReverseDepIt);
1596 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1597 while (!ReverseDepsToAdd.empty()) {
1598 ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
1599 .insert(ReverseDepsToAdd.back().second);
1600 ReverseDepsToAdd.pop_back();
1604 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1605 // value in the NonLocalPointerDeps info.
1606 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1607 ReverseNonLocalPtrDeps.find(RemInst);
1608 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1609 SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
1611 for (ValueIsLoadPair P : ReversePtrDepIt->second) {
1612 assert(P.getPointer() != RemInst &&
1613 "Already removed NonLocalPointerDeps info for RemInst");
1615 NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1617 // The cache is not valid for any specific block anymore.
1618 NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1620 // Update any entries for RemInst to use the instruction after it.
1621 for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
1623 if (DI->getResult().getInst() != RemInst) continue;
1625 // Convert to a dirty entry for the subsequent instruction.
1626 DI->setResult(NewDirtyVal);
1628 if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1629 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1632 // Re-sort the NonLocalDepInfo. Changing the dirty entry to its
1633 // subsequent value may invalidate the sortedness.
1634 std::sort(NLPDI.begin(), NLPDI.end());
1637 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1639 while (!ReversePtrDepsToAdd.empty()) {
1640 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
1641 .insert(ReversePtrDepsToAdd.back().second);
1642 ReversePtrDepsToAdd.pop_back();
1647 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1648 AA->deleteValue(RemInst);
1649 DEBUG(verifyRemoved(RemInst));
1651 /// verifyRemoved - Verify that the specified instruction does not occur
1652 /// in our internal data structures. This function verifies by asserting in
1654 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
1656 for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
1657 E = LocalDeps.end(); I != E; ++I) {
1658 assert(I->first != D && "Inst occurs in data structures");
1659 assert(I->second.getInst() != D &&
1660 "Inst occurs in data structures");
1663 for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
1664 E = NonLocalPointerDeps.end(); I != E; ++I) {
1665 assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
1666 const NonLocalDepInfo &Val = I->second.NonLocalDeps;
1667 for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
1669 assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
1672 for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
1673 E = NonLocalDeps.end(); I != E; ++I) {
1674 assert(I->first != D && "Inst occurs in data structures");
1675 const PerInstNLInfo &INLD = I->second;
1676 for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
1677 EE = INLD.first.end(); II != EE; ++II)
1678 assert(II->getResult().getInst() != D && "Inst occurs in data structures");
1681 for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
1682 E = ReverseLocalDeps.end(); I != E; ++I) {
1683 assert(I->first != D && "Inst occurs in data structures");
1684 for (Instruction *Inst : I->second)
1685 assert(Inst != D && "Inst occurs in data structures");
1688 for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
1689 E = ReverseNonLocalDeps.end();
1691 assert(I->first != D && "Inst occurs in data structures");
1692 for (Instruction *Inst : I->second)
1693 assert(Inst != D && "Inst occurs in data structures");
1696 for (ReverseNonLocalPtrDepTy::const_iterator
1697 I = ReverseNonLocalPtrDeps.begin(),
1698 E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
1699 assert(I->first != D && "Inst occurs in rev NLPD map");
1701 for (ValueIsLoadPair P : I->second)
1702 assert(P != ValueIsLoadPair(D, false) &&
1703 P != ValueIsLoadPair(D, true) &&
1704 "Inst occurs in ReverseNonLocalPtrDeps map");