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 // We can stop before processing PHIs or dbg intrinsics.
426 const BasicBlock::iterator Begin(BB->getFirstNonPHIOrDbg());
427 while (ScanIt != Begin) {
428 Instruction *Inst = --ScanIt;
430 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
431 // Debug intrinsics don't (and can't) cause dependencies.
432 if (isa<DbgInfoIntrinsic>(II)) continue;
434 // Limit the amount of scanning we do so we don't end up with quadratic
435 // running time on extreme testcases.
438 return MemDepResult::getUnknown();
440 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
441 // If we reach a lifetime begin or end marker, then the query ends here
442 // because the value is undefined.
443 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
444 // FIXME: This only considers queries directly on the invariant-tagged
445 // pointer, not on query pointers that are indexed off of them. It'd
446 // be nice to handle that at some point (the right approach is to use
447 // GetPointerBaseWithConstantOffset).
448 if (AA->isMustAlias(AliasAnalysis::Location(II->getArgOperand(1)),
450 return MemDepResult::getDef(II);
455 // Values depend on loads if the pointers are must aliased. This means that
456 // a load depends on another must aliased load from the same value.
457 // One exception is atomic loads: a value can depend on an atomic load that it
458 // does not alias with when this atomic load indicates that another thread may
459 // be accessing the location.
460 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
462 // While volatile access cannot be eliminated, they do not have to clobber
463 // non-aliasing locations, as normal accesses, for example, can be safely
464 // reordered with volatile accesses.
465 if (LI->isVolatile()) {
467 // Original QueryInst *may* be volatile
468 return MemDepResult::getClobber(LI);
469 if (isVolatile(QueryInst))
470 // Ordering required if QueryInst is itself volatile
471 return MemDepResult::getClobber(LI);
472 // Otherwise, volatile doesn't imply any special ordering
475 // Atomic loads have complications involved.
476 // A Monotonic (or higher) load is OK if the query inst is itself not atomic.
477 // An Acquire (or higher) load sets the HasSeenAcquire flag, so that any
478 // release store will know to return getClobber.
479 // FIXME: This is overly conservative.
480 if (LI->isAtomic() && LI->getOrdering() > Unordered) {
482 return MemDepResult::getClobber(LI);
483 if (auto *QueryLI = dyn_cast<LoadInst>(QueryInst)) {
484 if (!QueryLI->isSimple())
485 return MemDepResult::getClobber(LI);
486 } else if (auto *QuerySI = dyn_cast<StoreInst>(QueryInst)) {
487 if (!QuerySI->isSimple())
488 return MemDepResult::getClobber(LI);
489 } else if (QueryInst->mayReadOrWriteMemory()) {
490 return MemDepResult::getClobber(LI);
493 if (isAtLeastAcquire(LI->getOrdering()))
494 HasSeenAcquire = true;
497 AliasAnalysis::Location LoadLoc = AA->getLocation(LI);
499 // If we found a pointer, check if it could be the same as our pointer.
500 AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc);
503 if (R == AliasAnalysis::NoAlias) {
504 // If this is an over-aligned integer load (for example,
505 // "load i8* %P, align 4") see if it would obviously overlap with the
506 // queried location if widened to a larger load (e.g. if the queried
507 // location is 1 byte at P+1). If so, return it as a load/load
508 // clobber result, allowing the client to decide to widen the load if
510 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType()))
511 if (LI->getAlignment()*8 > ITy->getPrimitiveSizeInBits() &&
512 isLoadLoadClobberIfExtendedToFullWidth(MemLoc, MemLocBase,
513 MemLocOffset, LI, DL))
514 return MemDepResult::getClobber(Inst);
519 // Must aliased loads are defs of each other.
520 if (R == AliasAnalysis::MustAlias)
521 return MemDepResult::getDef(Inst);
523 #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads
524 // in terms of clobbering loads, but since it does this by looking
525 // at the clobbering load directly, it doesn't know about any
526 // phi translation that may have happened along the way.
528 // If we have a partial alias, then return this as a clobber for the
530 if (R == AliasAnalysis::PartialAlias)
531 return MemDepResult::getClobber(Inst);
534 // Random may-alias loads don't depend on each other without a
539 // Stores don't depend on other no-aliased accesses.
540 if (R == AliasAnalysis::NoAlias)
543 // Stores don't alias loads from read-only memory.
544 if (AA->pointsToConstantMemory(LoadLoc))
547 // Stores depend on may/must aliased loads.
548 return MemDepResult::getDef(Inst);
551 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
552 // Atomic stores have complications involved.
553 // A Monotonic store is OK if the query inst is itself not atomic.
554 // A Release (or higher) store further requires that no acquire load
556 // FIXME: This is overly conservative.
557 if (!SI->isUnordered()) {
559 return MemDepResult::getClobber(SI);
560 if (auto *QueryLI = dyn_cast<LoadInst>(QueryInst)) {
561 if (!QueryLI->isSimple())
562 return MemDepResult::getClobber(SI);
563 } else if (auto *QuerySI = dyn_cast<StoreInst>(QueryInst)) {
564 if (!QuerySI->isSimple())
565 return MemDepResult::getClobber(SI);
566 } else if (QueryInst->mayReadOrWriteMemory()) {
567 return MemDepResult::getClobber(SI);
570 if (HasSeenAcquire && isAtLeastRelease(SI->getOrdering()))
571 return MemDepResult::getClobber(SI);
574 // FIXME: this is overly conservative.
575 // While volatile access cannot be eliminated, they do not have to clobber
576 // non-aliasing locations, as normal accesses can for example be reordered
577 // with volatile accesses.
578 if (SI->isVolatile())
579 return MemDepResult::getClobber(SI);
581 // If alias analysis can tell that this store is guaranteed to not modify
582 // the query pointer, ignore it. Use getModRefInfo to handle cases where
583 // the query pointer points to constant memory etc.
584 if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
587 // Ok, this store might clobber the query pointer. Check to see if it is
588 // a must alias: in this case, we want to return this as a def.
589 AliasAnalysis::Location StoreLoc = AA->getLocation(SI);
591 // If we found a pointer, check if it could be the same as our pointer.
592 AliasAnalysis::AliasResult R = AA->alias(StoreLoc, MemLoc);
594 if (R == AliasAnalysis::NoAlias)
596 if (R == AliasAnalysis::MustAlias)
597 return MemDepResult::getDef(Inst);
600 return MemDepResult::getClobber(Inst);
603 // If this is an allocation, and if we know that the accessed pointer is to
604 // the allocation, return Def. This means that there is no dependence and
605 // the access can be optimized based on that. For example, a load could
607 // Note: Only determine this to be a malloc if Inst is the malloc call, not
608 // a subsequent bitcast of the malloc call result. There can be stores to
609 // the malloced memory between the malloc call and its bitcast uses, and we
610 // need to continue scanning until the malloc call.
611 const TargetLibraryInfo *TLI = AA->getTargetLibraryInfo();
612 if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, TLI)) {
613 const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL);
615 if (AccessPtr == Inst || AA->isMustAlias(Inst, AccessPtr))
616 return MemDepResult::getDef(Inst);
617 // Be conservative if the accessed pointer may alias the allocation.
618 if (AA->alias(Inst, AccessPtr) != AliasAnalysis::NoAlias)
619 return MemDepResult::getClobber(Inst);
620 // If the allocation is not aliased and does not read memory (like
621 // strdup), it is safe to ignore.
622 if (isa<AllocaInst>(Inst) ||
623 isMallocLikeFn(Inst, TLI) || isCallocLikeFn(Inst, TLI))
627 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
628 AliasAnalysis::ModRefResult MR = AA->getModRefInfo(Inst, MemLoc);
629 // If necessary, perform additional analysis.
630 if (MR == AliasAnalysis::ModRef)
631 MR = AA->callCapturesBefore(Inst, MemLoc, DT);
633 case AliasAnalysis::NoModRef:
634 // If the call has no effect on the queried pointer, just ignore it.
636 case AliasAnalysis::Mod:
637 return MemDepResult::getClobber(Inst);
638 case AliasAnalysis::Ref:
639 // If the call is known to never store to the pointer, and if this is a
640 // load query, we can safely ignore it (scan past it).
644 // Otherwise, there is a potential dependence. Return a clobber.
645 return MemDepResult::getClobber(Inst);
649 // No dependence found. If this is the entry block of the function, it is
650 // unknown, otherwise it is non-local.
651 if (BB != &BB->getParent()->getEntryBlock())
652 return MemDepResult::getNonLocal();
653 return MemDepResult::getNonFuncLocal();
656 /// getDependency - Return the instruction on which a memory operation
658 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
659 Instruction *ScanPos = QueryInst;
661 // Check for a cached result
662 MemDepResult &LocalCache = LocalDeps[QueryInst];
664 // If the cached entry is non-dirty, just return it. Note that this depends
665 // on MemDepResult's default constructing to 'dirty'.
666 if (!LocalCache.isDirty())
669 // Otherwise, if we have a dirty entry, we know we can start the scan at that
670 // instruction, which may save us some work.
671 if (Instruction *Inst = LocalCache.getInst()) {
674 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
677 BasicBlock *QueryParent = QueryInst->getParent();
680 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
681 // No dependence found. If this is the entry block of the function, it is
682 // unknown, otherwise it is non-local.
683 if (QueryParent != &QueryParent->getParent()->getEntryBlock())
684 LocalCache = MemDepResult::getNonLocal();
686 LocalCache = MemDepResult::getNonFuncLocal();
688 AliasAnalysis::Location MemLoc;
689 AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
691 // If we can do a pointer scan, make it happen.
692 bool isLoad = !(MR & AliasAnalysis::Mod);
693 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
694 isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
696 LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
697 QueryParent, QueryInst);
698 } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
699 CallSite QueryCS(QueryInst);
700 bool isReadOnly = AA->onlyReadsMemory(QueryCS);
701 LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
704 // Non-memory instruction.
705 LocalCache = MemDepResult::getUnknown();
708 // Remember the result!
709 if (Instruction *I = LocalCache.getInst())
710 ReverseLocalDeps[I].insert(QueryInst);
716 /// AssertSorted - This method is used when -debug is specified to verify that
717 /// cache arrays are properly kept sorted.
718 static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
720 if (Count == -1) Count = Cache.size();
721 if (Count == 0) return;
723 for (unsigned i = 1; i != unsigned(Count); ++i)
724 assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
728 /// getNonLocalCallDependency - Perform a full dependency query for the
729 /// specified call, returning the set of blocks that the value is
730 /// potentially live across. The returned set of results will include a
731 /// "NonLocal" result for all blocks where the value is live across.
733 /// This method assumes the instruction returns a "NonLocal" dependency
734 /// within its own block.
736 /// This returns a reference to an internal data structure that may be
737 /// invalidated on the next non-local query or when an instruction is
738 /// removed. Clients must copy this data if they want it around longer than
740 const MemoryDependenceAnalysis::NonLocalDepInfo &
741 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
742 assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
743 "getNonLocalCallDependency should only be used on calls with non-local deps!");
744 PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
745 NonLocalDepInfo &Cache = CacheP.first;
747 /// DirtyBlocks - This is the set of blocks that need to be recomputed. In
748 /// the cached case, this can happen due to instructions being deleted etc. In
749 /// the uncached case, this starts out as the set of predecessors we care
751 SmallVector<BasicBlock*, 32> DirtyBlocks;
753 if (!Cache.empty()) {
754 // Okay, we have a cache entry. If we know it is not dirty, just return it
755 // with no computation.
756 if (!CacheP.second) {
761 // If we already have a partially computed set of results, scan them to
762 // determine what is dirty, seeding our initial DirtyBlocks worklist.
763 for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
765 if (I->getResult().isDirty())
766 DirtyBlocks.push_back(I->getBB());
768 // Sort the cache so that we can do fast binary search lookups below.
769 std::sort(Cache.begin(), Cache.end());
771 ++NumCacheDirtyNonLocal;
772 //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
773 // << Cache.size() << " cached: " << *QueryInst;
775 // Seed DirtyBlocks with each of the preds of QueryInst's block.
776 BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
777 for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
778 DirtyBlocks.push_back(*PI);
779 ++NumUncacheNonLocal;
782 // isReadonlyCall - If this is a read-only call, we can be more aggressive.
783 bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
785 SmallPtrSet<BasicBlock*, 64> Visited;
787 unsigned NumSortedEntries = Cache.size();
788 DEBUG(AssertSorted(Cache));
790 // Iterate while we still have blocks to update.
791 while (!DirtyBlocks.empty()) {
792 BasicBlock *DirtyBB = DirtyBlocks.back();
793 DirtyBlocks.pop_back();
795 // Already processed this block?
796 if (!Visited.insert(DirtyBB).second)
799 // Do a binary search to see if we already have an entry for this block in
800 // the cache set. If so, find it.
801 DEBUG(AssertSorted(Cache, NumSortedEntries));
802 NonLocalDepInfo::iterator Entry =
803 std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
804 NonLocalDepEntry(DirtyBB));
805 if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
808 NonLocalDepEntry *ExistingResult = nullptr;
809 if (Entry != Cache.begin()+NumSortedEntries &&
810 Entry->getBB() == DirtyBB) {
811 // If we already have an entry, and if it isn't already dirty, the block
813 if (!Entry->getResult().isDirty())
816 // Otherwise, remember this slot so we can update the value.
817 ExistingResult = &*Entry;
820 // If the dirty entry has a pointer, start scanning from it so we don't have
821 // to rescan the entire block.
822 BasicBlock::iterator ScanPos = DirtyBB->end();
823 if (ExistingResult) {
824 if (Instruction *Inst = ExistingResult->getResult().getInst()) {
826 // We're removing QueryInst's use of Inst.
827 RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
828 QueryCS.getInstruction());
832 // Find out if this block has a local dependency for QueryInst.
835 if (ScanPos != DirtyBB->begin()) {
836 Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
837 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
838 // No dependence found. If this is the entry block of the function, it is
839 // a clobber, otherwise it is unknown.
840 Dep = MemDepResult::getNonLocal();
842 Dep = MemDepResult::getNonFuncLocal();
845 // If we had a dirty entry for the block, update it. Otherwise, just add
848 ExistingResult->setResult(Dep);
850 Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
852 // If the block has a dependency (i.e. it isn't completely transparent to
853 // the value), remember the association!
854 if (!Dep.isNonLocal()) {
855 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
856 // update this when we remove instructions.
857 if (Instruction *Inst = Dep.getInst())
858 ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
861 // If the block *is* completely transparent to the load, we need to check
862 // the predecessors of this block. Add them to our worklist.
863 for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
864 DirtyBlocks.push_back(*PI);
871 /// getNonLocalPointerDependency - Perform a full dependency query for an
872 /// access to the specified (non-volatile) memory location, returning the
873 /// set of instructions that either define or clobber the value.
875 /// This method assumes the pointer has a "NonLocal" dependency within its
878 void MemoryDependenceAnalysis::
879 getNonLocalPointerDependency(Instruction *QueryInst,
880 SmallVectorImpl<NonLocalDepResult> &Result) {
882 auto getLocation = [](AliasAnalysis *AA, Instruction *Inst) {
883 if (auto *I = dyn_cast<LoadInst>(Inst))
884 return AA->getLocation(I);
885 else if (auto *I = dyn_cast<StoreInst>(Inst))
886 return AA->getLocation(I);
887 else if (auto *I = dyn_cast<VAArgInst>(Inst))
888 return AA->getLocation(I);
889 else if (auto *I = dyn_cast<AtomicCmpXchgInst>(Inst))
890 return AA->getLocation(I);
891 else if (auto *I = dyn_cast<AtomicRMWInst>(Inst))
892 return AA->getLocation(I);
894 llvm_unreachable("unsupported memory instruction");
897 const AliasAnalysis::Location Loc = getLocation(AA, QueryInst);
898 bool isLoad = isa<LoadInst>(QueryInst);
899 BasicBlock *FromBB = QueryInst->getParent();
902 assert(Loc.Ptr->getType()->isPointerTy() &&
903 "Can't get pointer deps of a non-pointer!");
906 // This routine does not expect to deal with volatile instructions.
907 // Doing so would require piping through the QueryInst all the way through.
908 // TODO: volatiles can't be elided, but they can be reordered with other
909 // non-volatile accesses.
911 // We currently give up on any instruction which is ordered, but we do handle
912 // atomic instructions which are unordered.
913 // TODO: Handle ordered instructions
914 auto isOrdered = [](Instruction *Inst) {
915 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
916 return !LI->isUnordered();
917 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
918 return !SI->isUnordered();
922 if (isVolatile(QueryInst) || isOrdered(QueryInst)) {
923 Result.push_back(NonLocalDepResult(FromBB,
924 MemDepResult::getUnknown(),
925 const_cast<Value *>(Loc.Ptr)));
930 PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, AC);
932 // This is the set of blocks we've inspected, and the pointer we consider in
933 // each block. Because of critical edges, we currently bail out if querying
934 // a block with multiple different pointers. This can happen during PHI
936 DenseMap<BasicBlock*, Value*> Visited;
937 if (!getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
938 Result, Visited, true))
941 Result.push_back(NonLocalDepResult(FromBB,
942 MemDepResult::getUnknown(),
943 const_cast<Value *>(Loc.Ptr)));
946 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
947 /// Pointer/PointeeSize using either cached information in Cache or by doing a
948 /// lookup (which may use dirty cache info if available). If we do a lookup,
949 /// add the result to the cache.
950 MemDepResult MemoryDependenceAnalysis::
951 GetNonLocalInfoForBlock(Instruction *QueryInst,
952 const AliasAnalysis::Location &Loc,
953 bool isLoad, BasicBlock *BB,
954 NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
956 // Do a binary search to see if we already have an entry for this block in
957 // the cache set. If so, find it.
958 NonLocalDepInfo::iterator Entry =
959 std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
960 NonLocalDepEntry(BB));
961 if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
964 NonLocalDepEntry *ExistingResult = nullptr;
965 if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
966 ExistingResult = &*Entry;
968 // If we have a cached entry, and it is non-dirty, use it as the value for
970 if (ExistingResult && !ExistingResult->getResult().isDirty()) {
971 ++NumCacheNonLocalPtr;
972 return ExistingResult->getResult();
975 // Otherwise, we have to scan for the value. If we have a dirty cache
976 // entry, start scanning from its position, otherwise we scan from the end
978 BasicBlock::iterator ScanPos = BB->end();
979 if (ExistingResult && ExistingResult->getResult().getInst()) {
980 assert(ExistingResult->getResult().getInst()->getParent() == BB &&
981 "Instruction invalidated?");
982 ++NumCacheDirtyNonLocalPtr;
983 ScanPos = ExistingResult->getResult().getInst();
985 // Eliminating the dirty entry from 'Cache', so update the reverse info.
986 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
987 RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
989 ++NumUncacheNonLocalPtr;
992 // Scan the block for the dependency.
993 MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB,
996 // If we had a dirty entry for the block, update it. Otherwise, just add
999 ExistingResult->setResult(Dep);
1001 Cache->push_back(NonLocalDepEntry(BB, Dep));
1003 // If the block has a dependency (i.e. it isn't completely transparent to
1004 // the value), remember the reverse association because we just added it
1006 if (!Dep.isDef() && !Dep.isClobber())
1009 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
1010 // update MemDep when we remove instructions.
1011 Instruction *Inst = Dep.getInst();
1012 assert(Inst && "Didn't depend on anything?");
1013 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
1014 ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
1018 /// SortNonLocalDepInfoCache - Sort the NonLocalDepInfo cache, given a certain
1019 /// number of elements in the array that are already properly ordered. This is
1020 /// optimized for the case when only a few entries are added.
1022 SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
1023 unsigned NumSortedEntries) {
1024 switch (Cache.size() - NumSortedEntries) {
1026 // done, no new entries.
1029 // Two new entries, insert the last one into place.
1030 NonLocalDepEntry Val = Cache.back();
1032 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
1033 std::upper_bound(Cache.begin(), Cache.end()-1, Val);
1034 Cache.insert(Entry, Val);
1038 // One new entry, Just insert the new value at the appropriate position.
1039 if (Cache.size() != 1) {
1040 NonLocalDepEntry Val = Cache.back();
1042 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
1043 std::upper_bound(Cache.begin(), Cache.end(), Val);
1044 Cache.insert(Entry, Val);
1048 // Added many values, do a full scale sort.
1049 std::sort(Cache.begin(), Cache.end());
1054 /// getNonLocalPointerDepFromBB - Perform a dependency query based on
1055 /// pointer/pointeesize starting at the end of StartBB. Add any clobber/def
1056 /// results to the results vector and keep track of which blocks are visited in
1059 /// This has special behavior for the first block queries (when SkipFirstBlock
1060 /// is true). In this special case, it ignores the contents of the specified
1061 /// block and starts returning dependence info for its predecessors.
1063 /// This function returns false on success, or true to indicate that it could
1064 /// not compute dependence information for some reason. This should be treated
1065 /// as a clobber dependence on the first instruction in the predecessor block.
1066 bool MemoryDependenceAnalysis::
1067 getNonLocalPointerDepFromBB(Instruction *QueryInst,
1068 const PHITransAddr &Pointer,
1069 const AliasAnalysis::Location &Loc,
1070 bool isLoad, BasicBlock *StartBB,
1071 SmallVectorImpl<NonLocalDepResult> &Result,
1072 DenseMap<BasicBlock*, Value*> &Visited,
1073 bool SkipFirstBlock) {
1074 // Look up the cached info for Pointer.
1075 ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
1077 // Set up a temporary NLPI value. If the map doesn't yet have an entry for
1078 // CacheKey, this value will be inserted as the associated value. Otherwise,
1079 // it'll be ignored, and we'll have to check to see if the cached size and
1080 // aa tags are consistent with the current query.
1081 NonLocalPointerInfo InitialNLPI;
1082 InitialNLPI.Size = Loc.Size;
1083 InitialNLPI.AATags = Loc.AATags;
1085 // Get the NLPI for CacheKey, inserting one into the map if it doesn't
1086 // already have one.
1087 std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
1088 NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
1089 NonLocalPointerInfo *CacheInfo = &Pair.first->second;
1091 // If we already have a cache entry for this CacheKey, we may need to do some
1092 // work to reconcile the cache entry and the current query.
1094 if (CacheInfo->Size < Loc.Size) {
1095 // The query's Size is greater than the cached one. Throw out the
1096 // cached data and proceed with the query at the greater size.
1097 CacheInfo->Pair = BBSkipFirstBlockPair();
1098 CacheInfo->Size = Loc.Size;
1099 for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
1100 DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
1101 if (Instruction *Inst = DI->getResult().getInst())
1102 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1103 CacheInfo->NonLocalDeps.clear();
1104 } else if (CacheInfo->Size > Loc.Size) {
1105 // This query's Size is less than the cached one. Conservatively restart
1106 // the query using the greater size.
1107 return getNonLocalPointerDepFromBB(QueryInst, Pointer,
1108 Loc.getWithNewSize(CacheInfo->Size),
1109 isLoad, StartBB, Result, Visited,
1113 // If the query's AATags are inconsistent with the cached one,
1114 // conservatively throw out the cached data and restart the query with
1115 // no tag if needed.
1116 if (CacheInfo->AATags != Loc.AATags) {
1117 if (CacheInfo->AATags) {
1118 CacheInfo->Pair = BBSkipFirstBlockPair();
1119 CacheInfo->AATags = AAMDNodes();
1120 for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
1121 DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
1122 if (Instruction *Inst = DI->getResult().getInst())
1123 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1124 CacheInfo->NonLocalDeps.clear();
1127 return getNonLocalPointerDepFromBB(QueryInst,
1128 Pointer, Loc.getWithoutAATags(),
1129 isLoad, StartBB, Result, Visited,
1134 NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
1136 // If we have valid cached information for exactly the block we are
1137 // investigating, just return it with no recomputation.
1138 if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
1139 // We have a fully cached result for this query then we can just return the
1140 // cached results and populate the visited set. However, we have to verify
1141 // that we don't already have conflicting results for these blocks. Check
1142 // to ensure that if a block in the results set is in the visited set that
1143 // it was for the same pointer query.
1144 if (!Visited.empty()) {
1145 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
1147 DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
1148 if (VI == Visited.end() || VI->second == Pointer.getAddr())
1151 // We have a pointer mismatch in a block. Just return clobber, saying
1152 // that something was clobbered in this result. We could also do a
1153 // non-fully cached query, but there is little point in doing this.
1158 Value *Addr = Pointer.getAddr();
1159 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
1161 Visited.insert(std::make_pair(I->getBB(), Addr));
1162 if (I->getResult().isNonLocal()) {
1167 Result.push_back(NonLocalDepResult(I->getBB(),
1168 MemDepResult::getUnknown(),
1170 } else if (DT->isReachableFromEntry(I->getBB())) {
1171 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
1174 ++NumCacheCompleteNonLocalPtr;
1178 // Otherwise, either this is a new block, a block with an invalid cache
1179 // pointer or one that we're about to invalidate by putting more info into it
1180 // than its valid cache info. If empty, the result will be valid cache info,
1181 // otherwise it isn't.
1183 CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
1185 CacheInfo->Pair = BBSkipFirstBlockPair();
1187 SmallVector<BasicBlock*, 32> Worklist;
1188 Worklist.push_back(StartBB);
1190 // PredList used inside loop.
1191 SmallVector<std::pair<BasicBlock*, PHITransAddr>, 16> PredList;
1193 // Keep track of the entries that we know are sorted. Previously cached
1194 // entries will all be sorted. The entries we add we only sort on demand (we
1195 // don't insert every element into its sorted position). We know that we
1196 // won't get any reuse from currently inserted values, because we don't
1197 // revisit blocks after we insert info for them.
1198 unsigned NumSortedEntries = Cache->size();
1199 DEBUG(AssertSorted(*Cache));
1201 while (!Worklist.empty()) {
1202 BasicBlock *BB = Worklist.pop_back_val();
1204 // If we do process a large number of blocks it becomes very expensive and
1205 // likely it isn't worth worrying about
1206 if (Result.size() > NumResultsLimit) {
1208 // Sort it now (if needed) so that recursive invocations of
1209 // getNonLocalPointerDepFromBB and other routines that could reuse the
1210 // cache value will only see properly sorted cache arrays.
1211 if (Cache && NumSortedEntries != Cache->size()) {
1212 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1214 // Since we bail out, the "Cache" set won't contain all of the
1215 // results for the query. This is ok (we can still use it to accelerate
1216 // specific block queries) but we can't do the fastpath "return all
1217 // results from the set". Clear out the indicator for this.
1218 CacheInfo->Pair = BBSkipFirstBlockPair();
1222 // Skip the first block if we have it.
1223 if (!SkipFirstBlock) {
1224 // Analyze the dependency of *Pointer in FromBB. See if we already have
1226 assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
1228 // Get the dependency info for Pointer in BB. If we have cached
1229 // information, we will use it, otherwise we compute it.
1230 DEBUG(AssertSorted(*Cache, NumSortedEntries));
1231 MemDepResult Dep = GetNonLocalInfoForBlock(QueryInst,
1232 Loc, isLoad, BB, Cache,
1235 // If we got a Def or Clobber, add this to the list of results.
1236 if (!Dep.isNonLocal()) {
1238 Result.push_back(NonLocalDepResult(BB,
1239 MemDepResult::getUnknown(),
1240 Pointer.getAddr()));
1242 } else if (DT->isReachableFromEntry(BB)) {
1243 Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
1249 // If 'Pointer' is an instruction defined in this block, then we need to do
1250 // phi translation to change it into a value live in the predecessor block.
1251 // If not, we just add the predecessors to the worklist and scan them with
1252 // the same Pointer.
1253 if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
1254 SkipFirstBlock = false;
1255 SmallVector<BasicBlock*, 16> NewBlocks;
1256 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
1257 // Verify that we haven't looked at this block yet.
1258 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
1259 InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr()));
1260 if (InsertRes.second) {
1261 // First time we've looked at *PI.
1262 NewBlocks.push_back(*PI);
1266 // If we have seen this block before, but it was with a different
1267 // pointer then we have a phi translation failure and we have to treat
1268 // this as a clobber.
1269 if (InsertRes.first->second != Pointer.getAddr()) {
1270 // Make sure to clean up the Visited map before continuing on to
1271 // PredTranslationFailure.
1272 for (unsigned i = 0; i < NewBlocks.size(); i++)
1273 Visited.erase(NewBlocks[i]);
1274 goto PredTranslationFailure;
1277 Worklist.append(NewBlocks.begin(), NewBlocks.end());
1281 // We do need to do phi translation, if we know ahead of time we can't phi
1282 // translate this value, don't even try.
1283 if (!Pointer.IsPotentiallyPHITranslatable())
1284 goto PredTranslationFailure;
1286 // We may have added values to the cache list before this PHI translation.
1287 // If so, we haven't done anything to ensure that the cache remains sorted.
1288 // Sort it now (if needed) so that recursive invocations of
1289 // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1290 // value will only see properly sorted cache arrays.
1291 if (Cache && NumSortedEntries != Cache->size()) {
1292 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1293 NumSortedEntries = Cache->size();
1298 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
1299 BasicBlock *Pred = *PI;
1300 PredList.push_back(std::make_pair(Pred, Pointer));
1302 // Get the PHI translated pointer in this predecessor. This can fail if
1303 // not translatable, in which case the getAddr() returns null.
1304 PHITransAddr &PredPointer = PredList.back().second;
1305 PredPointer.PHITranslateValue(BB, Pred, nullptr);
1307 Value *PredPtrVal = PredPointer.getAddr();
1309 // Check to see if we have already visited this pred block with another
1310 // pointer. If so, we can't do this lookup. This failure can occur
1311 // with PHI translation when a critical edge exists and the PHI node in
1312 // the successor translates to a pointer value different than the
1313 // pointer the block was first analyzed with.
1314 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
1315 InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
1317 if (!InsertRes.second) {
1318 // We found the pred; take it off the list of preds to visit.
1319 PredList.pop_back();
1321 // If the predecessor was visited with PredPtr, then we already did
1322 // the analysis and can ignore it.
1323 if (InsertRes.first->second == PredPtrVal)
1326 // Otherwise, the block was previously analyzed with a different
1327 // pointer. We can't represent the result of this case, so we just
1328 // treat this as a phi translation failure.
1330 // Make sure to clean up the Visited map before continuing on to
1331 // PredTranslationFailure.
1332 for (unsigned i = 0, n = PredList.size(); i < n; ++i)
1333 Visited.erase(PredList[i].first);
1335 goto PredTranslationFailure;
1339 // Actually process results here; this need to be a separate loop to avoid
1340 // calling getNonLocalPointerDepFromBB for blocks we don't want to return
1341 // any results for. (getNonLocalPointerDepFromBB will modify our
1342 // datastructures in ways the code after the PredTranslationFailure label
1344 for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
1345 BasicBlock *Pred = PredList[i].first;
1346 PHITransAddr &PredPointer = PredList[i].second;
1347 Value *PredPtrVal = PredPointer.getAddr();
1349 bool CanTranslate = true;
1350 // If PHI translation was unable to find an available pointer in this
1351 // predecessor, then we have to assume that the pointer is clobbered in
1352 // that predecessor. We can still do PRE of the load, which would insert
1353 // a computation of the pointer in this predecessor.
1355 CanTranslate = false;
1357 // FIXME: it is entirely possible that PHI translating will end up with
1358 // the same value. Consider PHI translating something like:
1359 // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need*
1360 // to recurse here, pedantically speaking.
1362 // If getNonLocalPointerDepFromBB fails here, that means the cached
1363 // result conflicted with the Visited list; we have to conservatively
1364 // assume it is unknown, but this also does not block PRE of the load.
1365 if (!CanTranslate ||
1366 getNonLocalPointerDepFromBB(QueryInst, PredPointer,
1367 Loc.getWithNewPtr(PredPtrVal),
1370 // Add the entry to the Result list.
1371 NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
1372 Result.push_back(Entry);
1374 // Since we had a phi translation failure, the cache for CacheKey won't
1375 // include all of the entries that we need to immediately satisfy future
1376 // queries. Mark this in NonLocalPointerDeps by setting the
1377 // BBSkipFirstBlockPair pointer to null. This requires reuse of the
1378 // cached value to do more work but not miss the phi trans failure.
1379 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1380 NLPI.Pair = BBSkipFirstBlockPair();
1385 // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1386 CacheInfo = &NonLocalPointerDeps[CacheKey];
1387 Cache = &CacheInfo->NonLocalDeps;
1388 NumSortedEntries = Cache->size();
1390 // Since we did phi translation, the "Cache" set won't contain all of the
1391 // results for the query. This is ok (we can still use it to accelerate
1392 // specific block queries) but we can't do the fastpath "return all
1393 // results from the set" Clear out the indicator for this.
1394 CacheInfo->Pair = BBSkipFirstBlockPair();
1395 SkipFirstBlock = false;
1398 PredTranslationFailure:
1399 // The following code is "failure"; we can't produce a sane translation
1400 // for the given block. It assumes that we haven't modified any of
1401 // our datastructures while processing the current block.
1404 // Refresh the CacheInfo/Cache pointer if it got invalidated.
1405 CacheInfo = &NonLocalPointerDeps[CacheKey];
1406 Cache = &CacheInfo->NonLocalDeps;
1407 NumSortedEntries = Cache->size();
1410 // Since we failed phi translation, the "Cache" set won't contain all of the
1411 // results for the query. This is ok (we can still use it to accelerate
1412 // specific block queries) but we can't do the fastpath "return all
1413 // results from the set". Clear out the indicator for this.
1414 CacheInfo->Pair = BBSkipFirstBlockPair();
1416 // If *nothing* works, mark the pointer as unknown.
1418 // If this is the magic first block, return this as a clobber of the whole
1419 // incoming value. Since we can't phi translate to one of the predecessors,
1420 // we have to bail out.
1424 for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
1425 assert(I != Cache->rend() && "Didn't find current block??");
1426 if (I->getBB() != BB)
1429 assert((I->getResult().isNonLocal() || !DT->isReachableFromEntry(BB)) &&
1430 "Should only be here with transparent block");
1431 I->setResult(MemDepResult::getUnknown());
1432 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
1433 Pointer.getAddr()));
1438 // Okay, we're done now. If we added new values to the cache, re-sort it.
1439 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1440 DEBUG(AssertSorted(*Cache));
1444 /// RemoveCachedNonLocalPointerDependencies - If P exists in
1445 /// CachedNonLocalPointerInfo, remove it.
1446 void MemoryDependenceAnalysis::
1447 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
1448 CachedNonLocalPointerInfo::iterator It =
1449 NonLocalPointerDeps.find(P);
1450 if (It == NonLocalPointerDeps.end()) return;
1452 // Remove all of the entries in the BB->val map. This involves removing
1453 // instructions from the reverse map.
1454 NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1456 for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1457 Instruction *Target = PInfo[i].getResult().getInst();
1458 if (!Target) continue; // Ignore non-local dep results.
1459 assert(Target->getParent() == PInfo[i].getBB());
1461 // Eliminating the dirty entry from 'Cache', so update the reverse info.
1462 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1465 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1466 NonLocalPointerDeps.erase(It);
1470 /// invalidateCachedPointerInfo - This method is used to invalidate cached
1471 /// information about the specified pointer, because it may be too
1472 /// conservative in memdep. This is an optional call that can be used when
1473 /// the client detects an equivalence between the pointer and some other
1474 /// value and replaces the other value with ptr. This can make Ptr available
1475 /// in more places that cached info does not necessarily keep.
1476 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
1477 // If Ptr isn't really a pointer, just ignore it.
1478 if (!Ptr->getType()->isPointerTy()) return;
1479 // Flush store info for the pointer.
1480 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1481 // Flush load info for the pointer.
1482 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1485 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
1486 /// This needs to be done when the CFG changes, e.g., due to splitting
1488 void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
1492 /// removeInstruction - Remove an instruction from the dependence analysis,
1493 /// updating the dependence of instructions that previously depended on it.
1494 /// This method attempts to keep the cache coherent using the reverse map.
1495 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
1496 // Walk through the Non-local dependencies, removing this one as the value
1497 // for any cached queries.
1498 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1499 if (NLDI != NonLocalDeps.end()) {
1500 NonLocalDepInfo &BlockMap = NLDI->second.first;
1501 for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
1503 if (Instruction *Inst = DI->getResult().getInst())
1504 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1505 NonLocalDeps.erase(NLDI);
1508 // If we have a cached local dependence query for this instruction, remove it.
1510 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1511 if (LocalDepEntry != LocalDeps.end()) {
1512 // Remove us from DepInst's reverse set now that the local dep info is gone.
1513 if (Instruction *Inst = LocalDepEntry->second.getInst())
1514 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1516 // Remove this local dependency info.
1517 LocalDeps.erase(LocalDepEntry);
1520 // If we have any cached pointer dependencies on this instruction, remove
1521 // them. If the instruction has non-pointer type, then it can't be a pointer
1524 // Remove it from both the load info and the store info. The instruction
1525 // can't be in either of these maps if it is non-pointer.
1526 if (RemInst->getType()->isPointerTy()) {
1527 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1528 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1531 // Loop over all of the things that depend on the instruction we're removing.
1533 SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
1535 // If we find RemInst as a clobber or Def in any of the maps for other values,
1536 // we need to replace its entry with a dirty version of the instruction after
1537 // it. If RemInst is a terminator, we use a null dirty value.
1539 // Using a dirty version of the instruction after RemInst saves having to scan
1540 // the entire block to get to this point.
1541 MemDepResult NewDirtyVal;
1542 if (!RemInst->isTerminator())
1543 NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
1545 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1546 if (ReverseDepIt != ReverseLocalDeps.end()) {
1547 // RemInst can't be the terminator if it has local stuff depending on it.
1548 assert(!ReverseDepIt->second.empty() && !isa<TerminatorInst>(RemInst) &&
1549 "Nothing can locally depend on a terminator");
1551 for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
1552 assert(InstDependingOnRemInst != RemInst &&
1553 "Already removed our local dep info");
1555 LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1557 // Make sure to remember that new things depend on NewDepInst.
1558 assert(NewDirtyVal.getInst() && "There is no way something else can have "
1559 "a local dep on this if it is a terminator!");
1560 ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
1561 InstDependingOnRemInst));
1564 ReverseLocalDeps.erase(ReverseDepIt);
1566 // Add new reverse deps after scanning the set, to avoid invalidating the
1567 // 'ReverseDeps' reference.
1568 while (!ReverseDepsToAdd.empty()) {
1569 ReverseLocalDeps[ReverseDepsToAdd.back().first]
1570 .insert(ReverseDepsToAdd.back().second);
1571 ReverseDepsToAdd.pop_back();
1575 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1576 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1577 for (Instruction *I : ReverseDepIt->second) {
1578 assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
1580 PerInstNLInfo &INLD = NonLocalDeps[I];
1581 // The information is now dirty!
1584 for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
1585 DE = INLD.first.end(); DI != DE; ++DI) {
1586 if (DI->getResult().getInst() != RemInst) continue;
1588 // Convert to a dirty entry for the subsequent instruction.
1589 DI->setResult(NewDirtyVal);
1591 if (Instruction *NextI = NewDirtyVal.getInst())
1592 ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
1596 ReverseNonLocalDeps.erase(ReverseDepIt);
1598 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1599 while (!ReverseDepsToAdd.empty()) {
1600 ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
1601 .insert(ReverseDepsToAdd.back().second);
1602 ReverseDepsToAdd.pop_back();
1606 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1607 // value in the NonLocalPointerDeps info.
1608 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1609 ReverseNonLocalPtrDeps.find(RemInst);
1610 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1611 SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
1613 for (ValueIsLoadPair P : ReversePtrDepIt->second) {
1614 assert(P.getPointer() != RemInst &&
1615 "Already removed NonLocalPointerDeps info for RemInst");
1617 NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1619 // The cache is not valid for any specific block anymore.
1620 NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1622 // Update any entries for RemInst to use the instruction after it.
1623 for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
1625 if (DI->getResult().getInst() != RemInst) continue;
1627 // Convert to a dirty entry for the subsequent instruction.
1628 DI->setResult(NewDirtyVal);
1630 if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1631 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1634 // Re-sort the NonLocalDepInfo. Changing the dirty entry to its
1635 // subsequent value may invalidate the sortedness.
1636 std::sort(NLPDI.begin(), NLPDI.end());
1639 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1641 while (!ReversePtrDepsToAdd.empty()) {
1642 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
1643 .insert(ReversePtrDepsToAdd.back().second);
1644 ReversePtrDepsToAdd.pop_back();
1649 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1650 AA->deleteValue(RemInst);
1651 DEBUG(verifyRemoved(RemInst));
1653 /// verifyRemoved - Verify that the specified instruction does not occur
1654 /// in our internal data structures. This function verifies by asserting in
1656 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
1658 for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
1659 E = LocalDeps.end(); I != E; ++I) {
1660 assert(I->first != D && "Inst occurs in data structures");
1661 assert(I->second.getInst() != D &&
1662 "Inst occurs in data structures");
1665 for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
1666 E = NonLocalPointerDeps.end(); I != E; ++I) {
1667 assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
1668 const NonLocalDepInfo &Val = I->second.NonLocalDeps;
1669 for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
1671 assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
1674 for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
1675 E = NonLocalDeps.end(); I != E; ++I) {
1676 assert(I->first != D && "Inst occurs in data structures");
1677 const PerInstNLInfo &INLD = I->second;
1678 for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
1679 EE = INLD.first.end(); II != EE; ++II)
1680 assert(II->getResult().getInst() != D && "Inst occurs in data structures");
1683 for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
1684 E = ReverseLocalDeps.end(); I != E; ++I) {
1685 assert(I->first != D && "Inst occurs in data structures");
1686 for (Instruction *Inst : I->second)
1687 assert(Inst != D && "Inst occurs in data structures");
1690 for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
1691 E = ReverseNonLocalDeps.end();
1693 assert(I->first != D && "Inst occurs in data structures");
1694 for (Instruction *Inst : I->second)
1695 assert(Inst != D && "Inst occurs in data structures");
1698 for (ReverseNonLocalPtrDepTy::const_iterator
1699 I = ReverseNonLocalPtrDeps.begin(),
1700 E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
1701 assert(I->first != D && "Inst occurs in rev NLPD map");
1703 for (ValueIsLoadPair P : I->second)
1704 assert(P != ValueIsLoadPair(D, false) &&
1705 P != ValueIsLoadPair(D, true) &&
1706 "Inst occurs in ReverseNonLocalPtrDeps map");