1 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation --*- C++ -*-===//
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 #define DEBUG_TYPE "memdep"
18 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Function.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/InstructionSimplify.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/PHITransAddr.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/PredIteratorCache.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Target/TargetData.h"
36 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
37 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
38 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
40 STATISTIC(NumCacheNonLocalPtr,
41 "Number of fully cached non-local ptr responses");
42 STATISTIC(NumCacheDirtyNonLocalPtr,
43 "Number of cached, but dirty, non-local ptr responses");
44 STATISTIC(NumUncacheNonLocalPtr,
45 "Number of uncached non-local ptr responses");
46 STATISTIC(NumCacheCompleteNonLocalPtr,
47 "Number of block queries that were completely cached");
49 char MemoryDependenceAnalysis::ID = 0;
51 // Register this pass...
52 INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep",
53 "Memory Dependence Analysis", false, true)
54 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
55 INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep",
56 "Memory Dependence Analysis", false, true)
58 MemoryDependenceAnalysis::MemoryDependenceAnalysis()
59 : FunctionPass(ID), PredCache(0) {
60 initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry());
62 MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
65 /// Clean up memory in between runs
66 void MemoryDependenceAnalysis::releaseMemory() {
69 NonLocalPointerDeps.clear();
70 ReverseLocalDeps.clear();
71 ReverseNonLocalDeps.clear();
72 ReverseNonLocalPtrDeps.clear();
78 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
80 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
82 AU.addRequiredTransitive<AliasAnalysis>();
85 bool MemoryDependenceAnalysis::runOnFunction(Function &) {
86 AA = &getAnalysis<AliasAnalysis>();
87 TD = getAnalysisIfAvailable<TargetData>();
89 PredCache.reset(new PredIteratorCache());
93 /// RemoveFromReverseMap - This is a helper function that removes Val from
94 /// 'Inst's set in ReverseMap. If the set becomes empty, remove Inst's entry.
95 template <typename KeyTy>
96 static void RemoveFromReverseMap(DenseMap<Instruction*,
97 SmallPtrSet<KeyTy, 4> > &ReverseMap,
98 Instruction *Inst, KeyTy Val) {
99 typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator
100 InstIt = ReverseMap.find(Inst);
101 assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
102 bool Found = InstIt->second.erase(Val);
103 assert(Found && "Invalid reverse map!"); (void)Found;
104 if (InstIt->second.empty())
105 ReverseMap.erase(InstIt);
108 /// GetLocation - If the given instruction references a specific memory
109 /// location, fill in Loc with the details, otherwise set Loc.Ptr to null.
110 /// Return a ModRefInfo value describing the general behavior of the
113 AliasAnalysis::ModRefResult GetLocation(const Instruction *Inst,
114 AliasAnalysis::Location &Loc,
116 if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
117 if (LI->isVolatile()) {
118 Loc = AliasAnalysis::Location();
119 return AliasAnalysis::ModRef;
121 Loc = AA->getLocation(LI);
122 return AliasAnalysis::Ref;
125 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
126 if (SI->isVolatile()) {
127 Loc = AliasAnalysis::Location();
128 return AliasAnalysis::ModRef;
130 Loc = AA->getLocation(SI);
131 return AliasAnalysis::Mod;
134 if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
135 Loc = AA->getLocation(V);
136 return AliasAnalysis::ModRef;
139 if (const CallInst *CI = isFreeCall(Inst)) {
140 // calls to free() deallocate the entire structure
141 Loc = AliasAnalysis::Location(CI->getArgOperand(0));
142 return AliasAnalysis::Mod;
145 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
146 switch (II->getIntrinsicID()) {
147 case Intrinsic::lifetime_start:
148 case Intrinsic::lifetime_end:
149 case Intrinsic::invariant_start:
150 Loc = AliasAnalysis::Location(II->getArgOperand(1),
151 cast<ConstantInt>(II->getArgOperand(0))
153 II->getMetadata(LLVMContext::MD_tbaa));
154 // These intrinsics don't really modify the memory, but returning Mod
155 // will allow them to be handled conservatively.
156 return AliasAnalysis::Mod;
157 case Intrinsic::invariant_end:
158 Loc = AliasAnalysis::Location(II->getArgOperand(2),
159 cast<ConstantInt>(II->getArgOperand(1))
161 II->getMetadata(LLVMContext::MD_tbaa));
162 // These intrinsics don't really modify the memory, but returning Mod
163 // will allow them to be handled conservatively.
164 return AliasAnalysis::Mod;
169 // Otherwise, just do the coarse-grained thing that always works.
170 if (Inst->mayWriteToMemory())
171 return AliasAnalysis::ModRef;
172 if (Inst->mayReadFromMemory())
173 return AliasAnalysis::Ref;
174 return AliasAnalysis::NoModRef;
177 /// getCallSiteDependencyFrom - Private helper for finding the local
178 /// dependencies of a call site.
179 MemDepResult MemoryDependenceAnalysis::
180 getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
181 BasicBlock::iterator ScanIt, BasicBlock *BB) {
182 // Walk backwards through the block, looking for dependencies
183 while (ScanIt != BB->begin()) {
184 Instruction *Inst = --ScanIt;
186 // If this inst is a memory op, get the pointer it accessed
187 AliasAnalysis::Location Loc;
188 AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA);
190 // A simple instruction.
191 if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef)
192 return MemDepResult::getClobber(Inst);
196 if (CallSite InstCS = cast<Value>(Inst)) {
197 // Debug intrinsics don't cause dependences.
198 if (isa<DbgInfoIntrinsic>(Inst)) continue;
199 // If these two calls do not interfere, look past it.
200 switch (AA->getModRefInfo(CS, InstCS)) {
201 case AliasAnalysis::NoModRef:
202 // If the two calls are the same, return InstCS as a Def, so that
203 // CS can be found redundant and eliminated.
204 if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) &&
205 CS.getInstruction()->isIdenticalToWhenDefined(Inst))
206 return MemDepResult::getDef(Inst);
208 // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
212 return MemDepResult::getClobber(Inst);
217 // No dependence found. If this is the entry block of the function, it is a
218 // clobber, otherwise it is non-local.
219 if (BB != &BB->getParent()->getEntryBlock())
220 return MemDepResult::getNonLocal();
221 return MemDepResult::getClobber(ScanIt);
224 /// getPointerDependencyFrom - Return the instruction on which a memory
225 /// location depends. If isLoad is true, this routine ignores may-aliases with
226 /// read-only operations. If isLoad is false, this routine ignores may-aliases
227 /// with reads from read-only locations.
228 MemDepResult MemoryDependenceAnalysis::
229 getPointerDependencyFrom(const AliasAnalysis::Location &MemLoc, bool isLoad,
230 BasicBlock::iterator ScanIt, BasicBlock *BB) {
232 // Walk backwards through the basic block, looking for dependencies.
233 while (ScanIt != BB->begin()) {
234 Instruction *Inst = --ScanIt;
236 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
237 // Debug intrinsics don't (and can't) cause dependences.
238 if (isa<DbgInfoIntrinsic>(II)) continue;
240 // If we reach a lifetime begin or end marker, then the query ends here
241 // because the value is undefined.
242 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
243 // FIXME: This only considers queries directly on the invariant-tagged
244 // pointer, not on query pointers that are indexed off of them. It'd
245 // be nice to handle that at some point.
246 AliasAnalysis::AliasResult R =
247 AA->alias(AliasAnalysis::Location(II->getArgOperand(1)), MemLoc);
248 if (R == AliasAnalysis::MustAlias)
249 return MemDepResult::getDef(II);
254 // Values depend on loads if the pointers are must aliased. This means that
255 // a load depends on another must aliased load from the same value.
256 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
257 AliasAnalysis::Location LoadLoc = AA->getLocation(LI);
259 // If we found a pointer, check if it could be the same as our pointer.
260 AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc);
261 if (R == AliasAnalysis::NoAlias)
265 // Must aliased loads are defs of each other.
266 if (R == AliasAnalysis::MustAlias)
267 return MemDepResult::getDef(Inst);
269 // If we have a partial alias, then return this as a clobber for the
271 if (R == AliasAnalysis::PartialAlias)
272 return MemDepResult::getClobber(Inst);
274 // Random may-alias loads don't depend on each other without a
279 // Stores don't alias loads from read-only memory.
280 if (AA->pointsToConstantMemory(LoadLoc))
283 // Stores depend on may/must aliased loads.
284 return MemDepResult::getDef(Inst);
287 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
288 // If alias analysis can tell that this store is guaranteed to not modify
289 // the query pointer, ignore it. Use getModRefInfo to handle cases where
290 // the query pointer points to constant memory etc.
291 if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
294 // Ok, this store might clobber the query pointer. Check to see if it is
295 // a must alias: in this case, we want to return this as a def.
296 AliasAnalysis::Location StoreLoc = AA->getLocation(SI);
298 // If we found a pointer, check if it could be the same as our pointer.
299 AliasAnalysis::AliasResult R = AA->alias(StoreLoc, MemLoc);
301 if (R == AliasAnalysis::NoAlias)
303 if (R == AliasAnalysis::MustAlias)
304 return MemDepResult::getDef(Inst);
305 return MemDepResult::getClobber(Inst);
308 // If this is an allocation, and if we know that the accessed pointer is to
309 // the allocation, return Def. This means that there is no dependence and
310 // the access can be optimized based on that. For example, a load could
312 // Note: Only determine this to be a malloc if Inst is the malloc call, not
313 // a subsequent bitcast of the malloc call result. There can be stores to
314 // the malloced memory between the malloc call and its bitcast uses, and we
315 // need to continue scanning until the malloc call.
316 if (isa<AllocaInst>(Inst) ||
317 (isa<CallInst>(Inst) && extractMallocCall(Inst))) {
318 const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, TD);
320 if (AccessPtr == Inst ||
321 AA->alias(Inst, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
322 return MemDepResult::getDef(Inst);
326 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
327 switch (AA->getModRefInfo(Inst, MemLoc)) {
328 case AliasAnalysis::NoModRef:
329 // If the call has no effect on the queried pointer, just ignore it.
331 case AliasAnalysis::Mod:
332 return MemDepResult::getClobber(Inst);
333 case AliasAnalysis::Ref:
334 // If the call is known to never store to the pointer, and if this is a
335 // load query, we can safely ignore it (scan past it).
339 // Otherwise, there is a potential dependence. Return a clobber.
340 return MemDepResult::getClobber(Inst);
344 // No dependence found. If this is the entry block of the function, it is a
345 // clobber, otherwise it is non-local.
346 if (BB != &BB->getParent()->getEntryBlock())
347 return MemDepResult::getNonLocal();
348 return MemDepResult::getClobber(ScanIt);
351 /// getDependency - Return the instruction on which a memory operation
353 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
354 Instruction *ScanPos = QueryInst;
356 // Check for a cached result
357 MemDepResult &LocalCache = LocalDeps[QueryInst];
359 // If the cached entry is non-dirty, just return it. Note that this depends
360 // on MemDepResult's default constructing to 'dirty'.
361 if (!LocalCache.isDirty())
364 // Otherwise, if we have a dirty entry, we know we can start the scan at that
365 // instruction, which may save us some work.
366 if (Instruction *Inst = LocalCache.getInst()) {
369 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
372 BasicBlock *QueryParent = QueryInst->getParent();
375 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
376 // No dependence found. If this is the entry block of the function, it is a
377 // clobber, otherwise it is non-local.
378 if (QueryParent != &QueryParent->getParent()->getEntryBlock())
379 LocalCache = MemDepResult::getNonLocal();
381 LocalCache = MemDepResult::getClobber(QueryInst);
383 AliasAnalysis::Location MemLoc;
384 AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
386 // If we can do a pointer scan, make it happen.
387 bool isLoad = !(MR & AliasAnalysis::Mod);
388 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
389 isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_end;
391 LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
393 } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
394 CallSite QueryCS(QueryInst);
395 bool isReadOnly = AA->onlyReadsMemory(QueryCS);
396 LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
399 // Non-memory instruction.
400 LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
403 // Remember the result!
404 if (Instruction *I = LocalCache.getInst())
405 ReverseLocalDeps[I].insert(QueryInst);
411 /// AssertSorted - This method is used when -debug is specified to verify that
412 /// cache arrays are properly kept sorted.
413 static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
415 if (Count == -1) Count = Cache.size();
416 if (Count == 0) return;
418 for (unsigned i = 1; i != unsigned(Count); ++i)
419 assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
423 /// getNonLocalCallDependency - Perform a full dependency query for the
424 /// specified call, returning the set of blocks that the value is
425 /// potentially live across. The returned set of results will include a
426 /// "NonLocal" result for all blocks where the value is live across.
428 /// This method assumes the instruction returns a "NonLocal" dependency
429 /// within its own block.
431 /// This returns a reference to an internal data structure that may be
432 /// invalidated on the next non-local query or when an instruction is
433 /// removed. Clients must copy this data if they want it around longer than
435 const MemoryDependenceAnalysis::NonLocalDepInfo &
436 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
437 assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
438 "getNonLocalCallDependency should only be used on calls with non-local deps!");
439 PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
440 NonLocalDepInfo &Cache = CacheP.first;
442 /// DirtyBlocks - This is the set of blocks that need to be recomputed. In
443 /// the cached case, this can happen due to instructions being deleted etc. In
444 /// the uncached case, this starts out as the set of predecessors we care
446 SmallVector<BasicBlock*, 32> DirtyBlocks;
448 if (!Cache.empty()) {
449 // Okay, we have a cache entry. If we know it is not dirty, just return it
450 // with no computation.
451 if (!CacheP.second) {
456 // If we already have a partially computed set of results, scan them to
457 // determine what is dirty, seeding our initial DirtyBlocks worklist.
458 for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
460 if (I->getResult().isDirty())
461 DirtyBlocks.push_back(I->getBB());
463 // Sort the cache so that we can do fast binary search lookups below.
464 std::sort(Cache.begin(), Cache.end());
466 ++NumCacheDirtyNonLocal;
467 //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
468 // << Cache.size() << " cached: " << *QueryInst;
470 // Seed DirtyBlocks with each of the preds of QueryInst's block.
471 BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
472 for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
473 DirtyBlocks.push_back(*PI);
474 ++NumUncacheNonLocal;
477 // isReadonlyCall - If this is a read-only call, we can be more aggressive.
478 bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
480 SmallPtrSet<BasicBlock*, 64> Visited;
482 unsigned NumSortedEntries = Cache.size();
483 DEBUG(AssertSorted(Cache));
485 // Iterate while we still have blocks to update.
486 while (!DirtyBlocks.empty()) {
487 BasicBlock *DirtyBB = DirtyBlocks.back();
488 DirtyBlocks.pop_back();
490 // Already processed this block?
491 if (!Visited.insert(DirtyBB))
494 // Do a binary search to see if we already have an entry for this block in
495 // the cache set. If so, find it.
496 DEBUG(AssertSorted(Cache, NumSortedEntries));
497 NonLocalDepInfo::iterator Entry =
498 std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
499 NonLocalDepEntry(DirtyBB));
500 if (Entry != Cache.begin() && prior(Entry)->getBB() == DirtyBB)
503 NonLocalDepEntry *ExistingResult = 0;
504 if (Entry != Cache.begin()+NumSortedEntries &&
505 Entry->getBB() == DirtyBB) {
506 // If we already have an entry, and if it isn't already dirty, the block
508 if (!Entry->getResult().isDirty())
511 // Otherwise, remember this slot so we can update the value.
512 ExistingResult = &*Entry;
515 // If the dirty entry has a pointer, start scanning from it so we don't have
516 // to rescan the entire block.
517 BasicBlock::iterator ScanPos = DirtyBB->end();
518 if (ExistingResult) {
519 if (Instruction *Inst = ExistingResult->getResult().getInst()) {
521 // We're removing QueryInst's use of Inst.
522 RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
523 QueryCS.getInstruction());
527 // Find out if this block has a local dependency for QueryInst.
530 if (ScanPos != DirtyBB->begin()) {
531 Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
532 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
533 // No dependence found. If this is the entry block of the function, it is
534 // a clobber, otherwise it is non-local.
535 Dep = MemDepResult::getNonLocal();
537 Dep = MemDepResult::getClobber(ScanPos);
540 // If we had a dirty entry for the block, update it. Otherwise, just add
543 ExistingResult->setResult(Dep);
545 Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
547 // If the block has a dependency (i.e. it isn't completely transparent to
548 // the value), remember the association!
549 if (!Dep.isNonLocal()) {
550 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
551 // update this when we remove instructions.
552 if (Instruction *Inst = Dep.getInst())
553 ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
556 // If the block *is* completely transparent to the load, we need to check
557 // the predecessors of this block. Add them to our worklist.
558 for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
559 DirtyBlocks.push_back(*PI);
566 /// getNonLocalPointerDependency - Perform a full dependency query for an
567 /// access to the specified (non-volatile) memory location, returning the
568 /// set of instructions that either define or clobber the value.
570 /// This method assumes the pointer has a "NonLocal" dependency within its
573 void MemoryDependenceAnalysis::
574 getNonLocalPointerDependency(const AliasAnalysis::Location &Loc, bool isLoad,
576 SmallVectorImpl<NonLocalDepResult> &Result) {
577 assert(Loc.Ptr->getType()->isPointerTy() &&
578 "Can't get pointer deps of a non-pointer!");
581 PHITransAddr Address(const_cast<Value *>(Loc.Ptr), TD);
583 // This is the set of blocks we've inspected, and the pointer we consider in
584 // each block. Because of critical edges, we currently bail out if querying
585 // a block with multiple different pointers. This can happen during PHI
587 DenseMap<BasicBlock*, Value*> Visited;
588 if (!getNonLocalPointerDepFromBB(Address, Loc, isLoad, FromBB,
589 Result, Visited, true))
592 Result.push_back(NonLocalDepResult(FromBB,
593 MemDepResult::getClobber(FromBB->begin()),
594 const_cast<Value *>(Loc.Ptr)));
597 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
598 /// Pointer/PointeeSize using either cached information in Cache or by doing a
599 /// lookup (which may use dirty cache info if available). If we do a lookup,
600 /// add the result to the cache.
601 MemDepResult MemoryDependenceAnalysis::
602 GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc,
603 bool isLoad, BasicBlock *BB,
604 NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
606 // Do a binary search to see if we already have an entry for this block in
607 // the cache set. If so, find it.
608 NonLocalDepInfo::iterator Entry =
609 std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
610 NonLocalDepEntry(BB));
611 if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
614 NonLocalDepEntry *ExistingResult = 0;
615 if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
616 ExistingResult = &*Entry;
618 // If we have a cached entry, and it is non-dirty, use it as the value for
620 if (ExistingResult && !ExistingResult->getResult().isDirty()) {
621 ++NumCacheNonLocalPtr;
622 return ExistingResult->getResult();
625 // Otherwise, we have to scan for the value. If we have a dirty cache
626 // entry, start scanning from its position, otherwise we scan from the end
628 BasicBlock::iterator ScanPos = BB->end();
629 if (ExistingResult && ExistingResult->getResult().getInst()) {
630 assert(ExistingResult->getResult().getInst()->getParent() == BB &&
631 "Instruction invalidated?");
632 ++NumCacheDirtyNonLocalPtr;
633 ScanPos = ExistingResult->getResult().getInst();
635 // Eliminating the dirty entry from 'Cache', so update the reverse info.
636 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
637 RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
639 ++NumUncacheNonLocalPtr;
642 // Scan the block for the dependency.
643 MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB);
645 // If we had a dirty entry for the block, update it. Otherwise, just add
648 ExistingResult->setResult(Dep);
650 Cache->push_back(NonLocalDepEntry(BB, Dep));
652 // If the block has a dependency (i.e. it isn't completely transparent to
653 // the value), remember the reverse association because we just added it
655 if (Dep.isNonLocal())
658 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
659 // update MemDep when we remove instructions.
660 Instruction *Inst = Dep.getInst();
661 assert(Inst && "Didn't depend on anything?");
662 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
663 ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
667 /// SortNonLocalDepInfoCache - Sort the a NonLocalDepInfo cache, given a certain
668 /// number of elements in the array that are already properly ordered. This is
669 /// optimized for the case when only a few entries are added.
671 SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
672 unsigned NumSortedEntries) {
673 switch (Cache.size() - NumSortedEntries) {
675 // done, no new entries.
678 // Two new entries, insert the last one into place.
679 NonLocalDepEntry Val = Cache.back();
681 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
682 std::upper_bound(Cache.begin(), Cache.end()-1, Val);
683 Cache.insert(Entry, Val);
687 // One new entry, Just insert the new value at the appropriate position.
688 if (Cache.size() != 1) {
689 NonLocalDepEntry Val = Cache.back();
691 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
692 std::upper_bound(Cache.begin(), Cache.end(), Val);
693 Cache.insert(Entry, Val);
697 // Added many values, do a full scale sort.
698 std::sort(Cache.begin(), Cache.end());
703 /// getNonLocalPointerDepFromBB - Perform a dependency query based on
704 /// pointer/pointeesize starting at the end of StartBB. Add any clobber/def
705 /// results to the results vector and keep track of which blocks are visited in
708 /// This has special behavior for the first block queries (when SkipFirstBlock
709 /// is true). In this special case, it ignores the contents of the specified
710 /// block and starts returning dependence info for its predecessors.
712 /// This function returns false on success, or true to indicate that it could
713 /// not compute dependence information for some reason. This should be treated
714 /// as a clobber dependence on the first instruction in the predecessor block.
715 bool MemoryDependenceAnalysis::
716 getNonLocalPointerDepFromBB(const PHITransAddr &Pointer,
717 const AliasAnalysis::Location &Loc,
718 bool isLoad, BasicBlock *StartBB,
719 SmallVectorImpl<NonLocalDepResult> &Result,
720 DenseMap<BasicBlock*, Value*> &Visited,
721 bool SkipFirstBlock) {
723 // Look up the cached info for Pointer.
724 ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
726 // Set up a temporary NLPI value. If the map doesn't yet have an entry for
727 // CacheKey, this value will be inserted as the associated value. Otherwise,
728 // it'll be ignored, and we'll have to check to see if the cached size and
729 // tbaa tag are consistent with the current query.
730 NonLocalPointerInfo InitialNLPI;
731 InitialNLPI.Size = Loc.Size;
732 InitialNLPI.TBAATag = Loc.TBAATag;
734 // Get the NLPI for CacheKey, inserting one into the map if it doesn't
736 std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
737 NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
738 NonLocalPointerInfo *CacheInfo = &Pair.first->second;
740 // If we already have a cache entry for this CacheKey, we may need to do some
741 // work to reconcile the cache entry and the current query.
743 if (CacheInfo->Size < Loc.Size) {
744 // The query's Size is greater than the cached one. Throw out the
745 // cached data and procede with the query at the greater size.
746 CacheInfo->Pair = BBSkipFirstBlockPair();
747 CacheInfo->Size = Loc.Size;
748 for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
749 DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
750 if (Instruction *Inst = DI->getResult().getInst())
751 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
752 CacheInfo->NonLocalDeps.clear();
753 } else if (CacheInfo->Size > Loc.Size) {
754 // This query's Size is less than the cached one. Conservatively restart
755 // the query using the greater size.
756 return getNonLocalPointerDepFromBB(Pointer,
757 Loc.getWithNewSize(CacheInfo->Size),
758 isLoad, StartBB, Result, Visited,
762 // If the query's TBAATag is inconsistent with the cached one,
763 // conservatively throw out the cached data and restart the query with
765 if (CacheInfo->TBAATag != Loc.TBAATag) {
766 if (CacheInfo->TBAATag) {
767 CacheInfo->Pair = BBSkipFirstBlockPair();
768 CacheInfo->TBAATag = 0;
769 for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
770 DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
771 if (Instruction *Inst = DI->getResult().getInst())
772 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
773 CacheInfo->NonLocalDeps.clear();
776 return getNonLocalPointerDepFromBB(Pointer, Loc.getWithoutTBAATag(),
777 isLoad, StartBB, Result, Visited,
782 NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
784 // If we have valid cached information for exactly the block we are
785 // investigating, just return it with no recomputation.
786 if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
787 // We have a fully cached result for this query then we can just return the
788 // cached results and populate the visited set. However, we have to verify
789 // that we don't already have conflicting results for these blocks. Check
790 // to ensure that if a block in the results set is in the visited set that
791 // it was for the same pointer query.
792 if (!Visited.empty()) {
793 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
795 DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
796 if (VI == Visited.end() || VI->second == Pointer.getAddr())
799 // We have a pointer mismatch in a block. Just return clobber, saying
800 // that something was clobbered in this result. We could also do a
801 // non-fully cached query, but there is little point in doing this.
806 Value *Addr = Pointer.getAddr();
807 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
809 Visited.insert(std::make_pair(I->getBB(), Addr));
810 if (!I->getResult().isNonLocal())
811 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
813 ++NumCacheCompleteNonLocalPtr;
817 // Otherwise, either this is a new block, a block with an invalid cache
818 // pointer or one that we're about to invalidate by putting more info into it
819 // than its valid cache info. If empty, the result will be valid cache info,
820 // otherwise it isn't.
822 CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
824 CacheInfo->Pair = BBSkipFirstBlockPair();
826 SmallVector<BasicBlock*, 32> Worklist;
827 Worklist.push_back(StartBB);
829 // Keep track of the entries that we know are sorted. Previously cached
830 // entries will all be sorted. The entries we add we only sort on demand (we
831 // don't insert every element into its sorted position). We know that we
832 // won't get any reuse from currently inserted values, because we don't
833 // revisit blocks after we insert info for them.
834 unsigned NumSortedEntries = Cache->size();
835 DEBUG(AssertSorted(*Cache));
837 while (!Worklist.empty()) {
838 BasicBlock *BB = Worklist.pop_back_val();
840 // Skip the first block if we have it.
841 if (!SkipFirstBlock) {
842 // Analyze the dependency of *Pointer in FromBB. See if we already have
844 assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
846 // Get the dependency info for Pointer in BB. If we have cached
847 // information, we will use it, otherwise we compute it.
848 DEBUG(AssertSorted(*Cache, NumSortedEntries));
849 MemDepResult Dep = GetNonLocalInfoForBlock(Loc, isLoad, BB, Cache,
852 // If we got a Def or Clobber, add this to the list of results.
853 if (!Dep.isNonLocal()) {
854 Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
859 // If 'Pointer' is an instruction defined in this block, then we need to do
860 // phi translation to change it into a value live in the predecessor block.
861 // If not, we just add the predecessors to the worklist and scan them with
863 if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
864 SkipFirstBlock = false;
865 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
866 // Verify that we haven't looked at this block yet.
867 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
868 InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr()));
869 if (InsertRes.second) {
870 // First time we've looked at *PI.
871 Worklist.push_back(*PI);
875 // If we have seen this block before, but it was with a different
876 // pointer then we have a phi translation failure and we have to treat
877 // this as a clobber.
878 if (InsertRes.first->second != Pointer.getAddr())
879 goto PredTranslationFailure;
884 // We do need to do phi translation, if we know ahead of time we can't phi
885 // translate this value, don't even try.
886 if (!Pointer.IsPotentiallyPHITranslatable())
887 goto PredTranslationFailure;
889 // We may have added values to the cache list before this PHI translation.
890 // If so, we haven't done anything to ensure that the cache remains sorted.
891 // Sort it now (if needed) so that recursive invocations of
892 // getNonLocalPointerDepFromBB and other routines that could reuse the cache
893 // value will only see properly sorted cache arrays.
894 if (Cache && NumSortedEntries != Cache->size()) {
895 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
896 NumSortedEntries = Cache->size();
900 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
901 BasicBlock *Pred = *PI;
903 // Get the PHI translated pointer in this predecessor. This can fail if
904 // not translatable, in which case the getAddr() returns null.
905 PHITransAddr PredPointer(Pointer);
906 PredPointer.PHITranslateValue(BB, Pred, 0);
908 Value *PredPtrVal = PredPointer.getAddr();
910 // Check to see if we have already visited this pred block with another
911 // pointer. If so, we can't do this lookup. This failure can occur
912 // with PHI translation when a critical edge exists and the PHI node in
913 // the successor translates to a pointer value different than the
914 // pointer the block was first analyzed with.
915 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
916 InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
918 if (!InsertRes.second) {
919 // If the predecessor was visited with PredPtr, then we already did
920 // the analysis and can ignore it.
921 if (InsertRes.first->second == PredPtrVal)
924 // Otherwise, the block was previously analyzed with a different
925 // pointer. We can't represent the result of this case, so we just
926 // treat this as a phi translation failure.
927 goto PredTranslationFailure;
930 // If PHI translation was unable to find an available pointer in this
931 // predecessor, then we have to assume that the pointer is clobbered in
932 // that predecessor. We can still do PRE of the load, which would insert
933 // a computation of the pointer in this predecessor.
934 if (PredPtrVal == 0) {
935 // Add the entry to the Result list.
936 NonLocalDepResult Entry(Pred,
937 MemDepResult::getClobber(Pred->getTerminator()),
939 Result.push_back(Entry);
941 // Since we had a phi translation failure, the cache for CacheKey won't
942 // include all of the entries that we need to immediately satisfy future
943 // queries. Mark this in NonLocalPointerDeps by setting the
944 // BBSkipFirstBlockPair pointer to null. This requires reuse of the
945 // cached value to do more work but not miss the phi trans failure.
946 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
947 NLPI.Pair = BBSkipFirstBlockPair();
951 // FIXME: it is entirely possible that PHI translating will end up with
952 // the same value. Consider PHI translating something like:
953 // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need*
954 // to recurse here, pedantically speaking.
956 // If we have a problem phi translating, fall through to the code below
957 // to handle the failure condition.
958 if (getNonLocalPointerDepFromBB(PredPointer,
959 Loc.getWithNewPtr(PredPointer.getAddr()),
962 goto PredTranslationFailure;
965 // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
966 CacheInfo = &NonLocalPointerDeps[CacheKey];
967 Cache = &CacheInfo->NonLocalDeps;
968 NumSortedEntries = Cache->size();
970 // Since we did phi translation, the "Cache" set won't contain all of the
971 // results for the query. This is ok (we can still use it to accelerate
972 // specific block queries) but we can't do the fastpath "return all
973 // results from the set" Clear out the indicator for this.
974 CacheInfo->Pair = BBSkipFirstBlockPair();
975 SkipFirstBlock = false;
978 PredTranslationFailure:
981 // Refresh the CacheInfo/Cache pointer if it got invalidated.
982 CacheInfo = &NonLocalPointerDeps[CacheKey];
983 Cache = &CacheInfo->NonLocalDeps;
984 NumSortedEntries = Cache->size();
987 // Since we failed phi translation, the "Cache" set won't contain all of the
988 // results for the query. This is ok (we can still use it to accelerate
989 // specific block queries) but we can't do the fastpath "return all
990 // results from the set". Clear out the indicator for this.
991 CacheInfo->Pair = BBSkipFirstBlockPair();
993 // If *nothing* works, mark the pointer as being clobbered by the first
994 // instruction in this block.
996 // If this is the magic first block, return this as a clobber of the whole
997 // incoming value. Since we can't phi translate to one of the predecessors,
998 // we have to bail out.
1002 for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
1003 assert(I != Cache->rend() && "Didn't find current block??");
1004 if (I->getBB() != BB)
1007 assert(I->getResult().isNonLocal() &&
1008 "Should only be here with transparent block");
1009 I->setResult(MemDepResult::getClobber(BB->begin()));
1010 ReverseNonLocalPtrDeps[BB->begin()].insert(CacheKey);
1011 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
1012 Pointer.getAddr()));
1017 // Okay, we're done now. If we added new values to the cache, re-sort it.
1018 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1019 DEBUG(AssertSorted(*Cache));
1023 /// RemoveCachedNonLocalPointerDependencies - If P exists in
1024 /// CachedNonLocalPointerInfo, remove it.
1025 void MemoryDependenceAnalysis::
1026 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
1027 CachedNonLocalPointerInfo::iterator It =
1028 NonLocalPointerDeps.find(P);
1029 if (It == NonLocalPointerDeps.end()) return;
1031 // Remove all of the entries in the BB->val map. This involves removing
1032 // instructions from the reverse map.
1033 NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1035 for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1036 Instruction *Target = PInfo[i].getResult().getInst();
1037 if (Target == 0) continue; // Ignore non-local dep results.
1038 assert(Target->getParent() == PInfo[i].getBB());
1040 // Eliminating the dirty entry from 'Cache', so update the reverse info.
1041 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1044 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1045 NonLocalPointerDeps.erase(It);
1049 /// invalidateCachedPointerInfo - This method is used to invalidate cached
1050 /// information about the specified pointer, because it may be too
1051 /// conservative in memdep. This is an optional call that can be used when
1052 /// the client detects an equivalence between the pointer and some other
1053 /// value and replaces the other value with ptr. This can make Ptr available
1054 /// in more places that cached info does not necessarily keep.
1055 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
1056 // If Ptr isn't really a pointer, just ignore it.
1057 if (!Ptr->getType()->isPointerTy()) return;
1058 // Flush store info for the pointer.
1059 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1060 // Flush load info for the pointer.
1061 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1064 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
1065 /// This needs to be done when the CFG changes, e.g., due to splitting
1067 void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
1071 /// removeInstruction - Remove an instruction from the dependence analysis,
1072 /// updating the dependence of instructions that previously depended on it.
1073 /// This method attempts to keep the cache coherent using the reverse map.
1074 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
1075 // Walk through the Non-local dependencies, removing this one as the value
1076 // for any cached queries.
1077 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1078 if (NLDI != NonLocalDeps.end()) {
1079 NonLocalDepInfo &BlockMap = NLDI->second.first;
1080 for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
1082 if (Instruction *Inst = DI->getResult().getInst())
1083 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1084 NonLocalDeps.erase(NLDI);
1087 // If we have a cached local dependence query for this instruction, remove it.
1089 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1090 if (LocalDepEntry != LocalDeps.end()) {
1091 // Remove us from DepInst's reverse set now that the local dep info is gone.
1092 if (Instruction *Inst = LocalDepEntry->second.getInst())
1093 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1095 // Remove this local dependency info.
1096 LocalDeps.erase(LocalDepEntry);
1099 // If we have any cached pointer dependencies on this instruction, remove
1100 // them. If the instruction has non-pointer type, then it can't be a pointer
1103 // Remove it from both the load info and the store info. The instruction
1104 // can't be in either of these maps if it is non-pointer.
1105 if (RemInst->getType()->isPointerTy()) {
1106 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1107 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1110 // Loop over all of the things that depend on the instruction we're removing.
1112 SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
1114 // If we find RemInst as a clobber or Def in any of the maps for other values,
1115 // we need to replace its entry with a dirty version of the instruction after
1116 // it. If RemInst is a terminator, we use a null dirty value.
1118 // Using a dirty version of the instruction after RemInst saves having to scan
1119 // the entire block to get to this point.
1120 MemDepResult NewDirtyVal;
1121 if (!RemInst->isTerminator())
1122 NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
1124 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1125 if (ReverseDepIt != ReverseLocalDeps.end()) {
1126 SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
1127 // RemInst can't be the terminator if it has local stuff depending on it.
1128 assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
1129 "Nothing can locally depend on a terminator");
1131 for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
1132 E = ReverseDeps.end(); I != E; ++I) {
1133 Instruction *InstDependingOnRemInst = *I;
1134 assert(InstDependingOnRemInst != RemInst &&
1135 "Already removed our local dep info");
1137 LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1139 // Make sure to remember that new things depend on NewDepInst.
1140 assert(NewDirtyVal.getInst() && "There is no way something else can have "
1141 "a local dep on this if it is a terminator!");
1142 ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
1143 InstDependingOnRemInst));
1146 ReverseLocalDeps.erase(ReverseDepIt);
1148 // Add new reverse deps after scanning the set, to avoid invalidating the
1149 // 'ReverseDeps' reference.
1150 while (!ReverseDepsToAdd.empty()) {
1151 ReverseLocalDeps[ReverseDepsToAdd.back().first]
1152 .insert(ReverseDepsToAdd.back().second);
1153 ReverseDepsToAdd.pop_back();
1157 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1158 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1159 SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
1160 for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
1162 assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
1164 PerInstNLInfo &INLD = NonLocalDeps[*I];
1165 // The information is now dirty!
1168 for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
1169 DE = INLD.first.end(); DI != DE; ++DI) {
1170 if (DI->getResult().getInst() != RemInst) continue;
1172 // Convert to a dirty entry for the subsequent instruction.
1173 DI->setResult(NewDirtyVal);
1175 if (Instruction *NextI = NewDirtyVal.getInst())
1176 ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
1180 ReverseNonLocalDeps.erase(ReverseDepIt);
1182 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1183 while (!ReverseDepsToAdd.empty()) {
1184 ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
1185 .insert(ReverseDepsToAdd.back().second);
1186 ReverseDepsToAdd.pop_back();
1190 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1191 // value in the NonLocalPointerDeps info.
1192 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1193 ReverseNonLocalPtrDeps.find(RemInst);
1194 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1195 SmallPtrSet<ValueIsLoadPair, 4> &Set = ReversePtrDepIt->second;
1196 SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
1198 for (SmallPtrSet<ValueIsLoadPair, 4>::iterator I = Set.begin(),
1199 E = Set.end(); I != E; ++I) {
1200 ValueIsLoadPair P = *I;
1201 assert(P.getPointer() != RemInst &&
1202 "Already removed NonLocalPointerDeps info for RemInst");
1204 NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1206 // The cache is not valid for any specific block anymore.
1207 NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1209 // Update any entries for RemInst to use the instruction after it.
1210 for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
1212 if (DI->getResult().getInst() != RemInst) continue;
1214 // Convert to a dirty entry for the subsequent instruction.
1215 DI->setResult(NewDirtyVal);
1217 if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1218 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1221 // Re-sort the NonLocalDepInfo. Changing the dirty entry to its
1222 // subsequent value may invalidate the sortedness.
1223 std::sort(NLPDI.begin(), NLPDI.end());
1226 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1228 while (!ReversePtrDepsToAdd.empty()) {
1229 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
1230 .insert(ReversePtrDepsToAdd.back().second);
1231 ReversePtrDepsToAdd.pop_back();
1236 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1237 AA->deleteValue(RemInst);
1238 DEBUG(verifyRemoved(RemInst));
1240 /// verifyRemoved - Verify that the specified instruction does not occur
1241 /// in our internal data structures.
1242 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
1243 for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
1244 E = LocalDeps.end(); I != E; ++I) {
1245 assert(I->first != D && "Inst occurs in data structures");
1246 assert(I->second.getInst() != D &&
1247 "Inst occurs in data structures");
1250 for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
1251 E = NonLocalPointerDeps.end(); I != E; ++I) {
1252 assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
1253 const NonLocalDepInfo &Val = I->second.NonLocalDeps;
1254 for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
1256 assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
1259 for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
1260 E = NonLocalDeps.end(); I != E; ++I) {
1261 assert(I->first != D && "Inst occurs in data structures");
1262 const PerInstNLInfo &INLD = I->second;
1263 for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
1264 EE = INLD.first.end(); II != EE; ++II)
1265 assert(II->getResult().getInst() != D && "Inst occurs in data structures");
1268 for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
1269 E = ReverseLocalDeps.end(); I != E; ++I) {
1270 assert(I->first != D && "Inst occurs in data structures");
1271 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1272 EE = I->second.end(); II != EE; ++II)
1273 assert(*II != D && "Inst occurs in data structures");
1276 for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
1277 E = ReverseNonLocalDeps.end();
1279 assert(I->first != D && "Inst occurs in data structures");
1280 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1281 EE = I->second.end(); II != EE; ++II)
1282 assert(*II != D && "Inst occurs in data structures");
1285 for (ReverseNonLocalPtrDepTy::const_iterator
1286 I = ReverseNonLocalPtrDeps.begin(),
1287 E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
1288 assert(I->first != D && "Inst occurs in rev NLPD map");
1290 for (SmallPtrSet<ValueIsLoadPair, 4>::const_iterator II = I->second.begin(),
1291 E = I->second.end(); II != E; ++II)
1292 assert(*II != ValueIsLoadPair(D, false) &&
1293 *II != ValueIsLoadPair(D, true) &&
1294 "Inst occurs in ReverseNonLocalPtrDeps map");