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"
32 // Control the calculation of non-local dependencies by only examining the
33 // predecessors if the basic block has less than X amount (50 by default).
35 PredLimit("nonlocaldep-threshold", cl::Hidden, cl::init(50),
36 cl::desc("Control the calculation of non-local"
37 "dependencies (default = 50)"));
39 STATISTIC(NumCacheNonlocal, "Number of cached non-local responses");
40 STATISTIC(NumUncacheNonlocal, "Number of uncached non-local responses");
42 char MemoryDependenceAnalysis::ID = 0;
44 Instruction* const MemoryDependenceAnalysis::NonLocal = (Instruction*)-3;
45 Instruction* const MemoryDependenceAnalysis::None = (Instruction*)-4;
46 Instruction* const MemoryDependenceAnalysis::Dirty = (Instruction*)-5;
48 // Register this pass...
49 static RegisterPass<MemoryDependenceAnalysis> X("memdep",
50 "Memory Dependence Analysis", false, true);
52 /// verifyRemoved - Verify that the specified instruction does not occur
53 /// in our internal data structures.
54 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
55 for (depMapType::const_iterator I = depGraphLocal.begin(),
56 E = depGraphLocal.end(); I != E; ++I) {
57 assert(I->first != D && "Inst occurs in data structures");
58 assert(I->second.first != D && "Inst occurs in data structures");
61 for (nonLocalDepMapType::const_iterator I = depGraphNonLocal.begin(),
62 E = depGraphNonLocal.end(); I != E; ++I) {
63 assert(I->first != D && "Inst occurs in data structures");
64 for (DenseMap<BasicBlock*, Value*>::iterator II = I->second.begin(),
65 EE = I->second.end(); II != EE; ++II)
66 assert(II->second != D && "Inst occurs in data structures");
69 for (reverseDepMapType::const_iterator I = reverseDep.begin(),
70 E = reverseDep.end(); I != E; ++I)
71 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
72 EE = I->second.end(); II != EE; ++II)
73 assert(*II != D && "Inst occurs in data structures");
75 for (reverseDepMapType::const_iterator I = reverseDepNonLocal.begin(),
76 E = reverseDepNonLocal.end();
78 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
79 EE = I->second.end(); II != EE; ++II)
80 assert(*II != D && "Inst occurs in data structures");
83 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
85 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
87 AU.addRequiredTransitive<AliasAnalysis>();
88 AU.addRequiredTransitive<TargetData>();
91 /// getCallSiteDependency - Private helper for finding the local dependencies
93 Instruction* MemoryDependenceAnalysis::getCallSiteDependency(CallSite C,
97 std::pair<Instruction*, bool>& cachedResult =
98 depGraphLocal[C.getInstruction()];
99 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
100 TargetData& TD = getAnalysis<TargetData>();
101 BasicBlock::iterator blockBegin = C.getInstruction()->getParent()->begin();
102 BasicBlock::iterator QI = C.getInstruction();
104 // If the starting point was specified, use it
107 blockBegin = start->getParent()->begin();
108 // If the starting point wasn't specified, but the block was, use it
109 } else if (!start && block) {
111 blockBegin = block->begin();
114 // Walk backwards through the block, looking for dependencies
115 while (QI != blockBegin) {
118 // If this inst is a memory op, get the pointer it accessed
120 uint64_t pointerSize = 0;
121 if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
122 pointer = S->getPointerOperand();
123 pointerSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
124 } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
126 if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
127 pointerSize = C->getZExtValue() *
128 TD.getABITypeSize(AI->getAllocatedType());
131 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
132 pointer = V->getOperand(0);
133 pointerSize = TD.getTypeStoreSize(V->getType());
134 } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
135 pointer = F->getPointerOperand();
137 // FreeInsts erase the entire structure
139 } else if (CallSite::get(QI).getInstruction() != 0) {
140 AliasAnalysis::ModRefBehavior result =
141 AA.getModRefBehavior(CallSite::get(QI));
142 if (result != AliasAnalysis::DoesNotAccessMemory) {
143 if (!start && !block) {
144 cachedResult.first = QI;
145 cachedResult.second = true;
146 reverseDep[QI].insert(C.getInstruction());
155 if (AA.getModRefInfo(C, pointer, pointerSize) != AliasAnalysis::NoModRef) {
156 if (!start && !block) {
157 cachedResult.first = QI;
158 cachedResult.second = true;
159 reverseDep[QI].insert(C.getInstruction());
165 // No dependence found
166 cachedResult.first = NonLocal;
167 cachedResult.second = true;
168 reverseDep[NonLocal].insert(C.getInstruction());
172 /// nonLocalHelper - Private helper used to calculate non-local dependencies
173 /// by doing DFS on the predecessors of a block to find its dependencies
174 void MemoryDependenceAnalysis::nonLocalHelper(Instruction* query,
176 DenseMap<BasicBlock*, Value*>& resp) {
177 // Set of blocks that we've already visited in our DFS
178 SmallPtrSet<BasicBlock*, 4> visited;
179 // If we're updating a dirtied cache entry, we don't need to reprocess
180 // already computed entries.
181 for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(),
182 E = resp.end(); I != E; ++I)
183 if (I->second != Dirty)
184 visited.insert(I->first);
186 // Current stack of the DFS
187 SmallVector<BasicBlock*, 4> stack;
188 for (pred_iterator PI = pred_begin(block), PE = pred_end(block);
190 stack.push_back(*PI);
193 while (!stack.empty()) {
194 BasicBlock* BB = stack.back();
196 // If we've already visited this block, no need to revist
197 if (visited.count(BB)) {
202 // If we find a new block with a local dependency for query,
203 // then we insert the new dependency and backtrack.
207 Instruction* localDep = getDependency(query, 0, BB);
208 if (localDep != NonLocal) {
209 resp.insert(std::make_pair(BB, localDep));
214 // If we re-encounter the starting block, we still need to search it
215 // because there might be a dependency in the starting block AFTER
216 // the position of the query. This is necessary to get loops right.
217 } else if (BB == block) {
220 Instruction* localDep = getDependency(query, 0, BB);
221 if (localDep != query)
222 resp.insert(std::make_pair(BB, localDep));
229 // If we didn't find anything, recurse on the precessors of this block
230 // Only do this for blocks with a small number of predecessors.
231 bool predOnStack = false;
232 bool inserted = false;
233 if (std::distance(pred_begin(BB), pred_end(BB)) <= PredLimit) {
234 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
236 if (!visited.count(*PI)) {
237 stack.push_back(*PI);
243 // If we inserted a new predecessor, then we'll come back to this block
246 // If we didn't insert because we have no predecessors, then this
247 // query has no dependency at all.
248 else if (!inserted && !predOnStack) {
249 resp.insert(std::make_pair(BB, None));
250 // If we didn't insert because our predecessors are already on the stack,
251 // then we might still have a dependency, but it will be discovered during
253 } else if (!inserted && predOnStack){
254 resp.insert(std::make_pair(BB, NonLocal));
261 /// getNonLocalDependency - Fills the passed-in map with the non-local
262 /// dependencies of the queries. The map will contain NonLocal for
263 /// blocks between the query and its dependencies.
264 void MemoryDependenceAnalysis::getNonLocalDependency(Instruction* query,
265 DenseMap<BasicBlock*, Value*>& resp) {
266 if (depGraphNonLocal.count(query)) {
267 DenseMap<BasicBlock*, Value*>& cached = depGraphNonLocal[query];
270 SmallVector<BasicBlock*, 4> dirtied;
271 for (DenseMap<BasicBlock*, Value*>::iterator I = cached.begin(),
272 E = cached.end(); I != E; ++I)
273 if (I->second == Dirty)
274 dirtied.push_back(I->first);
276 for (SmallVector<BasicBlock*, 4>::iterator I = dirtied.begin(),
277 E = dirtied.end(); I != E; ++I) {
278 Instruction* localDep = getDependency(query, 0, *I);
279 if (localDep != NonLocal)
280 cached[*I] = localDep;
283 nonLocalHelper(query, *I, cached);
289 // Update the reverse non-local dependency cache
290 for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(), E = resp.end();
292 reverseDepNonLocal[I->second].insert(query);
296 NumUncacheNonlocal++;
298 // If not, go ahead and search for non-local deps.
299 nonLocalHelper(query, query->getParent(), resp);
301 // Update the non-local dependency cache
302 for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(), E = resp.end();
304 depGraphNonLocal[query].insert(*I);
305 reverseDepNonLocal[I->second].insert(query);
309 /// getDependency - Return the instruction on which a memory operation
310 /// depends. The local parameter indicates if the query should only
311 /// evaluate dependencies within the same basic block.
312 Instruction* MemoryDependenceAnalysis::getDependency(Instruction* query,
315 // Start looking for dependencies with the queried inst
316 BasicBlock::iterator QI = query;
318 // Check for a cached result
319 std::pair<Instruction*, bool>& cachedResult = depGraphLocal[query];
320 // If we have a _confirmed_ cached entry, return it
321 if (!block && !start) {
322 if (cachedResult.second)
323 return cachedResult.first;
324 else if (cachedResult.first && cachedResult.first != NonLocal)
325 // If we have an unconfirmed cached entry, we can start our search from there
326 QI = cachedResult.first;
331 else if (!start && block)
334 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
335 TargetData& TD = getAnalysis<TargetData>();
337 // Get the pointer value for which dependence will be determined
339 uint64_t dependeeSize = 0;
340 bool queryIsVolatile = false;
341 if (StoreInst* S = dyn_cast<StoreInst>(query)) {
342 dependee = S->getPointerOperand();
343 dependeeSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
344 queryIsVolatile = S->isVolatile();
345 } else if (LoadInst* L = dyn_cast<LoadInst>(query)) {
346 dependee = L->getPointerOperand();
347 dependeeSize = TD.getTypeStoreSize(L->getType());
348 queryIsVolatile = L->isVolatile();
349 } else if (VAArgInst* V = dyn_cast<VAArgInst>(query)) {
350 dependee = V->getOperand(0);
351 dependeeSize = TD.getTypeStoreSize(V->getType());
352 } else if (FreeInst* F = dyn_cast<FreeInst>(query)) {
353 dependee = F->getPointerOperand();
355 // FreeInsts erase the entire structure, not just a field
357 } else if (CallSite::get(query).getInstruction() != 0)
358 return getCallSiteDependency(CallSite::get(query), start, block);
359 else if (isa<AllocationInst>(query))
364 BasicBlock::iterator blockBegin = block ? block->begin()
365 : query->getParent()->begin();
367 // Walk backwards through the basic block, looking for dependencies
368 while (QI != blockBegin) {
371 // If this inst is a memory op, get the pointer it accessed
373 uint64_t pointerSize = 0;
374 if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
375 // All volatile loads/stores depend on each other
376 if (queryIsVolatile && S->isVolatile()) {
377 if (!start && !block) {
378 cachedResult.first = S;
379 cachedResult.second = true;
380 reverseDep[S].insert(query);
386 pointer = S->getPointerOperand();
387 pointerSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
388 } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
389 // All volatile loads/stores depend on each other
390 if (queryIsVolatile && L->isVolatile()) {
391 if (!start && !block) {
392 cachedResult.first = L;
393 cachedResult.second = true;
394 reverseDep[L].insert(query);
400 pointer = L->getPointerOperand();
401 pointerSize = TD.getTypeStoreSize(L->getType());
402 } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
404 if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
405 pointerSize = C->getZExtValue() *
406 TD.getABITypeSize(AI->getAllocatedType());
409 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
410 pointer = V->getOperand(0);
411 pointerSize = TD.getTypeStoreSize(V->getType());
412 } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
413 pointer = F->getPointerOperand();
415 // FreeInsts erase the entire structure
417 } else if (CallSite::get(QI).getInstruction() != 0) {
418 // Call insts need special handling. Check if they can modify our pointer
419 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(CallSite::get(QI),
420 dependee, dependeeSize);
422 if (MR != AliasAnalysis::NoModRef) {
423 // Loads don't depend on read-only calls
424 if (isa<LoadInst>(query) && MR == AliasAnalysis::Ref)
427 if (!start && !block) {
428 cachedResult.first = QI;
429 cachedResult.second = true;
430 reverseDep[QI].insert(query);
439 // If we found a pointer, check if it could be the same as our pointer
441 AliasAnalysis::AliasResult R = AA.alias(pointer, pointerSize,
442 dependee, dependeeSize);
444 if (R != AliasAnalysis::NoAlias) {
445 // May-alias loads don't depend on each other
446 if (isa<LoadInst>(query) && isa<LoadInst>(QI) &&
447 R == AliasAnalysis::MayAlias)
450 if (!start && !block) {
451 cachedResult.first = QI;
452 cachedResult.second = true;
453 reverseDep[QI].insert(query);
461 // If we found nothing, return the non-local flag
462 if (!start && !block) {
463 cachedResult.first = NonLocal;
464 cachedResult.second = true;
465 reverseDep[NonLocal].insert(query);
471 /// dropInstruction - Remove an instruction from the analysis, making
472 /// absolutely conservative assumptions when updating the cache. This is
473 /// useful, for example when an instruction is changed rather than removed.
474 void MemoryDependenceAnalysis::dropInstruction(Instruction* drop) {
475 depMapType::iterator depGraphEntry = depGraphLocal.find(drop);
476 if (depGraphEntry != depGraphLocal.end())
477 reverseDep[depGraphEntry->second.first].erase(drop);
479 // Drop dependency information for things that depended on this instr
480 SmallPtrSet<Instruction*, 4>& set = reverseDep[drop];
481 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
483 depGraphLocal.erase(*I);
485 depGraphLocal.erase(drop);
486 reverseDep.erase(drop);
488 for (DenseMap<BasicBlock*, Value*>::iterator DI =
489 depGraphNonLocal[drop].begin(), DE = depGraphNonLocal[drop].end();
491 if (DI->second != None)
492 reverseDepNonLocal[DI->second].erase(drop);
494 if (reverseDepNonLocal.count(drop)) {
495 SmallPtrSet<Instruction*, 4>& set = reverseDepNonLocal[drop];
496 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
498 for (DenseMap<BasicBlock*, Value*>::iterator DI =
499 depGraphNonLocal[*I].begin(), DE = depGraphNonLocal[*I].end();
501 if (DI->second == drop)
505 reverseDepNonLocal.erase(drop);
506 nonLocalDepMapType::iterator I = depGraphNonLocal.find(drop);
507 if (I != depGraphNonLocal.end())
508 depGraphNonLocal.erase(I);
511 /// removeInstruction - Remove an instruction from the dependence analysis,
512 /// updating the dependence of instructions that previously depended on it.
513 /// This method attempts to keep the cache coherent using the reverse map.
514 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
515 // Walk through the Non-local dependencies, removing this one as the value
516 // for any cached queries.
517 for (DenseMap<BasicBlock*, Value*>::iterator DI =
518 depGraphNonLocal[RemInst].begin(), DE = depGraphNonLocal[RemInst].end();
520 if (DI->second != None)
521 reverseDepNonLocal[DI->second].erase(RemInst);
523 // Shortly after this, we will look for things that depend on RemInst. In
524 // order to update these, we'll need a new dependency to base them on. We
525 // could completely delete any entries that depend on this, but it is better
526 // to make a more accurate approximation where possible. Compute that better
527 // approximation if we can.
528 Instruction *NewDependency = 0;
529 bool NewDependencyConfirmed = false;
531 // If we have a cached local dependence query for this instruction, remove it.
533 depMapType::iterator LocalDepEntry = depGraphLocal.find(RemInst);
534 if (LocalDepEntry != depGraphLocal.end()) {
535 Instruction *LocalDepInst = LocalDepEntry->second.first;
536 bool IsConfirmed = LocalDepEntry->second.second;
538 // Remove this local dependency info.
539 depGraphLocal.erase(LocalDepEntry);
541 // Remove us from DepInst's reverse set now that the local dep info is gone.
542 reverseDep[LocalDepInst].erase(RemInst);
544 // If we have unconfirmed info, don't trust it.
546 // If we have a confirmed non-local flag, use it.
547 if (LocalDepInst == NonLocal || LocalDepInst == None) {
548 NewDependency = LocalDepInst;
549 NewDependencyConfirmed = true;
551 // If we have dep info for RemInst, set them to it.
552 NewDependency = next(BasicBlock::iterator(LocalDepInst));
554 // Don't use RI for the new dependency!
555 if (NewDependency == RemInst)
561 // If we don't already have a local dependency answer for this instruction,
562 // use the immediate successor of RemInst. We use the successor because
563 // getDependence starts by checking the immediate predecessor of what is in
565 if (NewDependency == 0)
566 NewDependency = next(BasicBlock::iterator(RemInst));
568 SmallPtrSet<Instruction*, 4>& set = reverseDep[RemInst];
569 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
571 // Insert the new dependencies
572 // Mark it as unconfirmed as long as it is not the non-local flag
573 depGraphLocal[*I] = std::make_pair(NewDependency, NewDependencyConfirmed);
576 reverseDep.erase(RemInst);
578 if (reverseDepNonLocal.count(RemInst)) {
579 SmallPtrSet<Instruction*, 4>& set = reverseDepNonLocal[RemInst];
580 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
582 for (DenseMap<BasicBlock*, Value*>::iterator DI =
583 depGraphNonLocal[*I].begin(), DE = depGraphNonLocal[*I].end();
585 if (DI->second == RemInst)
590 reverseDepNonLocal.erase(RemInst);
591 depGraphNonLocal.erase(RemInst);
593 getAnalysis<AliasAnalysis>().deleteValue(RemInst);
595 DEBUG(verifyRemoved(RemInst));