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/Constants.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Function.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Target/TargetData.h"
31 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
32 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
33 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
34 char MemoryDependenceAnalysis::ID = 0;
36 // Register this pass...
37 static RegisterPass<MemoryDependenceAnalysis> X("memdep",
38 "Memory Dependence Analysis", false, true);
40 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
42 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
44 AU.addRequiredTransitive<AliasAnalysis>();
45 AU.addRequiredTransitive<TargetData>();
48 bool MemoryDependenceAnalysis::runOnFunction(Function &) {
49 AA = &getAnalysis<AliasAnalysis>();
50 TD = &getAnalysis<TargetData>();
55 /// getCallSiteDependency - Private helper for finding the local dependencies
57 MemDepResult MemoryDependenceAnalysis::
58 getCallSiteDependency(CallSite C, BasicBlock::iterator ScanIt, BasicBlock *BB) {
60 // Walk backwards through the block, looking for dependencies
61 while (ScanIt != BB->begin()) {
62 Instruction *Inst = --ScanIt;
64 // If this inst is a memory op, get the pointer it accessed
66 uint64_t PointerSize = 0;
67 if (StoreInst *S = dyn_cast<StoreInst>(Inst)) {
68 Pointer = S->getPointerOperand();
69 PointerSize = TD->getTypeStoreSize(S->getOperand(0)->getType());
70 } else if (VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
71 Pointer = V->getOperand(0);
72 PointerSize = TD->getTypeStoreSize(V->getType());
73 } else if (FreeInst *F = dyn_cast<FreeInst>(Inst)) {
74 Pointer = F->getPointerOperand();
76 // FreeInsts erase the entire structure
78 } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
79 if (AA->getModRefBehavior(CallSite::get(Inst)) ==
80 AliasAnalysis::DoesNotAccessMemory)
82 return MemDepResult::get(Inst);
84 // Non-memory instruction.
88 if (AA->getModRefInfo(C, Pointer, PointerSize) != AliasAnalysis::NoModRef)
89 return MemDepResult::get(Inst);
92 // No dependence found.
93 return MemDepResult::getNonLocal();
96 /// getDependencyFrom - Return the instruction on which a memory operation
98 MemDepResult MemoryDependenceAnalysis::
99 getDependencyFrom(Instruction *QueryInst, BasicBlock::iterator ScanIt,
101 // Get the pointer value for which dependence will be determined
103 uint64_t MemSize = 0;
104 bool MemVolatile = false;
106 if (StoreInst* S = dyn_cast<StoreInst>(QueryInst)) {
107 MemPtr = S->getPointerOperand();
108 MemSize = TD->getTypeStoreSize(S->getOperand(0)->getType());
109 MemVolatile = S->isVolatile();
110 } else if (LoadInst* L = dyn_cast<LoadInst>(QueryInst)) {
111 MemPtr = L->getPointerOperand();
112 MemSize = TD->getTypeStoreSize(L->getType());
113 MemVolatile = L->isVolatile();
114 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QueryInst)) {
115 MemPtr = V->getOperand(0);
116 MemSize = TD->getTypeStoreSize(V->getType());
117 } else if (FreeInst* F = dyn_cast<FreeInst>(QueryInst)) {
118 MemPtr = F->getPointerOperand();
119 // FreeInsts erase the entire structure, not just a field.
121 } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst))
122 return getCallSiteDependency(CallSite::get(QueryInst), ScanIt, BB);
123 else // Non-memory instructions depend on nothing.
124 return MemDepResult::getNone();
126 // Walk backwards through the basic block, looking for dependencies
127 while (ScanIt != BB->begin()) {
128 Instruction *Inst = --ScanIt;
130 // If the access is volatile and this is a volatile load/store, return a
133 ((isa<LoadInst>(Inst) && cast<LoadInst>(Inst)->isVolatile()) ||
134 (isa<StoreInst>(Inst) && cast<StoreInst>(Inst)->isVolatile())))
135 return MemDepResult::get(Inst);
137 // Values depend on loads if the pointers are must aliased. This means that
138 // a load depends on another must aliased load from the same value.
139 if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
140 Value *Pointer = L->getPointerOperand();
141 uint64_t PointerSize = TD->getTypeStoreSize(L->getType());
143 // If we found a pointer, check if it could be the same as our pointer
144 AliasAnalysis::AliasResult R =
145 AA->alias(Pointer, PointerSize, MemPtr, MemSize);
147 if (R == AliasAnalysis::NoAlias)
150 // May-alias loads don't depend on each other without a dependence.
151 if (isa<LoadInst>(QueryInst) && R == AliasAnalysis::MayAlias)
153 return MemDepResult::get(Inst);
156 // If this is an allocation, and if we know that the accessed pointer is to
157 // the allocation, return None. This means that there is no dependence and
158 // the access can be optimized based on that. For example, a load could
160 if (AllocationInst *AI = dyn_cast<AllocationInst>(Inst)) {
161 Value *AccessPtr = MemPtr->getUnderlyingObject();
163 if (AccessPtr == AI ||
164 AA->alias(AI, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
165 return MemDepResult::getNone();
169 // See if this instruction mod/ref's the pointer.
170 AliasAnalysis::ModRefResult MRR = AA->getModRefInfo(Inst, MemPtr, MemSize);
172 if (MRR == AliasAnalysis::NoModRef)
175 // Loads don't depend on read-only instructions.
176 if (isa<LoadInst>(QueryInst) && MRR == AliasAnalysis::Ref)
179 // Otherwise, there is a dependence.
180 return MemDepResult::get(Inst);
183 // If we found nothing, return the non-local flag.
184 return MemDepResult::getNonLocal();
187 /// getDependency - Return the instruction on which a memory operation
189 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
190 Instruction *ScanPos = QueryInst;
192 // Check for a cached result
193 MemDepResult &LocalCache = LocalDeps[QueryInst];
195 // If the cached entry is non-dirty, just return it. Note that this depends
196 // on MemDepResult's default constructing to 'dirty'.
197 if (!LocalCache.isDirty())
200 // Otherwise, if we have a dirty entry, we know we can start the scan at that
201 // instruction, which may save us some work.
202 if (Instruction *Inst = LocalCache.getInst()) {
205 SmallPtrSet<Instruction*, 4> &InstMap = ReverseLocalDeps[Inst];
206 InstMap.erase(QueryInst);
208 ReverseLocalDeps.erase(Inst);
212 LocalCache = getDependencyFrom(QueryInst, ScanPos, QueryInst->getParent());
214 // Remember the result!
215 if (Instruction *I = LocalCache.getInst())
216 ReverseLocalDeps[I].insert(QueryInst);
221 /// getNonLocalDependency - Perform a full dependency query for the
222 /// specified instruction, returning the set of blocks that the value is
223 /// potentially live across. The returned set of results will include a
224 /// "NonLocal" result for all blocks where the value is live across.
226 /// This method assumes the instruction returns a "nonlocal" dependency
227 /// within its own block.
229 const MemoryDependenceAnalysis::NonLocalDepInfo &
230 MemoryDependenceAnalysis::getNonLocalDependency(Instruction *QueryInst) {
231 assert(getDependency(QueryInst).isNonLocal() &&
232 "getNonLocalDependency should only be used on insts with non-local deps!");
233 PerInstNLInfo &CacheP = NonLocalDeps[QueryInst];
235 NonLocalDepInfo &Cache = CacheP.first;
237 /// DirtyBlocks - This is the set of blocks that need to be recomputed. In
238 /// the cached case, this can happen due to instructions being deleted etc. In
239 /// the uncached case, this starts out as the set of predecessors we care
241 SmallVector<BasicBlock*, 32> DirtyBlocks;
243 if (!Cache.empty()) {
244 // Okay, we have a cache entry. If we know it is not dirty, just return it
245 // with no computation.
246 if (!CacheP.second) {
251 // If we already have a partially computed set of results, scan them to
252 // determine what is dirty, seeding our initial DirtyBlocks worklist.
253 for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
255 if (I->second.isDirty())
256 DirtyBlocks.push_back(I->first);
258 // Sort the cache so that we can do fast binary search lookups below.
259 std::sort(Cache.begin(), Cache.end());
261 ++NumCacheDirtyNonLocal;
262 //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
263 // << Cache.size() << " cached: " << *QueryInst;
265 // Seed DirtyBlocks with each of the preds of QueryInst's block.
266 BasicBlock *QueryBB = QueryInst->getParent();
267 DirtyBlocks.append(pred_begin(QueryBB), pred_end(QueryBB));
268 NumUncacheNonLocal++;
271 // Visited checked first, vector in sorted order.
272 SmallPtrSet<BasicBlock*, 64> Visited;
274 unsigned NumSortedEntries = Cache.size();
276 // Iterate while we still have blocks to update.
277 while (!DirtyBlocks.empty()) {
278 BasicBlock *DirtyBB = DirtyBlocks.back();
279 DirtyBlocks.pop_back();
281 // Already processed this block?
282 if (!Visited.insert(DirtyBB))
285 // Do a binary search to see if we already have an entry for this block in
286 // the cache set. If so, find it.
287 NonLocalDepInfo::iterator Entry =
288 std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
289 std::make_pair(DirtyBB, MemDepResult()));
290 if (Entry != Cache.begin() && (&*Entry)[-1].first == DirtyBB)
293 MemDepResult *ExistingResult = 0;
294 if (Entry != Cache.begin()+NumSortedEntries &&
295 Entry->first == DirtyBB) {
296 // If we already have an entry, and if it isn't already dirty, the block
298 if (!Entry->second.isDirty())
301 // Otherwise, remember this slot so we can update the value.
302 ExistingResult = &Entry->second;
305 // If the dirty entry has a pointer, start scanning from it so we don't have
306 // to rescan the entire block.
307 BasicBlock::iterator ScanPos = DirtyBB->end();
308 if (ExistingResult) {
309 if (Instruction *Inst = ExistingResult->getInst()) {
312 // We're removing QueryInst's use of Inst.
313 SmallPtrSet<Instruction*, 4> &InstMap = ReverseNonLocalDeps[Inst];
314 InstMap.erase(QueryInst);
315 if (InstMap.empty()) ReverseNonLocalDeps.erase(Inst);
319 // Find out if this block has a local dependency for QueryInst.
320 MemDepResult Dep = getDependencyFrom(QueryInst, ScanPos, DirtyBB);
322 // If we had a dirty entry for the block, update it. Otherwise, just add
325 *ExistingResult = Dep;
327 Cache.push_back(std::make_pair(DirtyBB, Dep));
329 // If the block has a dependency (i.e. it isn't completely transparent to
330 // the value), remember the association!
331 if (!Dep.isNonLocal()) {
332 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
333 // update this when we remove instructions.
334 if (Instruction *Inst = Dep.getInst())
335 ReverseNonLocalDeps[Inst].insert(QueryInst);
338 // If the block *is* completely transparent to the load, we need to check
339 // the predecessors of this block. Add them to our worklist.
340 DirtyBlocks.append(pred_begin(DirtyBB), pred_end(DirtyBB));
347 /// removeInstruction - Remove an instruction from the dependence analysis,
348 /// updating the dependence of instructions that previously depended on it.
349 /// This method attempts to keep the cache coherent using the reverse map.
350 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
351 // Walk through the Non-local dependencies, removing this one as the value
352 // for any cached queries.
353 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
354 if (NLDI != NonLocalDeps.end()) {
355 NonLocalDepInfo &BlockMap = NLDI->second.first;
356 for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
358 if (Instruction *Inst = DI->second.getInst())
359 ReverseNonLocalDeps[Inst].erase(RemInst);
360 NonLocalDeps.erase(NLDI);
363 // If we have a cached local dependence query for this instruction, remove it.
365 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
366 if (LocalDepEntry != LocalDeps.end()) {
367 // Remove us from DepInst's reverse set now that the local dep info is gone.
368 if (Instruction *Inst = LocalDepEntry->second.getInst()) {
369 SmallPtrSet<Instruction*, 4> &RLD = ReverseLocalDeps[Inst];
372 ReverseLocalDeps.erase(Inst);
375 // Remove this local dependency info.
376 LocalDeps.erase(LocalDepEntry);
379 // Loop over all of the things that depend on the instruction we're removing.
381 SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
383 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
384 if (ReverseDepIt != ReverseLocalDeps.end()) {
385 SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
386 // RemInst can't be the terminator if it has stuff depending on it.
387 assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
388 "Nothing can locally depend on a terminator");
390 // Anything that was locally dependent on RemInst is now going to be
391 // dependent on the instruction after RemInst. It will have the dirty flag
392 // set so it will rescan. This saves having to scan the entire block to get
394 Instruction *NewDepInst = next(BasicBlock::iterator(RemInst));
396 for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
397 E = ReverseDeps.end(); I != E; ++I) {
398 Instruction *InstDependingOnRemInst = *I;
399 assert(InstDependingOnRemInst != RemInst &&
400 "Already removed our local dep info");
402 LocalDeps[InstDependingOnRemInst] = MemDepResult::getDirty(NewDepInst);
404 // Make sure to remember that new things depend on NewDepInst.
405 ReverseDepsToAdd.push_back(std::make_pair(NewDepInst,
406 InstDependingOnRemInst));
409 ReverseLocalDeps.erase(ReverseDepIt);
411 // Add new reverse deps after scanning the set, to avoid invalidating the
412 // 'ReverseDeps' reference.
413 while (!ReverseDepsToAdd.empty()) {
414 ReverseLocalDeps[ReverseDepsToAdd.back().first]
415 .insert(ReverseDepsToAdd.back().second);
416 ReverseDepsToAdd.pop_back();
420 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
421 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
422 SmallPtrSet<Instruction*, 4>& set = ReverseDepIt->second;
423 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
425 assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
427 PerInstNLInfo &INLD = NonLocalDeps[*I];
428 // The information is now dirty!
431 for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
432 DE = INLD.first.end(); DI != DE; ++DI) {
433 if (DI->second.getInst() != RemInst) continue;
435 // Convert to a dirty entry for the subsequent instruction.
436 Instruction *NextI = 0;
437 if (!RemInst->isTerminator()) {
438 NextI = next(BasicBlock::iterator(RemInst));
439 ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
441 DI->second = MemDepResult::getDirty(NextI);
445 ReverseNonLocalDeps.erase(ReverseDepIt);
447 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
448 while (!ReverseDepsToAdd.empty()) {
449 ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
450 .insert(ReverseDepsToAdd.back().second);
451 ReverseDepsToAdd.pop_back();
455 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
456 AA->deleteValue(RemInst);
457 DEBUG(verifyRemoved(RemInst));
460 /// verifyRemoved - Verify that the specified instruction does not occur
461 /// in our internal data structures.
462 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
463 for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
464 E = LocalDeps.end(); I != E; ++I) {
465 assert(I->first != D && "Inst occurs in data structures");
466 assert(I->second.getInst() != D &&
467 "Inst occurs in data structures");
470 for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
471 E = NonLocalDeps.end(); I != E; ++I) {
472 assert(I->first != D && "Inst occurs in data structures");
473 const PerInstNLInfo &INLD = I->second;
474 for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
475 EE = INLD.first.end(); II != EE; ++II)
476 assert(II->second.getInst() != D && "Inst occurs in data structures");
479 for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
480 E = ReverseLocalDeps.end(); I != E; ++I) {
481 assert(I->first != D && "Inst occurs in data structures");
482 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
483 EE = I->second.end(); II != EE; ++II)
484 assert(*II != D && "Inst occurs in data structures");
487 for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
488 E = ReverseNonLocalDeps.end();
490 assert(I->first != D && "Inst occurs in data structures");
491 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
492 EE = I->second.end(); II != EE; ++II)
493 assert(*II != D && "Inst occurs in data structures");