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 CS, BasicBlock::iterator ScanIt, BasicBlock *BB) {
59 // Walk backwards through the block, looking for dependencies
60 while (ScanIt != BB->begin()) {
61 Instruction *Inst = --ScanIt;
63 // If this inst is a memory op, get the pointer it accessed
65 uint64_t PointerSize = 0;
66 if (StoreInst *S = dyn_cast<StoreInst>(Inst)) {
67 Pointer = S->getPointerOperand();
68 PointerSize = TD->getTypeStoreSize(S->getOperand(0)->getType());
69 } else if (VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
70 Pointer = V->getOperand(0);
71 PointerSize = TD->getTypeStoreSize(V->getType());
72 } else if (FreeInst *F = dyn_cast<FreeInst>(Inst)) {
73 Pointer = F->getPointerOperand();
75 // FreeInsts erase the entire structure
77 } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
78 CallSite InstCS = CallSite::get(Inst);
79 // If these two calls do not interfere, look past it.
80 if (AA->getModRefInfo(CS, InstCS) == AliasAnalysis::NoModRef)
83 // FIXME: If this is a ref/ref result, we should ignore it!
86 // Z = strlen(P); // Z = X
88 // If they interfere, we generally return clobber. However, if they are
89 // calls to the same read-only functions we return Def.
90 if (!AA->onlyReadsMemory(CS) || CS.getCalledFunction() == 0 ||
91 CS.getCalledFunction() != InstCS.getCalledFunction())
92 return MemDepResult::getClobber(Inst);
93 return MemDepResult::getDef(Inst);
95 // Non-memory instruction.
99 if (AA->getModRefInfo(CS, Pointer, PointerSize) != AliasAnalysis::NoModRef)
100 return MemDepResult::getClobber(Inst);
103 // No dependence found.
104 return MemDepResult::getNonLocal();
107 /// getDependencyFrom - Return the instruction on which a memory operation
109 MemDepResult MemoryDependenceAnalysis::
110 getDependencyFrom(Instruction *QueryInst, BasicBlock::iterator ScanIt,
112 // Get the pointer value for which dependence will be determined
114 uint64_t MemSize = 0;
115 bool MemVolatile = false;
117 if (StoreInst* S = dyn_cast<StoreInst>(QueryInst)) {
118 MemPtr = S->getPointerOperand();
119 MemSize = TD->getTypeStoreSize(S->getOperand(0)->getType());
120 MemVolatile = S->isVolatile();
121 } else if (LoadInst* LI = dyn_cast<LoadInst>(QueryInst)) {
122 MemPtr = LI->getPointerOperand();
123 MemSize = TD->getTypeStoreSize(LI->getType());
124 MemVolatile = LI->isVolatile();
125 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QueryInst)) {
126 MemPtr = V->getOperand(0);
127 MemSize = TD->getTypeStoreSize(V->getType());
128 } else if (FreeInst* F = dyn_cast<FreeInst>(QueryInst)) {
129 MemPtr = F->getPointerOperand();
130 // FreeInsts erase the entire structure, not just a field.
133 assert((isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) &&
134 "Can only get dependency info for memory instructions!");
135 return getCallSiteDependency(CallSite::get(QueryInst), ScanIt, BB);
138 // Walk backwards through the basic block, looking for dependencies
139 while (ScanIt != BB->begin()) {
140 Instruction *Inst = --ScanIt;
142 // Values depend on loads if the pointers are must aliased. This means that
143 // a load depends on another must aliased load from the same value.
144 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
145 // If the access is volatile and this is volatile, return a dependence.
146 if (MemVolatile && LI->isVolatile())
147 return MemDepResult::getClobber(LI);
149 Value *Pointer = LI->getPointerOperand();
150 uint64_t PointerSize = TD->getTypeStoreSize(LI->getType());
152 // If we found a pointer, check if it could be the same as our pointer.
153 AliasAnalysis::AliasResult R =
154 AA->alias(Pointer, PointerSize, MemPtr, MemSize);
155 if (R == AliasAnalysis::NoAlias)
158 // May-alias loads don't depend on each other without a dependence.
159 if (isa<LoadInst>(QueryInst) && R == AliasAnalysis::MayAlias)
161 return MemDepResult::getDef(Inst);
164 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
165 // If the access is volatile and this is volatile, return a dependence.
166 if (MemVolatile && SI->isVolatile())
167 return MemDepResult::getClobber(SI);
169 Value *Pointer = SI->getPointerOperand();
170 uint64_t PointerSize = TD->getTypeStoreSize(SI->getOperand(0)->getType());
172 // If we found a pointer, check if it could be the same as our pointer.
173 AliasAnalysis::AliasResult R =
174 AA->alias(Pointer, PointerSize, MemPtr, MemSize);
176 if (R == AliasAnalysis::NoAlias)
178 if (R == AliasAnalysis::MayAlias)
179 return MemDepResult::getClobber(Inst);
180 return MemDepResult::getDef(Inst);
183 // If this is an allocation, and if we know that the accessed pointer is to
184 // the allocation, return Def. This means that there is no dependence and
185 // the access can be optimized based on that. For example, a load could
187 if (AllocationInst *AI = dyn_cast<AllocationInst>(Inst)) {
188 Value *AccessPtr = MemPtr->getUnderlyingObject();
190 if (AccessPtr == AI ||
191 AA->alias(AI, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
192 return MemDepResult::getDef(AI);
196 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
197 if (AA->getModRefInfo(Inst, MemPtr, MemSize) == AliasAnalysis::NoModRef)
200 // Otherwise, there is a dependence.
201 return MemDepResult::getClobber(Inst);
204 // If we found nothing, return the non-local flag.
205 return MemDepResult::getNonLocal();
208 /// getDependency - Return the instruction on which a memory operation
210 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
211 Instruction *ScanPos = QueryInst;
213 // Check for a cached result
214 MemDepResult &LocalCache = LocalDeps[QueryInst];
216 // If the cached entry is non-dirty, just return it. Note that this depends
217 // on MemDepResult's default constructing to 'dirty'.
218 if (!LocalCache.isDirty())
221 // Otherwise, if we have a dirty entry, we know we can start the scan at that
222 // instruction, which may save us some work.
223 if (Instruction *Inst = LocalCache.getInst()) {
226 SmallPtrSet<Instruction*, 4> &InstMap = ReverseLocalDeps[Inst];
227 InstMap.erase(QueryInst);
229 ReverseLocalDeps.erase(Inst);
233 LocalCache = getDependencyFrom(QueryInst, ScanPos, QueryInst->getParent());
235 // Remember the result!
236 if (Instruction *I = LocalCache.getInst())
237 ReverseLocalDeps[I].insert(QueryInst);
242 /// getNonLocalDependency - Perform a full dependency query for the
243 /// specified instruction, returning the set of blocks that the value is
244 /// potentially live across. The returned set of results will include a
245 /// "NonLocal" result for all blocks where the value is live across.
247 /// This method assumes the instruction returns a "nonlocal" dependency
248 /// within its own block.
250 const MemoryDependenceAnalysis::NonLocalDepInfo &
251 MemoryDependenceAnalysis::getNonLocalDependency(Instruction *QueryInst) {
252 assert(getDependency(QueryInst).isNonLocal() &&
253 "getNonLocalDependency should only be used on insts with non-local deps!");
254 PerInstNLInfo &CacheP = NonLocalDeps[QueryInst];
256 NonLocalDepInfo &Cache = CacheP.first;
258 /// DirtyBlocks - This is the set of blocks that need to be recomputed. In
259 /// the cached case, this can happen due to instructions being deleted etc. In
260 /// the uncached case, this starts out as the set of predecessors we care
262 SmallVector<BasicBlock*, 32> DirtyBlocks;
264 if (!Cache.empty()) {
265 // Okay, we have a cache entry. If we know it is not dirty, just return it
266 // with no computation.
267 if (!CacheP.second) {
272 // If we already have a partially computed set of results, scan them to
273 // determine what is dirty, seeding our initial DirtyBlocks worklist.
274 for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
276 if (I->second.isDirty())
277 DirtyBlocks.push_back(I->first);
279 // Sort the cache so that we can do fast binary search lookups below.
280 std::sort(Cache.begin(), Cache.end());
282 ++NumCacheDirtyNonLocal;
283 //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
284 // << Cache.size() << " cached: " << *QueryInst;
286 // Seed DirtyBlocks with each of the preds of QueryInst's block.
287 BasicBlock *QueryBB = QueryInst->getParent();
288 DirtyBlocks.append(pred_begin(QueryBB), pred_end(QueryBB));
289 NumUncacheNonLocal++;
292 // Visited checked first, vector in sorted order.
293 SmallPtrSet<BasicBlock*, 64> Visited;
295 unsigned NumSortedEntries = Cache.size();
297 // Iterate while we still have blocks to update.
298 while (!DirtyBlocks.empty()) {
299 BasicBlock *DirtyBB = DirtyBlocks.back();
300 DirtyBlocks.pop_back();
302 // Already processed this block?
303 if (!Visited.insert(DirtyBB))
306 // Do a binary search to see if we already have an entry for this block in
307 // the cache set. If so, find it.
308 NonLocalDepInfo::iterator Entry =
309 std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
310 std::make_pair(DirtyBB, MemDepResult()));
311 if (Entry != Cache.begin() && (&*Entry)[-1].first == DirtyBB)
314 MemDepResult *ExistingResult = 0;
315 if (Entry != Cache.begin()+NumSortedEntries &&
316 Entry->first == DirtyBB) {
317 // If we already have an entry, and if it isn't already dirty, the block
319 if (!Entry->second.isDirty())
322 // Otherwise, remember this slot so we can update the value.
323 ExistingResult = &Entry->second;
326 // If the dirty entry has a pointer, start scanning from it so we don't have
327 // to rescan the entire block.
328 BasicBlock::iterator ScanPos = DirtyBB->end();
329 if (ExistingResult) {
330 if (Instruction *Inst = ExistingResult->getInst()) {
333 // We're removing QueryInst's use of Inst.
334 SmallPtrSet<Instruction*, 4> &InstMap = ReverseNonLocalDeps[Inst];
335 InstMap.erase(QueryInst);
336 if (InstMap.empty()) ReverseNonLocalDeps.erase(Inst);
340 // Find out if this block has a local dependency for QueryInst.
341 MemDepResult Dep = getDependencyFrom(QueryInst, ScanPos, DirtyBB);
343 // If we had a dirty entry for the block, update it. Otherwise, just add
346 *ExistingResult = Dep;
348 Cache.push_back(std::make_pair(DirtyBB, Dep));
350 // If the block has a dependency (i.e. it isn't completely transparent to
351 // the value), remember the association!
352 if (!Dep.isNonLocal()) {
353 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
354 // update this when we remove instructions.
355 if (Instruction *Inst = Dep.getInst())
356 ReverseNonLocalDeps[Inst].insert(QueryInst);
359 // If the block *is* completely transparent to the load, we need to check
360 // the predecessors of this block. Add them to our worklist.
361 DirtyBlocks.append(pred_begin(DirtyBB), pred_end(DirtyBB));
368 /// removeInstruction - Remove an instruction from the dependence analysis,
369 /// updating the dependence of instructions that previously depended on it.
370 /// This method attempts to keep the cache coherent using the reverse map.
371 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
372 // Walk through the Non-local dependencies, removing this one as the value
373 // for any cached queries.
374 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
375 if (NLDI != NonLocalDeps.end()) {
376 NonLocalDepInfo &BlockMap = NLDI->second.first;
377 for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
379 if (Instruction *Inst = DI->second.getInst())
380 ReverseNonLocalDeps[Inst].erase(RemInst);
381 NonLocalDeps.erase(NLDI);
384 // If we have a cached local dependence query for this instruction, remove it.
386 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
387 if (LocalDepEntry != LocalDeps.end()) {
388 // Remove us from DepInst's reverse set now that the local dep info is gone.
389 if (Instruction *Inst = LocalDepEntry->second.getInst()) {
390 SmallPtrSet<Instruction*, 4> &RLD = ReverseLocalDeps[Inst];
393 ReverseLocalDeps.erase(Inst);
396 // Remove this local dependency info.
397 LocalDeps.erase(LocalDepEntry);
400 // Loop over all of the things that depend on the instruction we're removing.
402 SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
404 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
405 if (ReverseDepIt != ReverseLocalDeps.end()) {
406 SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
407 // RemInst can't be the terminator if it has stuff depending on it.
408 assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
409 "Nothing can locally depend on a terminator");
411 // Anything that was locally dependent on RemInst is now going to be
412 // dependent on the instruction after RemInst. It will have the dirty flag
413 // set so it will rescan. This saves having to scan the entire block to get
415 Instruction *NewDepInst = next(BasicBlock::iterator(RemInst));
417 for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
418 E = ReverseDeps.end(); I != E; ++I) {
419 Instruction *InstDependingOnRemInst = *I;
420 assert(InstDependingOnRemInst != RemInst &&
421 "Already removed our local dep info");
423 LocalDeps[InstDependingOnRemInst] = MemDepResult::getDirty(NewDepInst);
425 // Make sure to remember that new things depend on NewDepInst.
426 ReverseDepsToAdd.push_back(std::make_pair(NewDepInst,
427 InstDependingOnRemInst));
430 ReverseLocalDeps.erase(ReverseDepIt);
432 // Add new reverse deps after scanning the set, to avoid invalidating the
433 // 'ReverseDeps' reference.
434 while (!ReverseDepsToAdd.empty()) {
435 ReverseLocalDeps[ReverseDepsToAdd.back().first]
436 .insert(ReverseDepsToAdd.back().second);
437 ReverseDepsToAdd.pop_back();
441 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
442 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
443 SmallPtrSet<Instruction*, 4>& set = ReverseDepIt->second;
444 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
446 assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
448 PerInstNLInfo &INLD = NonLocalDeps[*I];
449 // The information is now dirty!
452 for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
453 DE = INLD.first.end(); DI != DE; ++DI) {
454 if (DI->second.getInst() != RemInst) continue;
456 // Convert to a dirty entry for the subsequent instruction.
457 Instruction *NextI = 0;
458 if (!RemInst->isTerminator()) {
459 NextI = next(BasicBlock::iterator(RemInst));
460 ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
462 DI->second = MemDepResult::getDirty(NextI);
466 ReverseNonLocalDeps.erase(ReverseDepIt);
468 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
469 while (!ReverseDepsToAdd.empty()) {
470 ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
471 .insert(ReverseDepsToAdd.back().second);
472 ReverseDepsToAdd.pop_back();
476 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
477 AA->deleteValue(RemInst);
478 DEBUG(verifyRemoved(RemInst));
481 /// verifyRemoved - Verify that the specified instruction does not occur
482 /// in our internal data structures.
483 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
484 for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
485 E = LocalDeps.end(); I != E; ++I) {
486 assert(I->first != D && "Inst occurs in data structures");
487 assert(I->second.getInst() != D &&
488 "Inst occurs in data structures");
491 for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
492 E = NonLocalDeps.end(); I != E; ++I) {
493 assert(I->first != D && "Inst occurs in data structures");
494 const PerInstNLInfo &INLD = I->second;
495 for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
496 EE = INLD.first.end(); II != EE; ++II)
497 assert(II->second.getInst() != D && "Inst occurs in data structures");
500 for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
501 E = ReverseLocalDeps.end(); I != E; ++I) {
502 assert(I->first != D && "Inst occurs in data structures");
503 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
504 EE = I->second.end(); II != EE; ++II)
505 assert(*II != D && "Inst occurs in data structures");
508 for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
509 E = ReverseNonLocalDeps.end();
511 assert(I->first != D && "Inst occurs in data structures");
512 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
513 EE = I->second.end(); II != EE; ++II)
514 assert(*II != D && "Inst occurs in data structures");