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 cached non-local responses");
32 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 /// getCallSiteDependency - Private helper for finding the local dependencies
50 MemoryDependenceAnalysis::DepResultTy MemoryDependenceAnalysis::
51 getCallSiteDependency(CallSite C, BasicBlock::iterator ScanIt,
53 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
54 TargetData &TD = getAnalysis<TargetData>();
56 // Walk backwards through the block, looking for dependencies
57 while (ScanIt != BB->begin()) {
58 Instruction *Inst = --ScanIt;
60 // If this inst is a memory op, get the pointer it accessed
62 uint64_t PointerSize = 0;
63 if (StoreInst *S = dyn_cast<StoreInst>(Inst)) {
64 Pointer = S->getPointerOperand();
65 PointerSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
66 } else if (VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
67 Pointer = V->getOperand(0);
68 PointerSize = TD.getTypeStoreSize(V->getType());
69 } else if (FreeInst *F = dyn_cast<FreeInst>(Inst)) {
70 Pointer = F->getPointerOperand();
72 // FreeInsts erase the entire structure
74 } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
75 if (AA.getModRefBehavior(CallSite::get(Inst)) ==
76 AliasAnalysis::DoesNotAccessMemory)
78 return DepResultTy(Inst, Normal);
80 // Non-memory instruction.
84 if (AA.getModRefInfo(C, Pointer, PointerSize) != AliasAnalysis::NoModRef)
85 return DepResultTy(Inst, Normal);
88 // No dependence found.
89 return DepResultTy(0, NonLocal);
92 /// getDependency - Return the instruction on which a memory operation
93 /// depends. The local parameter indicates if the query should only
94 /// evaluate dependencies within the same basic block.
95 MemoryDependenceAnalysis::DepResultTy MemoryDependenceAnalysis::
96 getDependencyFromInternal(Instruction *QueryInst, BasicBlock::iterator ScanIt,
98 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
99 TargetData &TD = getAnalysis<TargetData>();
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 DepResultTy(0, None);
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 DepResultTy(Inst, Normal);
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 DepResultTy(Inst, Normal);
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 DepResultTy(0, None);
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 DepResultTy(Inst, Normal);
183 // If we found nothing, return the non-local flag.
184 return DepResultTy(0, NonLocal);
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 DepResultTy &LocalCache = LocalDeps[QueryInst];
195 // If the cached entry is non-dirty, just return it. Note that this depends
196 // on DepResultTy's default constructing to 'dirty'.
197 if (LocalCache.getInt() != Dirty)
198 return ConvToResult(LocalCache);
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.getPointer()) {
205 SmallPtrSet<Instruction*, 4> &InstMap = ReverseLocalDeps[Inst];
206 InstMap.erase(QueryInst);
208 ReverseLocalDeps.erase(Inst);
212 LocalCache = getDependencyFromInternal(QueryInst, ScanPos,
213 QueryInst->getParent());
215 // Remember the result!
216 if (Instruction *I = LocalCache.getPointer())
217 ReverseLocalDeps[I].insert(QueryInst);
219 return ConvToResult(LocalCache);
222 /// getNonLocalDependency - Perform a full dependency query for the
223 /// specified instruction, returning the set of blocks that the value is
224 /// potentially live across. The returned set of results will include a
225 /// "NonLocal" result for all blocks where the value is live across.
227 /// This method assumes the instruction returns a "nonlocal" dependency
228 /// within its own block.
230 void MemoryDependenceAnalysis::
231 getNonLocalDependency(Instruction *QueryInst,
232 SmallVectorImpl<std::pair<BasicBlock*,
233 MemDepResult> > &Result) {
234 assert(getDependency(QueryInst).isNonLocal() &&
235 "getNonLocalDependency should only be used on insts with non-local deps!");
236 PerInstNLInfo &CacheP = NonLocalDeps[QueryInst];
237 if (CacheP.getPointer() == 0) CacheP.setPointer(new NonLocalDepInfo());
239 NonLocalDepInfo &Cache = *CacheP.getPointer();
241 /// DirtyBlocks - This is the set of blocks that need to be recomputed. In
242 /// the cached case, this can happen due to instructions being deleted etc. In
243 /// the uncached case, this starts out as the set of predecessors we care
245 SmallVector<BasicBlock*, 32> DirtyBlocks;
247 if (!Cache.empty()) {
248 // If we already have a partially computed set of results, scan them to
249 // determine what is dirty, seeding our initial DirtyBlocks worklist. The
250 // Int bit of CacheP tells us if we have anything dirty.
252 for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
254 if (I->second.getInt() == Dirty)
255 DirtyBlocks.push_back(I->first);
259 //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
260 // << Cache.size() << " cached: " << *QueryInst;
262 // Seed DirtyBlocks with each of the preds of QueryInst's block.
263 BasicBlock *QueryBB = QueryInst->getParent();
264 DirtyBlocks.append(pred_begin(QueryBB), pred_end(QueryBB));
265 NumUncacheNonLocal++;
268 // Iterate while we still have blocks to update.
269 while (!DirtyBlocks.empty()) {
270 BasicBlock *DirtyBB = DirtyBlocks.back();
271 DirtyBlocks.pop_back();
273 // Get the entry for this block. Note that this relies on DepResultTy
274 // default initializing to Dirty.
275 DepResultTy &DirtyBBEntry = Cache[DirtyBB];
277 // If DirtyBBEntry isn't dirty, it ended up on the worklist multiple times.
278 if (DirtyBBEntry.getInt() != Dirty) continue;
280 // If the dirty entry has a pointer, start scanning from it so we don't have
281 // to rescan the entire block.
282 BasicBlock::iterator ScanPos = DirtyBB->end();
283 if (Instruction *Inst = DirtyBBEntry.getPointer()) {
286 // We're removing QueryInst's dependence on Inst.
287 SmallPtrSet<Instruction*, 4> &InstMap = ReverseNonLocalDeps[Inst];
288 InstMap.erase(QueryInst);
289 if (InstMap.empty()) ReverseNonLocalDeps.erase(Inst);
292 // Find out if this block has a local dependency for QueryInst.
293 DirtyBBEntry = getDependencyFromInternal(QueryInst, ScanPos, DirtyBB);
295 // If the block has a dependency (i.e. it isn't completely transparent to
296 // the value), remember it!
297 if (DirtyBBEntry.getInt() != NonLocal) {
298 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
299 // update this when we remove instructions.
300 if (Instruction *Inst = DirtyBBEntry.getPointer())
301 ReverseNonLocalDeps[Inst].insert(QueryInst);
305 // If the block *is* completely transparent to the load, we need to check
306 // the predecessors of this block. Add them to our worklist.
307 DirtyBlocks.append(pred_begin(DirtyBB), pred_end(DirtyBB));
311 // Copy the result into the output set.
312 for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end(); I != E;++I)
313 Result.push_back(std::make_pair(I->first, ConvToResult(I->second)));
316 /// removeInstruction - Remove an instruction from the dependence analysis,
317 /// updating the dependence of instructions that previously depended on it.
318 /// This method attempts to keep the cache coherent using the reverse map.
319 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
320 // Walk through the Non-local dependencies, removing this one as the value
321 // for any cached queries.
322 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
323 if (NLDI != NonLocalDeps.end()) {
324 NonLocalDepInfo &BlockMap = *NLDI->second.getPointer();
325 for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
327 if (Instruction *Inst = DI->second.getPointer())
328 ReverseNonLocalDeps[Inst].erase(RemInst);
330 NonLocalDeps.erase(NLDI);
333 // If we have a cached local dependence query for this instruction, remove it.
335 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
336 if (LocalDepEntry != LocalDeps.end()) {
337 // Remove us from DepInst's reverse set now that the local dep info is gone.
338 if (Instruction *Inst = LocalDepEntry->second.getPointer()) {
339 SmallPtrSet<Instruction*, 4> &RLD = ReverseLocalDeps[Inst];
342 ReverseLocalDeps.erase(Inst);
345 // Remove this local dependency info.
346 LocalDeps.erase(LocalDepEntry);
349 // Loop over all of the things that depend on the instruction we're removing.
351 SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
353 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
354 if (ReverseDepIt != ReverseLocalDeps.end()) {
355 SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
356 // RemInst can't be the terminator if it has stuff depending on it.
357 assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
358 "Nothing can locally depend on a terminator");
360 // Anything that was locally dependent on RemInst is now going to be
361 // dependent on the instruction after RemInst. It will have the dirty flag
362 // set so it will rescan. This saves having to scan the entire block to get
364 Instruction *NewDepInst = next(BasicBlock::iterator(RemInst));
366 for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
367 E = ReverseDeps.end(); I != E; ++I) {
368 Instruction *InstDependingOnRemInst = *I;
369 assert(InstDependingOnRemInst != RemInst &&
370 "Already removed our local dep info");
372 LocalDeps[InstDependingOnRemInst] = DepResultTy(NewDepInst, Dirty);
374 // Make sure to remember that new things depend on NewDepInst.
375 ReverseDepsToAdd.push_back(std::make_pair(NewDepInst,
376 InstDependingOnRemInst));
379 ReverseLocalDeps.erase(ReverseDepIt);
381 // Add new reverse deps after scanning the set, to avoid invalidating the
382 // 'ReverseDeps' reference.
383 while (!ReverseDepsToAdd.empty()) {
384 ReverseLocalDeps[ReverseDepsToAdd.back().first]
385 .insert(ReverseDepsToAdd.back().second);
386 ReverseDepsToAdd.pop_back();
390 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
391 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
392 SmallPtrSet<Instruction*, 4>& set = ReverseDepIt->second;
393 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
395 assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
397 PerInstNLInfo &INLD = NonLocalDeps[*I];
398 assert(INLD.getPointer() != 0 && "Reverse mapping out of date?");
399 // The information is now dirty!
402 for (NonLocalDepInfo::iterator DI = INLD.getPointer()->begin(),
403 DE = INLD.getPointer()->end(); DI != DE; ++DI) {
404 if (DI->second.getPointer() != RemInst) continue;
406 // Convert to a dirty entry for the subsequent instruction.
407 DI->second.setInt(Dirty);
408 if (RemInst->isTerminator())
409 DI->second.setPointer(0);
411 Instruction *NextI = next(BasicBlock::iterator(RemInst));
412 DI->second.setPointer(NextI);
413 ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
418 ReverseNonLocalDeps.erase(ReverseDepIt);
420 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
421 while (!ReverseDepsToAdd.empty()) {
422 ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
423 .insert(ReverseDepsToAdd.back().second);
424 ReverseDepsToAdd.pop_back();
428 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
429 getAnalysis<AliasAnalysis>().deleteValue(RemInst);
430 DEBUG(verifyRemoved(RemInst));
433 /// verifyRemoved - Verify that the specified instruction does not occur
434 /// in our internal data structures.
435 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
436 for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
437 E = LocalDeps.end(); I != E; ++I) {
438 assert(I->first != D && "Inst occurs in data structures");
439 assert(I->second.getPointer() != D &&
440 "Inst occurs in data structures");
443 for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
444 E = NonLocalDeps.end(); I != E; ++I) {
445 assert(I->first != D && "Inst occurs in data structures");
446 const PerInstNLInfo &INLD = I->second;
447 for (NonLocalDepInfo::iterator II = INLD.getPointer()->begin(),
448 EE = INLD.getPointer()->end(); II != EE; ++II)
449 assert(II->second.getPointer() != D && "Inst occurs in data structures");
452 for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
453 E = ReverseLocalDeps.end(); I != E; ++I) {
454 assert(I->first != D && "Inst occurs in data structures");
455 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
456 EE = I->second.end(); II != EE; ++II)
457 assert(*II != D && "Inst occurs in data structures");
460 for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
461 E = ReverseNonLocalDeps.end();
463 assert(I->first != D && "Inst occurs in data structures");
464 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
465 EE = I->second.end(); II != EE; ++II)
466 assert(*II != D && "Inst occurs in data structures");