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 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Function.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/ADT/Statistic.h"
26 #define DEBUG_TYPE "memdep"
30 STATISTIC(NumCacheNonlocal, "Number of cached non-local responses");
31 STATISTIC(NumUncacheNonlocal, "Number of uncached non-local responses");
33 char MemoryDependenceAnalysis::ID = 0;
35 Instruction* const MemoryDependenceAnalysis::NonLocal = (Instruction*)-3;
36 Instruction* const MemoryDependenceAnalysis::None = (Instruction*)-4;
37 Instruction* const MemoryDependenceAnalysis::Dirty = (Instruction*)-5;
39 // Register this pass...
40 static RegisterPass<MemoryDependenceAnalysis> X("memdep",
41 "Memory Dependence Analysis");
43 void MemoryDependenceAnalysis::ping(Instruction *D) {
44 for (depMapType::iterator I = depGraphLocal.begin(), E = depGraphLocal.end();
46 assert(I->first != D);
47 assert(I->second.first != D);
50 for (nonLocalDepMapType::iterator I = depGraphNonLocal.begin(), E = depGraphNonLocal.end();
52 assert(I->first != D);
55 for (reverseDepMapType::iterator I = reverseDep.begin(), E = reverseDep.end();
57 for (SmallPtrSet<Instruction*, 4>::iterator II = I->second.begin(), EE = I->second.end();
61 for (reverseDepMapType::iterator I = reverseDepNonLocal.begin(), E = reverseDepNonLocal.end();
63 for (SmallPtrSet<Instruction*, 4>::iterator II = I->second.begin(), EE = I->second.end();
68 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
70 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequiredTransitive<AliasAnalysis>();
73 AU.addRequiredTransitive<TargetData>();
76 /// getCallSiteDependency - Private helper for finding the local dependencies
78 Instruction* MemoryDependenceAnalysis::getCallSiteDependency(CallSite C,
82 std::pair<Instruction*, bool>& cachedResult =
83 depGraphLocal[C.getInstruction()];
84 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
85 TargetData& TD = getAnalysis<TargetData>();
86 BasicBlock::iterator blockBegin = C.getInstruction()->getParent()->begin();
87 BasicBlock::iterator QI = C.getInstruction();
89 // If the starting point was specifiy, use it
92 blockBegin = start->getParent()->end();
93 // If the starting point wasn't specified, but the block was, use it
94 } else if (!start && block) {
96 blockBegin = block->end();
99 // Walk backwards through the block, looking for dependencies
100 while (QI != blockBegin) {
103 // If this inst is a memory op, get the pointer it accessed
105 uint64_t pointerSize = 0;
106 if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
107 pointer = S->getPointerOperand();
108 pointerSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
109 } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
111 if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
112 pointerSize = C->getZExtValue() * \
113 TD.getABITypeSize(AI->getAllocatedType());
116 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
117 pointer = V->getOperand(0);
118 pointerSize = TD.getTypeStoreSize(V->getType());
119 } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
120 pointer = F->getPointerOperand();
122 // FreeInsts erase the entire structure
124 } else if (isa<CallInst>(QI)) {
125 AliasAnalysis::ModRefBehavior result =
126 AA.getModRefBehavior(CallSite::get(QI));
127 if (result != AliasAnalysis::DoesNotAccessMemory &&
128 result != AliasAnalysis::OnlyReadsMemory) {
129 if (!start && !block) {
130 cachedResult.first = QI;
131 cachedResult.second = true;
132 reverseDep[QI].insert(C.getInstruction());
141 if (AA.getModRefInfo(C, pointer, pointerSize) != AliasAnalysis::NoModRef) {
142 if (!start && !block) {
143 cachedResult.first = QI;
144 cachedResult.second = true;
145 reverseDep[QI].insert(C.getInstruction());
151 // No dependence found
152 cachedResult.first = NonLocal;
153 cachedResult.second = true;
154 reverseDep[NonLocal].insert(C.getInstruction());
158 /// nonLocalHelper - Private helper used to calculate non-local dependencies
159 /// by doing DFS on the predecessors of a block to find its dependencies
160 void MemoryDependenceAnalysis::nonLocalHelper(Instruction* query,
162 DenseMap<BasicBlock*, Value*>& resp) {
163 // Set of blocks that we've already visited in our DFS
164 SmallPtrSet<BasicBlock*, 4> visited;
165 // If we're updating a dirtied cache entry, we don't need to reprocess
166 // already computed entries.
167 for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(),
168 E = resp.end(); I != E; ++I)
169 if (I->second != Dirty)
170 visited.insert(I->first);
172 // Current stack of the DFS
173 SmallVector<BasicBlock*, 4> stack;
174 stack.push_back(block);
177 while (!stack.empty()) {
178 BasicBlock* BB = stack.back();
180 // If we've already visited this block, no need to revist
181 if (visited.count(BB)) {
186 // If we find a new block with a local dependency for query,
187 // then we insert the new dependency and backtrack.
191 Instruction* localDep = getDependency(query, 0, BB);
192 if (localDep != NonLocal) {
193 resp.insert(std::make_pair(BB, localDep));
198 // If we re-encounter the starting block, we still need to search it
199 // because there might be a dependency in the starting block AFTER
200 // the position of the query. This is necessary to get loops right.
201 } else if (BB == block && stack.size() > 1) {
204 Instruction* localDep = getDependency(query, 0, BB);
205 if (localDep != query)
206 resp.insert(std::make_pair(BB, localDep));
213 // If we didn't find anything, recurse on the precessors of this block
214 bool predOnStack = false;
215 bool inserted = false;
216 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
218 if (!visited.count(*PI)) {
219 stack.push_back(*PI);
224 // If we inserted a new predecessor, then we'll come back to this block
227 // If we didn't insert because we have no predecessors, then this
228 // query has no dependency at all.
229 else if (!inserted && !predOnStack) {
230 resp.insert(std::make_pair(BB, None));
231 // If we didn't insert because our predecessors are already on the stack,
232 // then we might still have a dependency, but it will be discovered during
234 } else if (!inserted && predOnStack){
235 resp.insert(std::make_pair(BB, NonLocal));
242 /// getNonLocalDependency - Fills the passed-in map with the non-local
243 /// dependencies of the queries. The map will contain NonLocal for
244 /// blocks between the query and its dependencies.
245 void MemoryDependenceAnalysis::getNonLocalDependency(Instruction* query,
246 DenseMap<BasicBlock*, Value*>& resp) {
247 if (depGraphNonLocal.count(query)) {
248 DenseMap<BasicBlock*, Value*>& cached = depGraphNonLocal[query];
251 SmallVector<BasicBlock*, 4> dirtied;
252 for (DenseMap<BasicBlock*, Value*>::iterator I = cached.begin(),
253 E = cached.end(); I != E; ++I)
254 if (I->second == Dirty)
255 dirtied.push_back(I->first);
257 for (SmallVector<BasicBlock*, 4>::iterator I = dirtied.begin(),
258 E = dirtied.end(); I != E; ++I) {
259 Instruction* localDep = getDependency(query, 0, *I);
260 if (localDep != NonLocal)
261 cached[*I] = localDep;
264 nonLocalHelper(query, *I, cached);
272 NumUncacheNonlocal++;
274 // If not, go ahead and search for non-local deps.
275 nonLocalHelper(query, query->getParent(), resp);
277 // Update the non-local dependency cache
278 for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(), E = resp.end();
280 depGraphNonLocal[query].insert(*I);
281 reverseDepNonLocal[I->second].insert(query);
285 /// getDependency - Return the instruction on which a memory operation
286 /// depends. The local paramter indicates if the query should only
287 /// evaluate dependencies within the same basic block.
288 Instruction* MemoryDependenceAnalysis::getDependency(Instruction* query,
291 // Start looking for dependencies with the queried inst
292 BasicBlock::iterator QI = query;
294 // Check for a cached result
295 std::pair<Instruction*, bool>& cachedResult = depGraphLocal[query];
296 // If we have a _confirmed_ cached entry, return it
297 if (!block && !start) {
298 if (cachedResult.second)
299 return cachedResult.first;
300 else if (cachedResult.first && cachedResult.first != NonLocal)
301 // If we have an unconfirmed cached entry, we can start our search from there
302 QI = cachedResult.first;
307 else if (!start && block)
310 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
311 TargetData& TD = getAnalysis<TargetData>();
313 // Get the pointer value for which dependence will be determined
315 uint64_t dependeeSize = 0;
316 bool queryIsVolatile = false;
317 if (StoreInst* S = dyn_cast<StoreInst>(query)) {
318 dependee = S->getPointerOperand();
319 dependeeSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
320 queryIsVolatile = S->isVolatile();
321 } else if (LoadInst* L = dyn_cast<LoadInst>(query)) {
322 dependee = L->getPointerOperand();
323 dependeeSize = TD.getTypeStoreSize(L->getType());
324 queryIsVolatile = L->isVolatile();
325 } else if (VAArgInst* V = dyn_cast<VAArgInst>(query)) {
326 dependee = V->getOperand(0);
327 dependeeSize = TD.getTypeStoreSize(V->getType());
328 } else if (FreeInst* F = dyn_cast<FreeInst>(query)) {
329 dependee = F->getPointerOperand();
331 // FreeInsts erase the entire structure, not just a field
333 } else if (CallSite::get(query).getInstruction() != 0)
334 return getCallSiteDependency(CallSite::get(query), start, block);
335 else if (isa<AllocationInst>(query))
340 BasicBlock::iterator blockBegin = block ? block->begin()
341 : query->getParent()->begin();
343 // Walk backwards through the basic block, looking for dependencies
344 while (QI != blockBegin) {
347 // If this inst is a memory op, get the pointer it accessed
349 uint64_t pointerSize = 0;
350 if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
351 // All volatile loads/stores depend on each other
352 if (queryIsVolatile && S->isVolatile()) {
353 if (!start && !block) {
354 cachedResult.first = S;
355 cachedResult.second = true;
356 reverseDep[S].insert(query);
362 pointer = S->getPointerOperand();
363 pointerSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
364 } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
365 // All volatile loads/stores depend on each other
366 if (queryIsVolatile && L->isVolatile()) {
367 if (!start && !block) {
368 cachedResult.first = L;
369 cachedResult.second = true;
370 reverseDep[L].insert(query);
376 pointer = L->getPointerOperand();
377 pointerSize = TD.getTypeStoreSize(L->getType());
378 } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
380 if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
381 pointerSize = C->getZExtValue() * \
382 TD.getABITypeSize(AI->getAllocatedType());
385 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
386 pointer = V->getOperand(0);
387 pointerSize = TD.getTypeStoreSize(V->getType());
388 } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
389 pointer = F->getPointerOperand();
391 // FreeInsts erase the entire structure
393 } else if (CallSite::get(QI).getInstruction() != 0) {
394 // Call insts need special handling. Check if they can modify our pointer
395 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(CallSite::get(QI),
396 dependee, dependeeSize);
398 if (MR != AliasAnalysis::NoModRef) {
399 // Loads don't depend on read-only calls
400 if (isa<LoadInst>(query) && MR == AliasAnalysis::Ref)
403 if (!start && !block) {
404 cachedResult.first = QI;
405 cachedResult.second = true;
406 reverseDep[QI].insert(query);
415 // If we found a pointer, check if it could be the same as our pointer
417 AliasAnalysis::AliasResult R = AA.alias(pointer, pointerSize,
418 dependee, dependeeSize);
420 if (R != AliasAnalysis::NoAlias) {
421 // May-alias loads don't depend on each other
422 if (isa<LoadInst>(query) && isa<LoadInst>(QI) &&
423 R == AliasAnalysis::MayAlias)
426 if (!start && !block) {
427 cachedResult.first = QI;
428 cachedResult.second = true;
429 reverseDep[QI].insert(query);
437 // If we found nothing, return the non-local flag
438 if (!start && !block) {
439 cachedResult.first = NonLocal;
440 cachedResult.second = true;
441 reverseDep[NonLocal].insert(query);
447 /// removeInstruction - Remove an instruction from the dependence analysis,
448 /// updating the dependence of instructions that previously depended on it.
449 /// This method attempts to keep the cache coherent using the reverse map.
450 void MemoryDependenceAnalysis::removeInstruction(Instruction* rem) {
451 // Figure out the new dep for things that currently depend on rem
452 Instruction* newDep = NonLocal;
454 reverseDep[depGraphLocal[rem].first].erase(rem);
456 for (DenseMap<BasicBlock*, Value*>::iterator DI =
457 depGraphNonLocal[rem].begin(), DE = depGraphNonLocal[rem].end();
459 if (DI->second != None)
460 reverseDepNonLocal[DI->second].erase(rem);
462 depMapType::iterator depGraphEntry = depGraphLocal.find(rem);
464 if (depGraphEntry != depGraphLocal.end()) {
465 if (depGraphEntry->second.first != NonLocal &&
466 depGraphEntry->second.second) {
467 // If we have dep info for rem, set them to it
468 BasicBlock::iterator RI = depGraphEntry->second.first;
471 } else if (depGraphEntry->second.first == NonLocal &&
472 depGraphEntry->second.second ) {
473 // If we have a confirmed non-local flag, use it
476 // Otherwise, use the immediate successor of rem
477 // NOTE: This is because, when getDependence is called, it will first
478 // check the immediate predecessor of what is in the cache.
479 BasicBlock::iterator RI = rem;
484 SmallPtrSet<Instruction*, 4>& set = reverseDep[rem];
485 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
487 // Insert the new dependencies
488 // Mark it as unconfirmed as long as it is not the non-local flag
489 depGraphLocal[*I] = std::make_pair(newDep, !newDep);
493 depGraphLocal.erase(rem);
494 reverseDep.erase(rem);
496 if (reverseDepNonLocal.count(rem)) {
497 SmallPtrSet<Instruction*, 4>& set = reverseDepNonLocal[rem];
498 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
500 for (DenseMap<BasicBlock*, Value*>::iterator DI =
501 depGraphNonLocal[*I].begin(), DE = depGraphNonLocal[*I].end();
503 if (DI->second == rem)
508 reverseDepNonLocal.erase(rem);
509 nonLocalDepMapType::iterator I = depGraphNonLocal.find(rem);
510 if (I != depGraphNonLocal.end())
511 depGraphNonLocal.erase(I);
513 getAnalysis<AliasAnalysis>().deleteValue(rem);