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/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/AssumptionCache.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/Analysis/PHITransAddr.h"
26 #include "llvm/Analysis/OrderedBasicBlock.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/IR/CallSite.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Instruction.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/PredIteratorCache.h"
40 #include "llvm/Support/AtomicOrdering.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/MathExtras.h"
52 #define DEBUG_TYPE "memdep"
54 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
55 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
56 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
58 STATISTIC(NumCacheNonLocalPtr,
59 "Number of fully cached non-local ptr responses");
60 STATISTIC(NumCacheDirtyNonLocalPtr,
61 "Number of cached, but dirty, non-local ptr responses");
62 STATISTIC(NumUncacheNonLocalPtr, "Number of uncached non-local ptr responses");
63 STATISTIC(NumCacheCompleteNonLocalPtr,
64 "Number of block queries that were completely cached");
66 // Limit for the number of instructions to scan in a block.
68 static cl::opt<unsigned> BlockScanLimit(
69 "memdep-block-scan-limit", cl::Hidden, cl::init(100),
70 cl::desc("The number of instructions to scan in a block in memory "
71 "dependency analysis (default = 100)"));
73 static cl::opt<unsigned>
74 BlockNumberLimit("memdep-block-number-limit", cl::Hidden, cl::init(1000),
75 cl::desc("The number of blocks to scan during memory "
76 "dependency analysis (default = 1000)"));
78 // Limit on the number of memdep results to process.
79 static const unsigned int NumResultsLimit = 100;
81 /// This is a helper function that removes Val from 'Inst's set in ReverseMap.
83 /// If the set becomes empty, remove Inst's entry.
84 template <typename KeyTy>
86 RemoveFromReverseMap(DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>> &ReverseMap,
87 Instruction *Inst, KeyTy Val) {
88 typename DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>>::iterator InstIt =
89 ReverseMap.find(Inst);
90 assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
91 bool Found = InstIt->second.erase(Val);
92 assert(Found && "Invalid reverse map!");
94 if (InstIt->second.empty())
95 ReverseMap.erase(InstIt);
98 /// If the given instruction references a specific memory location, fill in Loc
99 /// with the details, otherwise set Loc.Ptr to null.
101 /// Returns a ModRefInfo value describing the general behavior of the
103 static ModRefInfo GetLocation(const Instruction *Inst, MemoryLocation &Loc,
104 const TargetLibraryInfo &TLI) {
105 if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
106 if (LI->isUnordered()) {
107 Loc = MemoryLocation::get(LI);
110 if (LI->getOrdering() == AtomicOrdering::Monotonic) {
111 Loc = MemoryLocation::get(LI);
114 Loc = MemoryLocation();
118 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
119 if (SI->isUnordered()) {
120 Loc = MemoryLocation::get(SI);
123 if (SI->getOrdering() == AtomicOrdering::Monotonic) {
124 Loc = MemoryLocation::get(SI);
127 Loc = MemoryLocation();
131 if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
132 Loc = MemoryLocation::get(V);
136 if (const CallInst *CI = isFreeCall(Inst, &TLI)) {
137 // calls to free() deallocate the entire structure
138 Loc = MemoryLocation(CI->getArgOperand(0));
142 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
145 switch (II->getIntrinsicID()) {
146 case Intrinsic::lifetime_start:
147 case Intrinsic::lifetime_end:
148 case Intrinsic::invariant_start:
149 II->getAAMetadata(AAInfo);
150 Loc = MemoryLocation(
151 II->getArgOperand(1),
152 cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(), AAInfo);
153 // These intrinsics don't really modify the memory, but returning Mod
154 // will allow them to be handled conservatively.
156 case Intrinsic::invariant_end:
157 II->getAAMetadata(AAInfo);
158 Loc = MemoryLocation(
159 II->getArgOperand(2),
160 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue(), AAInfo);
161 // These intrinsics don't really modify the memory, but returning Mod
162 // will allow them to be handled conservatively.
169 // Otherwise, just do the coarse-grained thing that always works.
170 if (Inst->mayWriteToMemory())
172 if (Inst->mayReadFromMemory())
177 /// Private helper for finding the local dependencies of a call site.
178 MemDepResult MemoryDependenceResults::getCallSiteDependencyFrom(
179 CallSite CS, bool isReadOnlyCall, BasicBlock::iterator ScanIt,
181 unsigned Limit = BlockScanLimit;
183 // Walk backwards through the block, looking for dependencies
184 while (ScanIt != BB->begin()) {
185 // Limit the amount of scanning we do so we don't end up with quadratic
186 // running time on extreme testcases.
189 return MemDepResult::getUnknown();
191 Instruction *Inst = &*--ScanIt;
193 // If this inst is a memory op, get the pointer it accessed
195 ModRefInfo MR = GetLocation(Inst, Loc, TLI);
197 // A simple instruction.
198 if (AA.getModRefInfo(CS, Loc) != MRI_NoModRef)
199 return MemDepResult::getClobber(Inst);
203 if (auto InstCS = CallSite(Inst)) {
204 // Debug intrinsics don't cause dependences.
205 if (isa<DbgInfoIntrinsic>(Inst))
207 // If these two calls do not interfere, look past it.
208 switch (AA.getModRefInfo(CS, InstCS)) {
210 // If the two calls are the same, return InstCS as a Def, so that
211 // CS can be found redundant and eliminated.
212 if (isReadOnlyCall && !(MR & MRI_Mod) &&
213 CS.getInstruction()->isIdenticalToWhenDefined(Inst))
214 return MemDepResult::getDef(Inst);
216 // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
220 return MemDepResult::getClobber(Inst);
224 // If we could not obtain a pointer for the instruction and the instruction
225 // touches memory then assume that this is a dependency.
226 if (MR != MRI_NoModRef)
227 return MemDepResult::getClobber(Inst);
230 // No dependence found. If this is the entry block of the function, it is
231 // unknown, otherwise it is non-local.
232 if (BB != &BB->getParent()->getEntryBlock())
233 return MemDepResult::getNonLocal();
234 return MemDepResult::getNonFuncLocal();
237 /// Return true if LI is a load that would fully overlap MemLoc if done as
238 /// a wider legal integer load.
240 /// MemLocBase, MemLocOffset are lazily computed here the first time the
241 /// base/offs of memloc is needed.
242 static bool isLoadLoadClobberIfExtendedToFullWidth(const MemoryLocation &MemLoc,
243 const Value *&MemLocBase,
245 const LoadInst *LI) {
246 const DataLayout &DL = LI->getModule()->getDataLayout();
248 // If we haven't already computed the base/offset of MemLoc, do so now.
250 MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, DL);
252 unsigned Size = MemoryDependenceResults::getLoadLoadClobberFullWidthSize(
253 MemLocBase, MemLocOffs, MemLoc.Size, LI);
257 unsigned MemoryDependenceResults::getLoadLoadClobberFullWidthSize(
258 const Value *MemLocBase, int64_t MemLocOffs, unsigned MemLocSize,
259 const LoadInst *LI) {
260 // We can only extend simple integer loads.
261 if (!isa<IntegerType>(LI->getType()) || !LI->isSimple())
264 // Load widening is hostile to ThreadSanitizer: it may cause false positives
265 // or make the reports more cryptic (access sizes are wrong).
266 if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
269 const DataLayout &DL = LI->getModule()->getDataLayout();
271 // Get the base of this load.
273 const Value *LIBase =
274 GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, DL);
276 // If the two pointers are not based on the same pointer, we can't tell that
278 if (LIBase != MemLocBase)
281 // Okay, the two values are based on the same pointer, but returned as
282 // no-alias. This happens when we have things like two byte loads at "P+1"
283 // and "P+3". Check to see if increasing the size of the "LI" load up to its
284 // alignment (or the largest native integer type) will allow us to load all
285 // the bits required by MemLoc.
287 // If MemLoc is before LI, then no widening of LI will help us out.
288 if (MemLocOffs < LIOffs)
291 // Get the alignment of the load in bytes. We assume that it is safe to load
292 // any legal integer up to this size without a problem. For example, if we're
293 // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
294 // widen it up to an i32 load. If it is known 2-byte aligned, we can widen it
296 unsigned LoadAlign = LI->getAlignment();
298 int64_t MemLocEnd = MemLocOffs + MemLocSize;
300 // If no amount of rounding up will let MemLoc fit into LI, then bail out.
301 if (LIOffs + LoadAlign < MemLocEnd)
304 // This is the size of the load to try. Start with the next larger power of
306 unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits() / 8U;
307 NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
310 // If this load size is bigger than our known alignment or would not fit
311 // into a native integer register, then we fail.
312 if (NewLoadByteSize > LoadAlign ||
313 !DL.fitsInLegalInteger(NewLoadByteSize * 8))
316 if (LIOffs + NewLoadByteSize > MemLocEnd &&
317 LI->getParent()->getParent()->hasFnAttribute(
318 Attribute::SanitizeAddress))
319 // We will be reading past the location accessed by the original program.
320 // While this is safe in a regular build, Address Safety analysis tools
321 // may start reporting false warnings. So, don't do widening.
324 // If a load of this width would include all of MemLoc, then we succeed.
325 if (LIOffs + NewLoadByteSize >= MemLocEnd)
326 return NewLoadByteSize;
328 NewLoadByteSize <<= 1;
332 static bool isVolatile(Instruction *Inst) {
333 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
334 return LI->isVolatile();
335 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
336 return SI->isVolatile();
337 else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst))
338 return AI->isVolatile();
342 MemDepResult MemoryDependenceResults::getPointerDependencyFrom(
343 const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
344 BasicBlock *BB, Instruction *QueryInst) {
346 if (QueryInst != nullptr) {
347 if (auto *LI = dyn_cast<LoadInst>(QueryInst)) {
348 MemDepResult invariantGroupDependency =
349 getInvariantGroupPointerDependency(LI, BB);
351 if (invariantGroupDependency.isDef())
352 return invariantGroupDependency;
355 return getSimplePointerDependencyFrom(MemLoc, isLoad, ScanIt, BB, QueryInst);
359 MemoryDependenceResults::getInvariantGroupPointerDependency(LoadInst *LI,
361 Value *LoadOperand = LI->getPointerOperand();
362 // It's is not safe to walk the use list of global value, because function
363 // passes aren't allowed to look outside their functions.
364 if (isa<GlobalValue>(LoadOperand))
365 return MemDepResult::getUnknown();
367 auto *InvariantGroupMD = LI->getMetadata(LLVMContext::MD_invariant_group);
368 if (!InvariantGroupMD)
369 return MemDepResult::getUnknown();
371 MemDepResult Result = MemDepResult::getUnknown();
372 SmallSet<Value *, 14> Seen;
373 // Queue to process all pointers that are equivalent to load operand.
374 SmallVector<Value *, 8> LoadOperandsQueue;
375 LoadOperandsQueue.push_back(LoadOperand);
376 while (!LoadOperandsQueue.empty()) {
377 Value *Ptr = LoadOperandsQueue.pop_back_val();
378 if (isa<GlobalValue>(Ptr))
381 if (auto *BCI = dyn_cast<BitCastInst>(Ptr)) {
382 if (Seen.insert(BCI->getOperand(0)).second) {
383 LoadOperandsQueue.push_back(BCI->getOperand(0));
387 for (Use &Us : Ptr->uses()) {
388 auto *U = dyn_cast<Instruction>(Us.getUser());
389 if (!U || U == LI || !DT.dominates(U, LI))
392 if (auto *BCI = dyn_cast<BitCastInst>(U)) {
393 if (Seen.insert(BCI).second) {
394 LoadOperandsQueue.push_back(BCI);
398 // If we hit load/store with the same invariant.group metadata (and the
399 // same pointer operand) we can assume that value pointed by pointer
400 // operand didn't change.
401 if ((isa<LoadInst>(U) || isa<StoreInst>(U)) && U->getParent() == BB &&
402 U->getMetadata(LLVMContext::MD_invariant_group) == InvariantGroupMD)
403 return MemDepResult::getDef(U);
409 MemDepResult MemoryDependenceResults::getSimplePointerDependencyFrom(
410 const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
411 BasicBlock *BB, Instruction *QueryInst) {
412 const Value *MemLocBase = nullptr;
413 int64_t MemLocOffset = 0;
414 unsigned Limit = BlockScanLimit;
415 bool isInvariantLoad = false;
417 // We must be careful with atomic accesses, as they may allow another thread
418 // to touch this location, clobbering it. We are conservative: if the
419 // QueryInst is not a simple (non-atomic) memory access, we automatically
420 // return getClobber.
421 // If it is simple, we know based on the results of
422 // "Compiler testing via a theory of sound optimisations in the C11/C++11
423 // memory model" in PLDI 2013, that a non-atomic location can only be
424 // clobbered between a pair of a release and an acquire action, with no
425 // access to the location in between.
426 // Here is an example for giving the general intuition behind this rule.
427 // In the following code:
429 // release action; [1]
430 // acquire action; [4]
432 // It is unsafe to replace %val by 0 because another thread may be running:
433 // acquire action; [2]
435 // release action; [3]
436 // with synchronization from 1 to 2 and from 3 to 4, resulting in %val
437 // being 42. A key property of this program however is that if either
438 // 1 or 4 were missing, there would be a race between the store of 42
439 // either the store of 0 or the load (making the whole program racy).
440 // The paper mentioned above shows that the same property is respected
441 // by every program that can detect any optimization of that kind: either
442 // it is racy (undefined) or there is a release followed by an acquire
443 // between the pair of accesses under consideration.
445 // If the load is invariant, we "know" that it doesn't alias *any* write. We
446 // do want to respect mustalias results since defs are useful for value
447 // forwarding, but any mayalias write can be assumed to be noalias.
448 // Arguably, this logic should be pushed inside AliasAnalysis itself.
449 if (isLoad && QueryInst) {
450 LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
451 if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr)
452 isInvariantLoad = true;
455 const DataLayout &DL = BB->getModule()->getDataLayout();
457 // Create a numbered basic block to lazily compute and cache instruction
458 // positions inside a BB. This is used to provide fast queries for relative
459 // position between two instructions in a BB and can be used by
460 // AliasAnalysis::callCapturesBefore.
461 OrderedBasicBlock OBB(BB);
463 // Return "true" if and only if the instruction I is either a non-simple
464 // load or a non-simple store.
465 auto isNonSimpleLoadOrStore = [](Instruction *I) -> bool {
466 if (auto *LI = dyn_cast<LoadInst>(I))
467 return !LI->isSimple();
468 if (auto *SI = dyn_cast<StoreInst>(I))
469 return !SI->isSimple();
473 // Return "true" if I is not a load and not a store, but it does access
475 auto isOtherMemAccess = [](Instruction *I) -> bool {
476 return !isa<LoadInst>(I) && !isa<StoreInst>(I) && I->mayReadOrWriteMemory();
479 // Walk backwards through the basic block, looking for dependencies.
480 while (ScanIt != BB->begin()) {
481 Instruction *Inst = &*--ScanIt;
483 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
484 // Debug intrinsics don't (and can't) cause dependencies.
485 if (isa<DbgInfoIntrinsic>(II))
488 // Limit the amount of scanning we do so we don't end up with quadratic
489 // running time on extreme testcases.
492 return MemDepResult::getUnknown();
494 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
495 // If we reach a lifetime begin or end marker, then the query ends here
496 // because the value is undefined.
497 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
498 // FIXME: This only considers queries directly on the invariant-tagged
499 // pointer, not on query pointers that are indexed off of them. It'd
500 // be nice to handle that at some point (the right approach is to use
501 // GetPointerBaseWithConstantOffset).
502 if (AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), MemLoc))
503 return MemDepResult::getDef(II);
508 // Values depend on loads if the pointers are must aliased. This means
509 // that a load depends on another must aliased load from the same value.
510 // One exception is atomic loads: a value can depend on an atomic load that
511 // it does not alias with when this atomic load indicates that another
512 // thread may be accessing the location.
513 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
515 // While volatile access cannot be eliminated, they do not have to clobber
516 // non-aliasing locations, as normal accesses, for example, can be safely
517 // reordered with volatile accesses.
518 if (LI->isVolatile()) {
520 // Original QueryInst *may* be volatile
521 return MemDepResult::getClobber(LI);
522 if (isVolatile(QueryInst))
523 // Ordering required if QueryInst is itself volatile
524 return MemDepResult::getClobber(LI);
525 // Otherwise, volatile doesn't imply any special ordering
528 // Atomic loads have complications involved.
529 // A Monotonic (or higher) load is OK if the query inst is itself not
531 // FIXME: This is overly conservative.
532 if (LI->isAtomic() && isStrongerThanUnordered(LI->getOrdering())) {
533 if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
534 isOtherMemAccess(QueryInst))
535 return MemDepResult::getClobber(LI);
536 if (LI->getOrdering() != AtomicOrdering::Monotonic)
537 return MemDepResult::getClobber(LI);
540 MemoryLocation LoadLoc = MemoryLocation::get(LI);
542 // If we found a pointer, check if it could be the same as our pointer.
543 AliasResult R = AA.alias(LoadLoc, MemLoc);
547 // If this is an over-aligned integer load (for example,
548 // "load i8* %P, align 4") see if it would obviously overlap with the
549 // queried location if widened to a larger load (e.g. if the queried
550 // location is 1 byte at P+1). If so, return it as a load/load
551 // clobber result, allowing the client to decide to widen the load if
553 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
554 if (LI->getAlignment() * 8 > ITy->getPrimitiveSizeInBits() &&
555 isLoadLoadClobberIfExtendedToFullWidth(MemLoc, MemLocBase,
557 return MemDepResult::getClobber(Inst);
562 // Must aliased loads are defs of each other.
564 return MemDepResult::getDef(Inst);
566 #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads
567 // in terms of clobbering loads, but since it does this by looking
568 // at the clobbering load directly, it doesn't know about any
569 // phi translation that may have happened along the way.
571 // If we have a partial alias, then return this as a clobber for the
573 if (R == PartialAlias)
574 return MemDepResult::getClobber(Inst);
577 // Random may-alias loads don't depend on each other without a
582 // Stores don't depend on other no-aliased accesses.
586 // Stores don't alias loads from read-only memory.
587 if (AA.pointsToConstantMemory(LoadLoc))
590 // Stores depend on may/must aliased loads.
591 return MemDepResult::getDef(Inst);
594 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
595 // Atomic stores have complications involved.
596 // A Monotonic store is OK if the query inst is itself not atomic.
597 // FIXME: This is overly conservative.
598 if (!SI->isUnordered() && SI->isAtomic()) {
599 if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
600 isOtherMemAccess(QueryInst))
601 return MemDepResult::getClobber(SI);
602 if (SI->getOrdering() != AtomicOrdering::Monotonic)
603 return MemDepResult::getClobber(SI);
606 // FIXME: this is overly conservative.
607 // While volatile access cannot be eliminated, they do not have to clobber
608 // non-aliasing locations, as normal accesses can for example be reordered
609 // with volatile accesses.
610 if (SI->isVolatile())
611 if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
612 isOtherMemAccess(QueryInst))
613 return MemDepResult::getClobber(SI);
615 // If alias analysis can tell that this store is guaranteed to not modify
616 // the query pointer, ignore it. Use getModRefInfo to handle cases where
617 // the query pointer points to constant memory etc.
618 if (AA.getModRefInfo(SI, MemLoc) == MRI_NoModRef)
621 // Ok, this store might clobber the query pointer. Check to see if it is
622 // a must alias: in this case, we want to return this as a def.
623 MemoryLocation StoreLoc = MemoryLocation::get(SI);
625 // If we found a pointer, check if it could be the same as our pointer.
626 AliasResult R = AA.alias(StoreLoc, MemLoc);
631 return MemDepResult::getDef(Inst);
634 return MemDepResult::getClobber(Inst);
637 // If this is an allocation, and if we know that the accessed pointer is to
638 // the allocation, return Def. This means that there is no dependence and
639 // the access can be optimized based on that. For example, a load could
640 // turn into undef. Note that we can bypass the allocation itself when
641 // looking for a clobber in many cases; that's an alias property and is
642 // handled by BasicAA.
643 if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, &TLI)) {
644 const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL);
645 if (AccessPtr == Inst || AA.isMustAlias(Inst, AccessPtr))
646 return MemDepResult::getDef(Inst);
652 // A release fence requires that all stores complete before it, but does
653 // not prevent the reordering of following loads or stores 'before' the
654 // fence. As a result, we look past it when finding a dependency for
655 // loads. DSE uses this to find preceeding stores to delete and thus we
656 // can't bypass the fence if the query instruction is a store.
657 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
658 if (isLoad && FI->getOrdering() == AtomicOrdering::Release)
661 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
662 ModRefInfo MR = AA.getModRefInfo(Inst, MemLoc);
663 // If necessary, perform additional analysis.
664 if (MR == MRI_ModRef)
665 MR = AA.callCapturesBefore(Inst, MemLoc, &DT, &OBB);
668 // If the call has no effect on the queried pointer, just ignore it.
671 return MemDepResult::getClobber(Inst);
673 // If the call is known to never store to the pointer, and if this is a
674 // load query, we can safely ignore it (scan past it).
678 // Otherwise, there is a potential dependence. Return a clobber.
679 return MemDepResult::getClobber(Inst);
683 // No dependence found. If this is the entry block of the function, it is
684 // unknown, otherwise it is non-local.
685 if (BB != &BB->getParent()->getEntryBlock())
686 return MemDepResult::getNonLocal();
687 return MemDepResult::getNonFuncLocal();
690 MemDepResult MemoryDependenceResults::getDependency(Instruction *QueryInst) {
691 Instruction *ScanPos = QueryInst;
693 // Check for a cached result
694 MemDepResult &LocalCache = LocalDeps[QueryInst];
696 // If the cached entry is non-dirty, just return it. Note that this depends
697 // on MemDepResult's default constructing to 'dirty'.
698 if (!LocalCache.isDirty())
701 // Otherwise, if we have a dirty entry, we know we can start the scan at that
702 // instruction, which may save us some work.
703 if (Instruction *Inst = LocalCache.getInst()) {
706 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
709 BasicBlock *QueryParent = QueryInst->getParent();
712 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
713 // No dependence found. If this is the entry block of the function, it is
714 // unknown, otherwise it is non-local.
715 if (QueryParent != &QueryParent->getParent()->getEntryBlock())
716 LocalCache = MemDepResult::getNonLocal();
718 LocalCache = MemDepResult::getNonFuncLocal();
720 MemoryLocation MemLoc;
721 ModRefInfo MR = GetLocation(QueryInst, MemLoc, TLI);
723 // If we can do a pointer scan, make it happen.
724 bool isLoad = !(MR & MRI_Mod);
725 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
726 isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
728 LocalCache = getPointerDependencyFrom(
729 MemLoc, isLoad, ScanPos->getIterator(), QueryParent, QueryInst);
730 } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
731 CallSite QueryCS(QueryInst);
732 bool isReadOnly = AA.onlyReadsMemory(QueryCS);
733 LocalCache = getCallSiteDependencyFrom(
734 QueryCS, isReadOnly, ScanPos->getIterator(), QueryParent);
736 // Non-memory instruction.
737 LocalCache = MemDepResult::getUnknown();
740 // Remember the result!
741 if (Instruction *I = LocalCache.getInst())
742 ReverseLocalDeps[I].insert(QueryInst);
748 /// This method is used when -debug is specified to verify that cache arrays
749 /// are properly kept sorted.
750 static void AssertSorted(MemoryDependenceResults::NonLocalDepInfo &Cache,
753 Count = Cache.size();
754 assert(std::is_sorted(Cache.begin(), Cache.begin() + Count) &&
755 "Cache isn't sorted!");
759 const MemoryDependenceResults::NonLocalDepInfo &
760 MemoryDependenceResults::getNonLocalCallDependency(CallSite QueryCS) {
761 assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
762 "getNonLocalCallDependency should only be used on calls with "
764 PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
765 NonLocalDepInfo &Cache = CacheP.first;
767 // This is the set of blocks that need to be recomputed. In the cached case,
768 // this can happen due to instructions being deleted etc. In the uncached
769 // case, this starts out as the set of predecessors we care about.
770 SmallVector<BasicBlock *, 32> DirtyBlocks;
772 if (!Cache.empty()) {
773 // Okay, we have a cache entry. If we know it is not dirty, just return it
774 // with no computation.
775 if (!CacheP.second) {
780 // If we already have a partially computed set of results, scan them to
781 // determine what is dirty, seeding our initial DirtyBlocks worklist.
782 for (auto &Entry : Cache)
783 if (Entry.getResult().isDirty())
784 DirtyBlocks.push_back(Entry.getBB());
786 // Sort the cache so that we can do fast binary search lookups below.
787 std::sort(Cache.begin(), Cache.end());
789 ++NumCacheDirtyNonLocal;
790 // cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
791 // << Cache.size() << " cached: " << *QueryInst;
793 // Seed DirtyBlocks with each of the preds of QueryInst's block.
794 BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
795 for (BasicBlock *Pred : PredCache.get(QueryBB))
796 DirtyBlocks.push_back(Pred);
797 ++NumUncacheNonLocal;
800 // isReadonlyCall - If this is a read-only call, we can be more aggressive.
801 bool isReadonlyCall = AA.onlyReadsMemory(QueryCS);
803 SmallPtrSet<BasicBlock *, 32> Visited;
805 unsigned NumSortedEntries = Cache.size();
806 DEBUG(AssertSorted(Cache));
808 // Iterate while we still have blocks to update.
809 while (!DirtyBlocks.empty()) {
810 BasicBlock *DirtyBB = DirtyBlocks.back();
811 DirtyBlocks.pop_back();
813 // Already processed this block?
814 if (!Visited.insert(DirtyBB).second)
817 // Do a binary search to see if we already have an entry for this block in
818 // the cache set. If so, find it.
819 DEBUG(AssertSorted(Cache, NumSortedEntries));
820 NonLocalDepInfo::iterator Entry =
821 std::upper_bound(Cache.begin(), Cache.begin() + NumSortedEntries,
822 NonLocalDepEntry(DirtyBB));
823 if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
826 NonLocalDepEntry *ExistingResult = nullptr;
827 if (Entry != Cache.begin() + NumSortedEntries &&
828 Entry->getBB() == DirtyBB) {
829 // If we already have an entry, and if it isn't already dirty, the block
831 if (!Entry->getResult().isDirty())
834 // Otherwise, remember this slot so we can update the value.
835 ExistingResult = &*Entry;
838 // If the dirty entry has a pointer, start scanning from it so we don't have
839 // to rescan the entire block.
840 BasicBlock::iterator ScanPos = DirtyBB->end();
841 if (ExistingResult) {
842 if (Instruction *Inst = ExistingResult->getResult().getInst()) {
843 ScanPos = Inst->getIterator();
844 // We're removing QueryInst's use of Inst.
845 RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
846 QueryCS.getInstruction());
850 // Find out if this block has a local dependency for QueryInst.
853 if (ScanPos != DirtyBB->begin()) {
855 getCallSiteDependencyFrom(QueryCS, isReadonlyCall, ScanPos, DirtyBB);
856 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
857 // No dependence found. If this is the entry block of the function, it is
858 // a clobber, otherwise it is unknown.
859 Dep = MemDepResult::getNonLocal();
861 Dep = MemDepResult::getNonFuncLocal();
864 // If we had a dirty entry for the block, update it. Otherwise, just add
867 ExistingResult->setResult(Dep);
869 Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
871 // If the block has a dependency (i.e. it isn't completely transparent to
872 // the value), remember the association!
873 if (!Dep.isNonLocal()) {
874 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
875 // update this when we remove instructions.
876 if (Instruction *Inst = Dep.getInst())
877 ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
880 // If the block *is* completely transparent to the load, we need to check
881 // the predecessors of this block. Add them to our worklist.
882 for (BasicBlock *Pred : PredCache.get(DirtyBB))
883 DirtyBlocks.push_back(Pred);
890 void MemoryDependenceResults::getNonLocalPointerDependency(
891 Instruction *QueryInst, SmallVectorImpl<NonLocalDepResult> &Result) {
892 const MemoryLocation Loc = MemoryLocation::get(QueryInst);
893 bool isLoad = isa<LoadInst>(QueryInst);
894 BasicBlock *FromBB = QueryInst->getParent();
897 assert(Loc.Ptr->getType()->isPointerTy() &&
898 "Can't get pointer deps of a non-pointer!");
901 // This routine does not expect to deal with volatile instructions.
902 // Doing so would require piping through the QueryInst all the way through.
903 // TODO: volatiles can't be elided, but they can be reordered with other
904 // non-volatile accesses.
906 // We currently give up on any instruction which is ordered, but we do handle
907 // atomic instructions which are unordered.
908 // TODO: Handle ordered instructions
909 auto isOrdered = [](Instruction *Inst) {
910 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
911 return !LI->isUnordered();
912 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
913 return !SI->isUnordered();
917 if (isVolatile(QueryInst) || isOrdered(QueryInst)) {
918 Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
919 const_cast<Value *>(Loc.Ptr)));
922 const DataLayout &DL = FromBB->getModule()->getDataLayout();
923 PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, &AC);
925 // This is the set of blocks we've inspected, and the pointer we consider in
926 // each block. Because of critical edges, we currently bail out if querying
927 // a block with multiple different pointers. This can happen during PHI
929 DenseMap<BasicBlock *, Value *> Visited;
930 if (getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
931 Result, Visited, true))
934 Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
935 const_cast<Value *>(Loc.Ptr)));
938 /// Compute the memdep value for BB with Pointer/PointeeSize using either
939 /// cached information in Cache or by doing a lookup (which may use dirty cache
940 /// info if available).
942 /// If we do a lookup, add the result to the cache.
943 MemDepResult MemoryDependenceResults::GetNonLocalInfoForBlock(
944 Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad,
945 BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
947 // Do a binary search to see if we already have an entry for this block in
948 // the cache set. If so, find it.
949 NonLocalDepInfo::iterator Entry = std::upper_bound(
950 Cache->begin(), Cache->begin() + NumSortedEntries, NonLocalDepEntry(BB));
951 if (Entry != Cache->begin() && (Entry - 1)->getBB() == BB)
954 NonLocalDepEntry *ExistingResult = nullptr;
955 if (Entry != Cache->begin() + NumSortedEntries && Entry->getBB() == BB)
956 ExistingResult = &*Entry;
958 // If we have a cached entry, and it is non-dirty, use it as the value for
960 if (ExistingResult && !ExistingResult->getResult().isDirty()) {
961 ++NumCacheNonLocalPtr;
962 return ExistingResult->getResult();
965 // Otherwise, we have to scan for the value. If we have a dirty cache
966 // entry, start scanning from its position, otherwise we scan from the end
968 BasicBlock::iterator ScanPos = BB->end();
969 if (ExistingResult && ExistingResult->getResult().getInst()) {
970 assert(ExistingResult->getResult().getInst()->getParent() == BB &&
971 "Instruction invalidated?");
972 ++NumCacheDirtyNonLocalPtr;
973 ScanPos = ExistingResult->getResult().getInst()->getIterator();
975 // Eliminating the dirty entry from 'Cache', so update the reverse info.
976 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
977 RemoveFromReverseMap(ReverseNonLocalPtrDeps, &*ScanPos, CacheKey);
979 ++NumUncacheNonLocalPtr;
982 // Scan the block for the dependency.
984 getPointerDependencyFrom(Loc, isLoad, ScanPos, BB, QueryInst);
986 // If we had a dirty entry for the block, update it. Otherwise, just add
989 ExistingResult->setResult(Dep);
991 Cache->push_back(NonLocalDepEntry(BB, Dep));
993 // If the block has a dependency (i.e. it isn't completely transparent to
994 // the value), remember the reverse association because we just added it
996 if (!Dep.isDef() && !Dep.isClobber())
999 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
1000 // update MemDep when we remove instructions.
1001 Instruction *Inst = Dep.getInst();
1002 assert(Inst && "Didn't depend on anything?");
1003 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
1004 ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
1008 /// Sort the NonLocalDepInfo cache, given a certain number of elements in the
1009 /// array that are already properly ordered.
1011 /// This is optimized for the case when only a few entries are added.
1013 SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache,
1014 unsigned NumSortedEntries) {
1015 switch (Cache.size() - NumSortedEntries) {
1017 // done, no new entries.
1020 // Two new entries, insert the last one into place.
1021 NonLocalDepEntry Val = Cache.back();
1023 MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
1024 std::upper_bound(Cache.begin(), Cache.end() - 1, Val);
1025 Cache.insert(Entry, Val);
1029 // One new entry, Just insert the new value at the appropriate position.
1030 if (Cache.size() != 1) {
1031 NonLocalDepEntry Val = Cache.back();
1033 MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
1034 std::upper_bound(Cache.begin(), Cache.end(), Val);
1035 Cache.insert(Entry, Val);
1039 // Added many values, do a full scale sort.
1040 std::sort(Cache.begin(), Cache.end());
1045 /// Perform a dependency query based on pointer/pointeesize starting at the end
1048 /// Add any clobber/def results to the results vector and keep track of which
1049 /// blocks are visited in 'Visited'.
1051 /// This has special behavior for the first block queries (when SkipFirstBlock
1052 /// is true). In this special case, it ignores the contents of the specified
1053 /// block and starts returning dependence info for its predecessors.
1055 /// This function returns true on success, or false to indicate that it could
1056 /// not compute dependence information for some reason. This should be treated
1057 /// as a clobber dependence on the first instruction in the predecessor block.
1058 bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
1059 Instruction *QueryInst, const PHITransAddr &Pointer,
1060 const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB,
1061 SmallVectorImpl<NonLocalDepResult> &Result,
1062 DenseMap<BasicBlock *, Value *> &Visited, bool SkipFirstBlock) {
1063 // Look up the cached info for Pointer.
1064 ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
1066 // Set up a temporary NLPI value. If the map doesn't yet have an entry for
1067 // CacheKey, this value will be inserted as the associated value. Otherwise,
1068 // it'll be ignored, and we'll have to check to see if the cached size and
1069 // aa tags are consistent with the current query.
1070 NonLocalPointerInfo InitialNLPI;
1071 InitialNLPI.Size = Loc.Size;
1072 InitialNLPI.AATags = Loc.AATags;
1074 // Get the NLPI for CacheKey, inserting one into the map if it doesn't
1075 // already have one.
1076 std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
1077 NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
1078 NonLocalPointerInfo *CacheInfo = &Pair.first->second;
1080 // If we already have a cache entry for this CacheKey, we may need to do some
1081 // work to reconcile the cache entry and the current query.
1083 if (CacheInfo->Size < Loc.Size) {
1084 // The query's Size is greater than the cached one. Throw out the
1085 // cached data and proceed with the query at the greater size.
1086 CacheInfo->Pair = BBSkipFirstBlockPair();
1087 CacheInfo->Size = Loc.Size;
1088 for (auto &Entry : CacheInfo->NonLocalDeps)
1089 if (Instruction *Inst = Entry.getResult().getInst())
1090 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1091 CacheInfo->NonLocalDeps.clear();
1092 } else if (CacheInfo->Size > Loc.Size) {
1093 // This query's Size is less than the cached one. Conservatively restart
1094 // the query using the greater size.
1095 return getNonLocalPointerDepFromBB(
1096 QueryInst, Pointer, Loc.getWithNewSize(CacheInfo->Size), isLoad,
1097 StartBB, Result, Visited, SkipFirstBlock);
1100 // If the query's AATags are inconsistent with the cached one,
1101 // conservatively throw out the cached data and restart the query with
1102 // no tag if needed.
1103 if (CacheInfo->AATags != Loc.AATags) {
1104 if (CacheInfo->AATags) {
1105 CacheInfo->Pair = BBSkipFirstBlockPair();
1106 CacheInfo->AATags = AAMDNodes();
1107 for (auto &Entry : CacheInfo->NonLocalDeps)
1108 if (Instruction *Inst = Entry.getResult().getInst())
1109 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1110 CacheInfo->NonLocalDeps.clear();
1113 return getNonLocalPointerDepFromBB(
1114 QueryInst, Pointer, Loc.getWithoutAATags(), isLoad, StartBB, Result,
1115 Visited, SkipFirstBlock);
1119 NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
1121 // If we have valid cached information for exactly the block we are
1122 // investigating, just return it with no recomputation.
1123 if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
1124 // We have a fully cached result for this query then we can just return the
1125 // cached results and populate the visited set. However, we have to verify
1126 // that we don't already have conflicting results for these blocks. Check
1127 // to ensure that if a block in the results set is in the visited set that
1128 // it was for the same pointer query.
1129 if (!Visited.empty()) {
1130 for (auto &Entry : *Cache) {
1131 DenseMap<BasicBlock *, Value *>::iterator VI =
1132 Visited.find(Entry.getBB());
1133 if (VI == Visited.end() || VI->second == Pointer.getAddr())
1136 // We have a pointer mismatch in a block. Just return false, saying
1137 // that something was clobbered in this result. We could also do a
1138 // non-fully cached query, but there is little point in doing this.
1143 Value *Addr = Pointer.getAddr();
1144 for (auto &Entry : *Cache) {
1145 Visited.insert(std::make_pair(Entry.getBB(), Addr));
1146 if (Entry.getResult().isNonLocal()) {
1150 if (DT.isReachableFromEntry(Entry.getBB())) {
1152 NonLocalDepResult(Entry.getBB(), Entry.getResult(), Addr));
1155 ++NumCacheCompleteNonLocalPtr;
1159 // Otherwise, either this is a new block, a block with an invalid cache
1160 // pointer or one that we're about to invalidate by putting more info into it
1161 // than its valid cache info. If empty, the result will be valid cache info,
1162 // otherwise it isn't.
1164 CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
1166 CacheInfo->Pair = BBSkipFirstBlockPair();
1168 SmallVector<BasicBlock *, 32> Worklist;
1169 Worklist.push_back(StartBB);
1171 // PredList used inside loop.
1172 SmallVector<std::pair<BasicBlock *, PHITransAddr>, 16> PredList;
1174 // Keep track of the entries that we know are sorted. Previously cached
1175 // entries will all be sorted. The entries we add we only sort on demand (we
1176 // don't insert every element into its sorted position). We know that we
1177 // won't get any reuse from currently inserted values, because we don't
1178 // revisit blocks after we insert info for them.
1179 unsigned NumSortedEntries = Cache->size();
1180 unsigned WorklistEntries = BlockNumberLimit;
1181 bool GotWorklistLimit = false;
1182 DEBUG(AssertSorted(*Cache));
1184 while (!Worklist.empty()) {
1185 BasicBlock *BB = Worklist.pop_back_val();
1187 // If we do process a large number of blocks it becomes very expensive and
1188 // likely it isn't worth worrying about
1189 if (Result.size() > NumResultsLimit) {
1191 // Sort it now (if needed) so that recursive invocations of
1192 // getNonLocalPointerDepFromBB and other routines that could reuse the
1193 // cache value will only see properly sorted cache arrays.
1194 if (Cache && NumSortedEntries != Cache->size()) {
1195 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1197 // Since we bail out, the "Cache" set won't contain all of the
1198 // results for the query. This is ok (we can still use it to accelerate
1199 // specific block queries) but we can't do the fastpath "return all
1200 // results from the set". Clear out the indicator for this.
1201 CacheInfo->Pair = BBSkipFirstBlockPair();
1205 // Skip the first block if we have it.
1206 if (!SkipFirstBlock) {
1207 // Analyze the dependency of *Pointer in FromBB. See if we already have
1209 assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
1211 // Get the dependency info for Pointer in BB. If we have cached
1212 // information, we will use it, otherwise we compute it.
1213 DEBUG(AssertSorted(*Cache, NumSortedEntries));
1214 MemDepResult Dep = GetNonLocalInfoForBlock(QueryInst, Loc, isLoad, BB,
1215 Cache, NumSortedEntries);
1217 // If we got a Def or Clobber, add this to the list of results.
1218 if (!Dep.isNonLocal()) {
1219 if (DT.isReachableFromEntry(BB)) {
1220 Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
1226 // If 'Pointer' is an instruction defined in this block, then we need to do
1227 // phi translation to change it into a value live in the predecessor block.
1228 // If not, we just add the predecessors to the worklist and scan them with
1229 // the same Pointer.
1230 if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
1231 SkipFirstBlock = false;
1232 SmallVector<BasicBlock *, 16> NewBlocks;
1233 for (BasicBlock *Pred : PredCache.get(BB)) {
1234 // Verify that we haven't looked at this block yet.
1235 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
1236 Visited.insert(std::make_pair(Pred, Pointer.getAddr()));
1237 if (InsertRes.second) {
1238 // First time we've looked at *PI.
1239 NewBlocks.push_back(Pred);
1243 // If we have seen this block before, but it was with a different
1244 // pointer then we have a phi translation failure and we have to treat
1245 // this as a clobber.
1246 if (InsertRes.first->second != Pointer.getAddr()) {
1247 // Make sure to clean up the Visited map before continuing on to
1248 // PredTranslationFailure.
1249 for (unsigned i = 0; i < NewBlocks.size(); i++)
1250 Visited.erase(NewBlocks[i]);
1251 goto PredTranslationFailure;
1254 if (NewBlocks.size() > WorklistEntries) {
1255 // Make sure to clean up the Visited map before continuing on to
1256 // PredTranslationFailure.
1257 for (unsigned i = 0; i < NewBlocks.size(); i++)
1258 Visited.erase(NewBlocks[i]);
1259 GotWorklistLimit = true;
1260 goto PredTranslationFailure;
1262 WorklistEntries -= NewBlocks.size();
1263 Worklist.append(NewBlocks.begin(), NewBlocks.end());
1267 // We do need to do phi translation, if we know ahead of time we can't phi
1268 // translate this value, don't even try.
1269 if (!Pointer.IsPotentiallyPHITranslatable())
1270 goto PredTranslationFailure;
1272 // We may have added values to the cache list before this PHI translation.
1273 // If so, we haven't done anything to ensure that the cache remains sorted.
1274 // Sort it now (if needed) so that recursive invocations of
1275 // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1276 // value will only see properly sorted cache arrays.
1277 if (Cache && NumSortedEntries != Cache->size()) {
1278 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1279 NumSortedEntries = Cache->size();
1284 for (BasicBlock *Pred : PredCache.get(BB)) {
1285 PredList.push_back(std::make_pair(Pred, Pointer));
1287 // Get the PHI translated pointer in this predecessor. This can fail if
1288 // not translatable, in which case the getAddr() returns null.
1289 PHITransAddr &PredPointer = PredList.back().second;
1290 PredPointer.PHITranslateValue(BB, Pred, &DT, /*MustDominate=*/false);
1291 Value *PredPtrVal = PredPointer.getAddr();
1293 // Check to see if we have already visited this pred block with another
1294 // pointer. If so, we can't do this lookup. This failure can occur
1295 // with PHI translation when a critical edge exists and the PHI node in
1296 // the successor translates to a pointer value different than the
1297 // pointer the block was first analyzed with.
1298 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
1299 Visited.insert(std::make_pair(Pred, PredPtrVal));
1301 if (!InsertRes.second) {
1302 // We found the pred; take it off the list of preds to visit.
1303 PredList.pop_back();
1305 // If the predecessor was visited with PredPtr, then we already did
1306 // the analysis and can ignore it.
1307 if (InsertRes.first->second == PredPtrVal)
1310 // Otherwise, the block was previously analyzed with a different
1311 // pointer. We can't represent the result of this case, so we just
1312 // treat this as a phi translation failure.
1314 // Make sure to clean up the Visited map before continuing on to
1315 // PredTranslationFailure.
1316 for (unsigned i = 0, n = PredList.size(); i < n; ++i)
1317 Visited.erase(PredList[i].first);
1319 goto PredTranslationFailure;
1323 // Actually process results here; this need to be a separate loop to avoid
1324 // calling getNonLocalPointerDepFromBB for blocks we don't want to return
1325 // any results for. (getNonLocalPointerDepFromBB will modify our
1326 // datastructures in ways the code after the PredTranslationFailure label
1328 for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
1329 BasicBlock *Pred = PredList[i].first;
1330 PHITransAddr &PredPointer = PredList[i].second;
1331 Value *PredPtrVal = PredPointer.getAddr();
1333 bool CanTranslate = true;
1334 // If PHI translation was unable to find an available pointer in this
1335 // predecessor, then we have to assume that the pointer is clobbered in
1336 // that predecessor. We can still do PRE of the load, which would insert
1337 // a computation of the pointer in this predecessor.
1339 CanTranslate = false;
1341 // FIXME: it is entirely possible that PHI translating will end up with
1342 // the same value. Consider PHI translating something like:
1343 // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need*
1344 // to recurse here, pedantically speaking.
1346 // If getNonLocalPointerDepFromBB fails here, that means the cached
1347 // result conflicted with the Visited list; we have to conservatively
1348 // assume it is unknown, but this also does not block PRE of the load.
1349 if (!CanTranslate ||
1350 !getNonLocalPointerDepFromBB(QueryInst, PredPointer,
1351 Loc.getWithNewPtr(PredPtrVal), isLoad,
1352 Pred, Result, Visited)) {
1353 // Add the entry to the Result list.
1354 NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
1355 Result.push_back(Entry);
1357 // Since we had a phi translation failure, the cache for CacheKey won't
1358 // include all of the entries that we need to immediately satisfy future
1359 // queries. Mark this in NonLocalPointerDeps by setting the
1360 // BBSkipFirstBlockPair pointer to null. This requires reuse of the
1361 // cached value to do more work but not miss the phi trans failure.
1362 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1363 NLPI.Pair = BBSkipFirstBlockPair();
1368 // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1369 CacheInfo = &NonLocalPointerDeps[CacheKey];
1370 Cache = &CacheInfo->NonLocalDeps;
1371 NumSortedEntries = Cache->size();
1373 // Since we did phi translation, the "Cache" set won't contain all of the
1374 // results for the query. This is ok (we can still use it to accelerate
1375 // specific block queries) but we can't do the fastpath "return all
1376 // results from the set" Clear out the indicator for this.
1377 CacheInfo->Pair = BBSkipFirstBlockPair();
1378 SkipFirstBlock = false;
1381 PredTranslationFailure:
1382 // The following code is "failure"; we can't produce a sane translation
1383 // for the given block. It assumes that we haven't modified any of
1384 // our datastructures while processing the current block.
1387 // Refresh the CacheInfo/Cache pointer if it got invalidated.
1388 CacheInfo = &NonLocalPointerDeps[CacheKey];
1389 Cache = &CacheInfo->NonLocalDeps;
1390 NumSortedEntries = Cache->size();
1393 // Since we failed phi translation, the "Cache" set won't contain all of the
1394 // results for the query. This is ok (we can still use it to accelerate
1395 // specific block queries) but we can't do the fastpath "return all
1396 // results from the set". Clear out the indicator for this.
1397 CacheInfo->Pair = BBSkipFirstBlockPair();
1399 // If *nothing* works, mark the pointer as unknown.
1401 // If this is the magic first block, return this as a clobber of the whole
1402 // incoming value. Since we can't phi translate to one of the predecessors,
1403 // we have to bail out.
1407 bool foundBlock = false;
1408 for (NonLocalDepEntry &I : llvm::reverse(*Cache)) {
1409 if (I.getBB() != BB)
1412 assert((GotWorklistLimit || I.getResult().isNonLocal() ||
1413 !DT.isReachableFromEntry(BB)) &&
1414 "Should only be here with transparent block");
1416 I.setResult(MemDepResult::getUnknown());
1418 NonLocalDepResult(I.getBB(), I.getResult(), Pointer.getAddr()));
1421 (void)foundBlock; (void)GotWorklistLimit;
1422 assert((foundBlock || GotWorklistLimit) && "Current block not in cache?");
1425 // Okay, we're done now. If we added new values to the cache, re-sort it.
1426 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1427 DEBUG(AssertSorted(*Cache));
1431 /// If P exists in CachedNonLocalPointerInfo, remove it.
1432 void MemoryDependenceResults::RemoveCachedNonLocalPointerDependencies(
1433 ValueIsLoadPair P) {
1434 CachedNonLocalPointerInfo::iterator It = NonLocalPointerDeps.find(P);
1435 if (It == NonLocalPointerDeps.end())
1438 // Remove all of the entries in the BB->val map. This involves removing
1439 // instructions from the reverse map.
1440 NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1442 for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1443 Instruction *Target = PInfo[i].getResult().getInst();
1445 continue; // Ignore non-local dep results.
1446 assert(Target->getParent() == PInfo[i].getBB());
1448 // Eliminating the dirty entry from 'Cache', so update the reverse info.
1449 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1452 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1453 NonLocalPointerDeps.erase(It);
1456 void MemoryDependenceResults::invalidateCachedPointerInfo(Value *Ptr) {
1457 // If Ptr isn't really a pointer, just ignore it.
1458 if (!Ptr->getType()->isPointerTy())
1460 // Flush store info for the pointer.
1461 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1462 // Flush load info for the pointer.
1463 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1466 void MemoryDependenceResults::invalidateCachedPredecessors() {
1470 void MemoryDependenceResults::removeInstruction(Instruction *RemInst) {
1471 // Walk through the Non-local dependencies, removing this one as the value
1472 // for any cached queries.
1473 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1474 if (NLDI != NonLocalDeps.end()) {
1475 NonLocalDepInfo &BlockMap = NLDI->second.first;
1476 for (auto &Entry : BlockMap)
1477 if (Instruction *Inst = Entry.getResult().getInst())
1478 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1479 NonLocalDeps.erase(NLDI);
1482 // If we have a cached local dependence query for this instruction, remove it.
1484 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1485 if (LocalDepEntry != LocalDeps.end()) {
1486 // Remove us from DepInst's reverse set now that the local dep info is gone.
1487 if (Instruction *Inst = LocalDepEntry->second.getInst())
1488 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1490 // Remove this local dependency info.
1491 LocalDeps.erase(LocalDepEntry);
1494 // If we have any cached pointer dependencies on this instruction, remove
1495 // them. If the instruction has non-pointer type, then it can't be a pointer
1498 // Remove it from both the load info and the store info. The instruction
1499 // can't be in either of these maps if it is non-pointer.
1500 if (RemInst->getType()->isPointerTy()) {
1501 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1502 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1505 // Loop over all of the things that depend on the instruction we're removing.
1507 SmallVector<std::pair<Instruction *, Instruction *>, 8> ReverseDepsToAdd;
1509 // If we find RemInst as a clobber or Def in any of the maps for other values,
1510 // we need to replace its entry with a dirty version of the instruction after
1511 // it. If RemInst is a terminator, we use a null dirty value.
1513 // Using a dirty version of the instruction after RemInst saves having to scan
1514 // the entire block to get to this point.
1515 MemDepResult NewDirtyVal;
1516 if (!RemInst->isTerminator())
1517 NewDirtyVal = MemDepResult::getDirty(&*++RemInst->getIterator());
1519 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1520 if (ReverseDepIt != ReverseLocalDeps.end()) {
1521 // RemInst can't be the terminator if it has local stuff depending on it.
1522 assert(!ReverseDepIt->second.empty() && !isa<TerminatorInst>(RemInst) &&
1523 "Nothing can locally depend on a terminator");
1525 for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
1526 assert(InstDependingOnRemInst != RemInst &&
1527 "Already removed our local dep info");
1529 LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1531 // Make sure to remember that new things depend on NewDepInst.
1532 assert(NewDirtyVal.getInst() &&
1533 "There is no way something else can have "
1534 "a local dep on this if it is a terminator!");
1535 ReverseDepsToAdd.push_back(
1536 std::make_pair(NewDirtyVal.getInst(), InstDependingOnRemInst));
1539 ReverseLocalDeps.erase(ReverseDepIt);
1541 // Add new reverse deps after scanning the set, to avoid invalidating the
1542 // 'ReverseDeps' reference.
1543 while (!ReverseDepsToAdd.empty()) {
1544 ReverseLocalDeps[ReverseDepsToAdd.back().first].insert(
1545 ReverseDepsToAdd.back().second);
1546 ReverseDepsToAdd.pop_back();
1550 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1551 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1552 for (Instruction *I : ReverseDepIt->second) {
1553 assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
1555 PerInstNLInfo &INLD = NonLocalDeps[I];
1556 // The information is now dirty!
1559 for (auto &Entry : INLD.first) {
1560 if (Entry.getResult().getInst() != RemInst)
1563 // Convert to a dirty entry for the subsequent instruction.
1564 Entry.setResult(NewDirtyVal);
1566 if (Instruction *NextI = NewDirtyVal.getInst())
1567 ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
1571 ReverseNonLocalDeps.erase(ReverseDepIt);
1573 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1574 while (!ReverseDepsToAdd.empty()) {
1575 ReverseNonLocalDeps[ReverseDepsToAdd.back().first].insert(
1576 ReverseDepsToAdd.back().second);
1577 ReverseDepsToAdd.pop_back();
1581 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1582 // value in the NonLocalPointerDeps info.
1583 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1584 ReverseNonLocalPtrDeps.find(RemInst);
1585 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1586 SmallVector<std::pair<Instruction *, ValueIsLoadPair>, 8>
1587 ReversePtrDepsToAdd;
1589 for (ValueIsLoadPair P : ReversePtrDepIt->second) {
1590 assert(P.getPointer() != RemInst &&
1591 "Already removed NonLocalPointerDeps info for RemInst");
1593 NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1595 // The cache is not valid for any specific block anymore.
1596 NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1598 // Update any entries for RemInst to use the instruction after it.
1599 for (auto &Entry : NLPDI) {
1600 if (Entry.getResult().getInst() != RemInst)
1603 // Convert to a dirty entry for the subsequent instruction.
1604 Entry.setResult(NewDirtyVal);
1606 if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1607 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1610 // Re-sort the NonLocalDepInfo. Changing the dirty entry to its
1611 // subsequent value may invalidate the sortedness.
1612 std::sort(NLPDI.begin(), NLPDI.end());
1615 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1617 while (!ReversePtrDepsToAdd.empty()) {
1618 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first].insert(
1619 ReversePtrDepsToAdd.back().second);
1620 ReversePtrDepsToAdd.pop_back();
1624 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1625 DEBUG(verifyRemoved(RemInst));
1628 /// Verify that the specified instruction does not occur in our internal data
1631 /// This function verifies by asserting in debug builds.
1632 void MemoryDependenceResults::verifyRemoved(Instruction *D) const {
1634 for (const auto &DepKV : LocalDeps) {
1635 assert(DepKV.first != D && "Inst occurs in data structures");
1636 assert(DepKV.second.getInst() != D && "Inst occurs in data structures");
1639 for (const auto &DepKV : NonLocalPointerDeps) {
1640 assert(DepKV.first.getPointer() != D && "Inst occurs in NLPD map key");
1641 for (const auto &Entry : DepKV.second.NonLocalDeps)
1642 assert(Entry.getResult().getInst() != D && "Inst occurs as NLPD value");
1645 for (const auto &DepKV : NonLocalDeps) {
1646 assert(DepKV.first != D && "Inst occurs in data structures");
1647 const PerInstNLInfo &INLD = DepKV.second;
1648 for (const auto &Entry : INLD.first)
1649 assert(Entry.getResult().getInst() != D &&
1650 "Inst occurs in data structures");
1653 for (const auto &DepKV : ReverseLocalDeps) {
1654 assert(DepKV.first != D && "Inst occurs in data structures");
1655 for (Instruction *Inst : DepKV.second)
1656 assert(Inst != D && "Inst occurs in data structures");
1659 for (const auto &DepKV : ReverseNonLocalDeps) {
1660 assert(DepKV.first != D && "Inst occurs in data structures");
1661 for (Instruction *Inst : DepKV.second)
1662 assert(Inst != D && "Inst occurs in data structures");
1665 for (const auto &DepKV : ReverseNonLocalPtrDeps) {
1666 assert(DepKV.first != D && "Inst occurs in rev NLPD map");
1668 for (ValueIsLoadPair P : DepKV.second)
1669 assert(P != ValueIsLoadPair(D, false) && P != ValueIsLoadPair(D, true) &&
1670 "Inst occurs in ReverseNonLocalPtrDeps map");
1675 char MemoryDependenceAnalysis::PassID;
1677 MemoryDependenceResults
1678 MemoryDependenceAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
1679 auto &AA = AM.getResult<AAManager>(F);
1680 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1681 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1682 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1683 return MemoryDependenceResults(AA, AC, TLI, DT);
1686 char MemoryDependenceWrapperPass::ID = 0;
1688 INITIALIZE_PASS_BEGIN(MemoryDependenceWrapperPass, "memdep",
1689 "Memory Dependence Analysis", false, true)
1690 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1691 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1692 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1693 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1694 INITIALIZE_PASS_END(MemoryDependenceWrapperPass, "memdep",
1695 "Memory Dependence Analysis", false, true)
1697 MemoryDependenceWrapperPass::MemoryDependenceWrapperPass() : FunctionPass(ID) {
1698 initializeMemoryDependenceWrapperPassPass(*PassRegistry::getPassRegistry());
1701 MemoryDependenceWrapperPass::~MemoryDependenceWrapperPass() {}
1703 void MemoryDependenceWrapperPass::releaseMemory() {
1707 void MemoryDependenceWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1708 AU.setPreservesAll();
1709 AU.addRequired<AssumptionCacheTracker>();
1710 AU.addRequired<DominatorTreeWrapperPass>();
1711 AU.addRequiredTransitive<AAResultsWrapperPass>();
1712 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
1715 bool MemoryDependenceWrapperPass::runOnFunction(Function &F) {
1716 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1717 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1718 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1719 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1720 MemDep.emplace(AA, AC, TLI, DT);