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