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/Support/CommandLine.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/ADT/Statistic.h"
27 #define DEBUG_TYPE "memdep"
31 // Control the calculation of non-local dependencies by only examining the
32 // predecessors if the basic block has less than X amount (50 by default).
34 PredLimit("nonlocaldep-threshold", cl::Hidden, cl::init(50),
35 cl::desc("Control the calculation of non-local"
36 "dependencies (default = 50)"));
38 STATISTIC(NumCacheNonlocal, "Number of cached non-local responses");
39 STATISTIC(NumUncacheNonlocal, "Number of uncached non-local responses");
41 char MemoryDependenceAnalysis::ID = 0;
43 Instruction* const MemoryDependenceAnalysis::NonLocal = (Instruction*)-3;
44 Instruction* const MemoryDependenceAnalysis::None = (Instruction*)-4;
45 Instruction* const MemoryDependenceAnalysis::Dirty = (Instruction*)-5;
47 // Register this pass...
48 static RegisterPass<MemoryDependenceAnalysis> X("memdep",
49 "Memory Dependence Analysis", false, true);
51 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
52 for (depMapType::const_iterator I = depGraphLocal.begin(),
53 E = depGraphLocal.end(); I != E; ++I) {
54 assert(I->first != D);
55 assert(I->second.first != D);
58 for (nonLocalDepMapType::const_iterator I = depGraphNonLocal.begin(),
59 E = depGraphNonLocal.end(); I != E; ++I) {
60 assert(I->first != D);
61 for (DenseMap<BasicBlock*, Value*>::iterator II = I->second.begin(),
62 EE = I->second.end(); II != EE; ++II)
63 assert(II->second != D);
66 for (reverseDepMapType::const_iterator I = reverseDep.begin(),
67 E = reverseDep.end(); I != E; ++I)
68 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
69 EE = I->second.end(); II != EE; ++II)
72 for (reverseDepMapType::const_iterator I = reverseDepNonLocal.begin(),
73 E = reverseDepNonLocal.end();
75 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
76 EE = I->second.end(); II != EE; ++II)
80 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
82 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.addRequiredTransitive<AliasAnalysis>();
85 AU.addRequiredTransitive<TargetData>();
88 /// getCallSiteDependency - Private helper for finding the local dependencies
90 Instruction* MemoryDependenceAnalysis::getCallSiteDependency(CallSite C,
94 std::pair<Instruction*, bool>& cachedResult =
95 depGraphLocal[C.getInstruction()];
96 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
97 TargetData& TD = getAnalysis<TargetData>();
98 BasicBlock::iterator blockBegin = C.getInstruction()->getParent()->begin();
99 BasicBlock::iterator QI = C.getInstruction();
101 // If the starting point was specified, use it
104 blockBegin = start->getParent()->begin();
105 // If the starting point wasn't specified, but the block was, use it
106 } else if (!start && block) {
108 blockBegin = block->begin();
111 // Walk backwards through the block, looking for dependencies
112 while (QI != blockBegin) {
115 // If this inst is a memory op, get the pointer it accessed
117 uint64_t pointerSize = 0;
118 if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
119 pointer = S->getPointerOperand();
120 pointerSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
121 } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
123 if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
124 pointerSize = C->getZExtValue() *
125 TD.getABITypeSize(AI->getAllocatedType());
128 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
129 pointer = V->getOperand(0);
130 pointerSize = TD.getTypeStoreSize(V->getType());
131 } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
132 pointer = F->getPointerOperand();
134 // FreeInsts erase the entire structure
136 } else if (CallSite::get(QI).getInstruction() != 0) {
137 AliasAnalysis::ModRefBehavior result =
138 AA.getModRefBehavior(CallSite::get(QI));
139 if (result != AliasAnalysis::DoesNotAccessMemory) {
140 if (!start && !block) {
141 cachedResult.first = QI;
142 cachedResult.second = true;
143 reverseDep[QI].insert(C.getInstruction());
152 if (AA.getModRefInfo(C, pointer, pointerSize) != AliasAnalysis::NoModRef) {
153 if (!start && !block) {
154 cachedResult.first = QI;
155 cachedResult.second = true;
156 reverseDep[QI].insert(C.getInstruction());
162 // No dependence found
163 cachedResult.first = NonLocal;
164 cachedResult.second = true;
165 reverseDep[NonLocal].insert(C.getInstruction());
169 /// nonLocalHelper - Private helper used to calculate non-local dependencies
170 /// by doing DFS on the predecessors of a block to find its dependencies
171 void MemoryDependenceAnalysis::nonLocalHelper(Instruction* query,
173 DenseMap<BasicBlock*, Value*>& resp) {
174 // Set of blocks that we've already visited in our DFS
175 SmallPtrSet<BasicBlock*, 4> visited;
176 // If we're updating a dirtied cache entry, we don't need to reprocess
177 // already computed entries.
178 for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(),
179 E = resp.end(); I != E; ++I)
180 if (I->second != Dirty)
181 visited.insert(I->first);
183 // Current stack of the DFS
184 SmallVector<BasicBlock*, 4> stack;
185 for (pred_iterator PI = pred_begin(block), PE = pred_end(block);
187 stack.push_back(*PI);
190 while (!stack.empty()) {
191 BasicBlock* BB = stack.back();
193 // If we've already visited this block, no need to revist
194 if (visited.count(BB)) {
199 // If we find a new block with a local dependency for query,
200 // then we insert the new dependency and backtrack.
204 Instruction* localDep = getDependency(query, 0, BB);
205 if (localDep != NonLocal) {
206 resp.insert(std::make_pair(BB, localDep));
211 // If we re-encounter the starting block, we still need to search it
212 // because there might be a dependency in the starting block AFTER
213 // the position of the query. This is necessary to get loops right.
214 } else if (BB == block) {
217 Instruction* localDep = getDependency(query, 0, BB);
218 if (localDep != query)
219 resp.insert(std::make_pair(BB, localDep));
226 // If we didn't find anything, recurse on the precessors of this block
227 // Only do this for blocks with a small number of predecessors.
228 bool predOnStack = false;
229 bool inserted = false;
230 if (std::distance(pred_begin(BB), pred_end(BB)) <= PredLimit) {
231 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
233 if (!visited.count(*PI)) {
234 stack.push_back(*PI);
240 // If we inserted a new predecessor, then we'll come back to this block
243 // If we didn't insert because we have no predecessors, then this
244 // query has no dependency at all.
245 else if (!inserted && !predOnStack) {
246 resp.insert(std::make_pair(BB, None));
247 // If we didn't insert because our predecessors are already on the stack,
248 // then we might still have a dependency, but it will be discovered during
250 } else if (!inserted && predOnStack){
251 resp.insert(std::make_pair(BB, NonLocal));
258 /// getNonLocalDependency - Fills the passed-in map with the non-local
259 /// dependencies of the queries. The map will contain NonLocal for
260 /// blocks between the query and its dependencies.
261 void MemoryDependenceAnalysis::getNonLocalDependency(Instruction* query,
262 DenseMap<BasicBlock*, Value*>& resp) {
263 if (depGraphNonLocal.count(query)) {
264 DenseMap<BasicBlock*, Value*>& cached = depGraphNonLocal[query];
267 SmallVector<BasicBlock*, 4> dirtied;
268 for (DenseMap<BasicBlock*, Value*>::iterator I = cached.begin(),
269 E = cached.end(); I != E; ++I)
270 if (I->second == Dirty)
271 dirtied.push_back(I->first);
273 for (SmallVector<BasicBlock*, 4>::iterator I = dirtied.begin(),
274 E = dirtied.end(); I != E; ++I) {
275 Instruction* localDep = getDependency(query, 0, *I);
276 if (localDep != NonLocal)
277 cached[*I] = localDep;
280 nonLocalHelper(query, *I, cached);
286 // Update the reverse non-local dependency cache
287 for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(), E = resp.end();
289 reverseDepNonLocal[I->second].insert(query);
293 NumUncacheNonlocal++;
295 // If not, go ahead and search for non-local deps.
296 nonLocalHelper(query, query->getParent(), resp);
298 // Update the non-local dependency cache
299 for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(), E = resp.end();
301 depGraphNonLocal[query].insert(*I);
302 reverseDepNonLocal[I->second].insert(query);
306 /// getDependency - Return the instruction on which a memory operation
307 /// depends. The local parameter indicates if the query should only
308 /// evaluate dependencies within the same basic block.
309 Instruction* MemoryDependenceAnalysis::getDependency(Instruction* query,
312 // Start looking for dependencies with the queried inst
313 BasicBlock::iterator QI = query;
315 // Check for a cached result
316 std::pair<Instruction*, bool>& cachedResult = depGraphLocal[query];
317 // If we have a _confirmed_ cached entry, return it
318 if (!block && !start) {
319 if (cachedResult.second)
320 return cachedResult.first;
321 else if (cachedResult.first && cachedResult.first != NonLocal)
322 // If we have an unconfirmed cached entry, we can start our search from there
323 QI = cachedResult.first;
328 else if (!start && block)
331 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
332 TargetData& TD = getAnalysis<TargetData>();
334 // Get the pointer value for which dependence will be determined
336 uint64_t dependeeSize = 0;
337 bool queryIsVolatile = false;
338 if (StoreInst* S = dyn_cast<StoreInst>(query)) {
339 dependee = S->getPointerOperand();
340 dependeeSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
341 queryIsVolatile = S->isVolatile();
342 } else if (LoadInst* L = dyn_cast<LoadInst>(query)) {
343 dependee = L->getPointerOperand();
344 dependeeSize = TD.getTypeStoreSize(L->getType());
345 queryIsVolatile = L->isVolatile();
346 } else if (VAArgInst* V = dyn_cast<VAArgInst>(query)) {
347 dependee = V->getOperand(0);
348 dependeeSize = TD.getTypeStoreSize(V->getType());
349 } else if (FreeInst* F = dyn_cast<FreeInst>(query)) {
350 dependee = F->getPointerOperand();
352 // FreeInsts erase the entire structure, not just a field
354 } else if (CallSite::get(query).getInstruction() != 0)
355 return getCallSiteDependency(CallSite::get(query), start, block);
356 else if (isa<AllocationInst>(query))
361 BasicBlock::iterator blockBegin = block ? block->begin()
362 : query->getParent()->begin();
364 // Walk backwards through the basic block, looking for dependencies
365 while (QI != blockBegin) {
368 // If this inst is a memory op, get the pointer it accessed
370 uint64_t pointerSize = 0;
371 if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
372 // All volatile loads/stores depend on each other
373 if (queryIsVolatile && S->isVolatile()) {
374 if (!start && !block) {
375 cachedResult.first = S;
376 cachedResult.second = true;
377 reverseDep[S].insert(query);
383 pointer = S->getPointerOperand();
384 pointerSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
385 } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
386 // All volatile loads/stores depend on each other
387 if (queryIsVolatile && L->isVolatile()) {
388 if (!start && !block) {
389 cachedResult.first = L;
390 cachedResult.second = true;
391 reverseDep[L].insert(query);
397 pointer = L->getPointerOperand();
398 pointerSize = TD.getTypeStoreSize(L->getType());
399 } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
401 if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
402 pointerSize = C->getZExtValue() *
403 TD.getABITypeSize(AI->getAllocatedType());
406 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
407 pointer = V->getOperand(0);
408 pointerSize = TD.getTypeStoreSize(V->getType());
409 } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
410 pointer = F->getPointerOperand();
412 // FreeInsts erase the entire structure
414 } else if (CallSite::get(QI).getInstruction() != 0) {
415 // Call insts need special handling. Check if they can modify our pointer
416 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(CallSite::get(QI),
417 dependee, dependeeSize);
419 if (MR != AliasAnalysis::NoModRef) {
420 // Loads don't depend on read-only calls
421 if (isa<LoadInst>(query) && MR == AliasAnalysis::Ref)
424 if (!start && !block) {
425 cachedResult.first = QI;
426 cachedResult.second = true;
427 reverseDep[QI].insert(query);
436 // If we found a pointer, check if it could be the same as our pointer
438 AliasAnalysis::AliasResult R = AA.alias(pointer, pointerSize,
439 dependee, dependeeSize);
441 if (R != AliasAnalysis::NoAlias) {
442 // May-alias loads don't depend on each other
443 if (isa<LoadInst>(query) && isa<LoadInst>(QI) &&
444 R == AliasAnalysis::MayAlias)
447 if (!start && !block) {
448 cachedResult.first = QI;
449 cachedResult.second = true;
450 reverseDep[QI].insert(query);
458 // If we found nothing, return the non-local flag
459 if (!start && !block) {
460 cachedResult.first = NonLocal;
461 cachedResult.second = true;
462 reverseDep[NonLocal].insert(query);
468 /// dropInstruction - Remove an instruction from the analysis, making
469 /// absolutely conservative assumptions when updating the cache. This is
470 /// useful, for example when an instruction is changed rather than removed.
471 void MemoryDependenceAnalysis::dropInstruction(Instruction* drop) {
472 depMapType::iterator depGraphEntry = depGraphLocal.find(drop);
473 if (depGraphEntry != depGraphLocal.end())
474 reverseDep[depGraphEntry->second.first].erase(drop);
476 // Drop dependency information for things that depended on this instr
477 SmallPtrSet<Instruction*, 4>& set = reverseDep[drop];
478 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
480 depGraphLocal.erase(*I);
482 depGraphLocal.erase(drop);
483 reverseDep.erase(drop);
485 for (DenseMap<BasicBlock*, Value*>::iterator DI =
486 depGraphNonLocal[drop].begin(), DE = depGraphNonLocal[drop].end();
488 if (DI->second != None)
489 reverseDepNonLocal[DI->second].erase(drop);
491 if (reverseDepNonLocal.count(drop)) {
492 SmallPtrSet<Instruction*, 4>& set = reverseDepNonLocal[drop];
493 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
495 for (DenseMap<BasicBlock*, Value*>::iterator DI =
496 depGraphNonLocal[*I].begin(), DE = depGraphNonLocal[*I].end();
498 if (DI->second == drop)
502 reverseDepNonLocal.erase(drop);
503 nonLocalDepMapType::iterator I = depGraphNonLocal.find(drop);
504 if (I != depGraphNonLocal.end())
505 depGraphNonLocal.erase(I);
508 /// removeInstruction - Remove an instruction from the dependence analysis,
509 /// updating the dependence of instructions that previously depended on it.
510 /// This method attempts to keep the cache coherent using the reverse map.
511 void MemoryDependenceAnalysis::removeInstruction(Instruction* rem) {
512 // Figure out the new dep for things that currently depend on rem
513 Instruction* newDep = NonLocal;
515 for (DenseMap<BasicBlock*, Value*>::iterator DI =
516 depGraphNonLocal[rem].begin(), DE = depGraphNonLocal[rem].end();
518 if (DI->second != None)
519 reverseDepNonLocal[DI->second].erase(rem);
521 depMapType::iterator depGraphEntry = depGraphLocal.find(rem);
523 if (depGraphEntry != depGraphLocal.end()) {
524 reverseDep[depGraphEntry->second.first].erase(rem);
526 if (depGraphEntry->second.first != NonLocal &&
527 depGraphEntry->second.first != None &&
528 depGraphEntry->second.second) {
529 // If we have dep info for rem, set them to it
530 BasicBlock::iterator RI = depGraphEntry->second.first;
533 // If RI is rem, then we use rem's immediate successor.
534 if (RI == (BasicBlock::iterator)rem) RI++;
537 } else if ((depGraphEntry->second.first == NonLocal ||
538 depGraphEntry->second.first == None) &&
539 depGraphEntry->second.second) {
540 // If we have a confirmed non-local flag, use it
541 newDep = depGraphEntry->second.first;
543 // Otherwise, use the immediate successor of rem
544 // NOTE: This is because, when getDependence is called, it will first
545 // check the immediate predecessor of what is in the cache.
546 BasicBlock::iterator RI = rem;
551 // Otherwise, use the immediate successor of rem
552 // NOTE: This is because, when getDependence is called, it will first
553 // check the immediate predecessor of what is in the cache.
554 BasicBlock::iterator RI = rem;
559 SmallPtrSet<Instruction*, 4>& set = reverseDep[rem];
560 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
562 // Insert the new dependencies
563 // Mark it as unconfirmed as long as it is not the non-local flag
564 depGraphLocal[*I] = std::make_pair(newDep, (newDep == NonLocal ||
568 depGraphLocal.erase(rem);
569 reverseDep.erase(rem);
571 if (reverseDepNonLocal.count(rem)) {
572 SmallPtrSet<Instruction*, 4>& set = reverseDepNonLocal[rem];
573 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
575 for (DenseMap<BasicBlock*, Value*>::iterator DI =
576 depGraphNonLocal[*I].begin(), DE = depGraphNonLocal[*I].end();
578 if (DI->second == rem)
583 reverseDepNonLocal.erase(rem);
584 nonLocalDepMapType::iterator I = depGraphNonLocal.find(rem);
585 if (I != depGraphNonLocal.end())
586 depGraphNonLocal.erase(I);
588 getAnalysis<AliasAnalysis>().deleteValue(rem);