1 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the Owen Anderson and is distributed under
6 // the University of Illinois Open Source 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;
38 // Register this pass...
39 static RegisterPass<MemoryDependenceAnalysis> X("memdep",
40 "Memory Dependence Analysis");
42 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
44 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.addRequiredTransitive<AliasAnalysis>();
47 AU.addRequiredTransitive<TargetData>();
50 /// getCallSiteDependency - Private helper for finding the local dependencies
52 Instruction* MemoryDependenceAnalysis::getCallSiteDependency(CallSite C,
56 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
57 TargetData& TD = getAnalysis<TargetData>();
58 BasicBlock::iterator blockBegin = C.getInstruction()->getParent()->begin();
59 BasicBlock::iterator QI = C.getInstruction();
61 // If the starting point was specifiy, use it
64 blockBegin = start->getParent()->end();
65 // If the starting point wasn't specified, but the block was, use it
66 } else if (!start && block) {
68 blockBegin = block->end();
71 // Walk backwards through the block, looking for dependencies
72 while (QI != blockBegin) {
75 // If this inst is a memory op, get the pointer it accessed
77 uint64_t pointerSize = 0;
78 if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
79 pointer = S->getPointerOperand();
80 pointerSize = TD.getTypeSize(S->getOperand(0)->getType());
81 } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
82 pointer = L->getPointerOperand();
83 pointerSize = TD.getTypeSize(L->getType());
84 } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
86 if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
87 pointerSize = C->getZExtValue() * \
88 TD.getTypeSize(AI->getAllocatedType());
91 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
92 pointer = V->getOperand(0);
93 pointerSize = TD.getTypeSize(V->getType());
94 } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
95 pointer = F->getPointerOperand();
97 // FreeInsts erase the entire structure
99 } else if (CallSite::get(QI).getInstruction() != 0) {
100 if (AA.getModRefInfo(C, CallSite::get(QI)) != AliasAnalysis::NoModRef) {
101 if (!start && !block) {
102 depGraphLocal.insert(std::make_pair(C.getInstruction(),
103 std::make_pair(QI, true)));
104 reverseDep[QI].insert(C.getInstruction());
113 if (AA.getModRefInfo(C, pointer, pointerSize) != AliasAnalysis::NoModRef) {
114 if (!start && !block) {
115 depGraphLocal.insert(std::make_pair(C.getInstruction(),
116 std::make_pair(QI, true)));
117 reverseDep[QI].insert(C.getInstruction());
123 // No dependence found
124 depGraphLocal.insert(std::make_pair(C.getInstruction(),
125 std::make_pair(NonLocal, true)));
126 reverseDep[NonLocal].insert(C.getInstruction());
130 /// nonLocalHelper - Private helper used to calculate non-local dependencies
131 /// by doing DFS on the predecessors of a block to find its dependencies
132 void MemoryDependenceAnalysis::nonLocalHelper(Instruction* query,
134 DenseMap<BasicBlock*, Value*>& resp) {
135 // Set of blocks that we've already visited in our DFS
136 SmallPtrSet<BasicBlock*, 4> visited;
137 // Current stack of the DFS
138 SmallVector<BasicBlock*, 4> stack;
139 stack.push_back(block);
142 while (!stack.empty()) {
143 BasicBlock* BB = stack.back();
145 // If we've already visited this block, no need to revist
146 if (visited.count(BB)) {
151 // If we find a new block with a local dependency for query,
152 // then we insert the new dependency and backtrack.
156 Instruction* localDep = getDependency(query, 0, BB);
157 if (localDep != NonLocal) {
158 resp.insert(std::make_pair(BB, localDep));
163 // If we re-encounter the starting block, we still need to search it
164 // because there might be a dependency in the starting block AFTER
165 // the position of the query. This is necessary to get loops right.
166 } else if (BB == block && stack.size() > 1) {
169 Instruction* localDep = getDependency(query, 0, BB);
170 if (localDep != query)
171 resp.insert(std::make_pair(BB, localDep));
178 // If we didn't find anything, recurse on the precessors of this block
179 bool predOnStack = false;
180 bool inserted = false;
181 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
183 if (!visited.count(*PI)) {
184 stack.push_back(*PI);
189 // If we inserted a new predecessor, then we'll come back to this block
192 // If we didn't insert because we have no predecessors, then this
193 // query has no dependency at all.
194 else if (!inserted && !predOnStack) {
195 resp.insert(std::make_pair(BB, None));
196 // If we didn't insert because our predecessors are already on the stack,
197 // then we might still have a dependency, but it will be discovered during
199 } else if (!inserted && predOnStack){
200 resp.insert(std::make_pair(BB, NonLocal));
207 /// getNonLocalDependency - Fills the passed-in map with the non-local
208 /// dependencies of the queries. The map will contain NonLocal for
209 /// blocks between the query and its dependencies.
210 void MemoryDependenceAnalysis::getNonLocalDependency(Instruction* query,
211 DenseMap<BasicBlock*, Value*>& resp) {
212 if (depGraphNonLocal.count(query)) {
213 resp = depGraphNonLocal[query];
217 NumUncacheNonlocal++;
219 // If not, go ahead and search for non-local deps.
220 nonLocalHelper(query, query->getParent(), resp);
222 // Update the non-local dependency cache
223 for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(), E = resp.end();
225 depGraphNonLocal[query].insert(*I);
226 reverseDepNonLocal[I->second].insert(query);
230 /// getDependency - Return the instruction on which a memory operation
231 /// depends. The local paramter indicates if the query should only
232 /// evaluate dependencies within the same basic block.
233 Instruction* MemoryDependenceAnalysis::getDependency(Instruction* query,
236 // Start looking for dependencies with the queried inst
237 BasicBlock::iterator QI = query;
239 // Check for a cached result
240 std::pair<Instruction*, bool> cachedResult = depGraphLocal[query];
241 // If we have a _confirmed_ cached entry, return it
242 if (cachedResult.second)
243 return cachedResult.first;
244 else if (cachedResult.first && cachedResult.first != NonLocal)
245 // If we have an unconfirmed cached entry, we can start our search from there
246 QI = cachedResult.first;
250 else if (!start && block)
253 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
254 TargetData& TD = getAnalysis<TargetData>();
256 // Get the pointer value for which dependence will be determined
258 uint64_t dependeeSize = 0;
259 bool queryIsVolatile = false;
260 if (StoreInst* S = dyn_cast<StoreInst>(query)) {
261 dependee = S->getPointerOperand();
262 dependeeSize = TD.getTypeSize(S->getOperand(0)->getType());
263 queryIsVolatile = S->isVolatile();
264 } else if (LoadInst* L = dyn_cast<LoadInst>(query)) {
265 dependee = L->getPointerOperand();
266 dependeeSize = TD.getTypeSize(L->getType());
267 queryIsVolatile = L->isVolatile();
268 } else if (VAArgInst* V = dyn_cast<VAArgInst>(query)) {
269 dependee = V->getOperand(0);
270 dependeeSize = TD.getTypeSize(V->getType());
271 } else if (FreeInst* F = dyn_cast<FreeInst>(query)) {
272 dependee = F->getPointerOperand();
274 // FreeInsts erase the entire structure, not just a field
276 } else if (CallSite::get(query).getInstruction() != 0)
277 return getCallSiteDependency(CallSite::get(query), start, block);
278 else if (isa<AllocationInst>(query))
283 BasicBlock::iterator blockBegin = block ? block->begin()
284 : query->getParent()->begin();
286 // Walk backwards through the basic block, looking for dependencies
287 while (QI != blockBegin) {
290 // If this inst is a memory op, get the pointer it accessed
292 uint64_t pointerSize = 0;
293 if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
294 // All volatile loads/stores depend on each other
295 if (queryIsVolatile && S->isVolatile()) {
296 if (!start && !block) {
297 depGraphLocal.insert(std::make_pair(query, std::make_pair(S, true)));
298 reverseDep[S].insert(query);
304 pointer = S->getPointerOperand();
305 pointerSize = TD.getTypeSize(S->getOperand(0)->getType());
306 } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
307 // All volatile loads/stores depend on each other
308 if (queryIsVolatile && L->isVolatile()) {
309 if (!start && !block) {
310 depGraphLocal.insert(std::make_pair(query, std::make_pair(L, true)));
311 reverseDep[L].insert(query);
317 pointer = L->getPointerOperand();
318 pointerSize = TD.getTypeSize(L->getType());
319 } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
321 if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
322 pointerSize = C->getZExtValue() * \
323 TD.getTypeSize(AI->getAllocatedType());
326 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
327 pointer = V->getOperand(0);
328 pointerSize = TD.getTypeSize(V->getType());
329 } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
330 pointer = F->getPointerOperand();
332 // FreeInsts erase the entire structure
334 } else if (CallSite::get(QI).getInstruction() != 0) {
335 // Call insts need special handling. Check if they can modify our pointer
336 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(CallSite::get(QI),
337 dependee, dependeeSize);
339 if (MR != AliasAnalysis::NoModRef) {
340 // Loads don't depend on read-only calls
341 if (isa<LoadInst>(query) && MR == AliasAnalysis::Ref)
344 if (!start && !block) {
345 depGraphLocal.insert(std::make_pair(query,
346 std::make_pair(QI, true)));
347 reverseDep[QI].insert(query);
356 // If we found a pointer, check if it could be the same as our pointer
358 AliasAnalysis::AliasResult R = AA.alias(pointer, pointerSize,
359 dependee, dependeeSize);
361 if (R != AliasAnalysis::NoAlias) {
362 // May-alias loads don't depend on each other
363 if (isa<LoadInst>(query) && isa<LoadInst>(QI) &&
364 R == AliasAnalysis::MayAlias)
367 if (!start && !block) {
368 depGraphLocal.insert(std::make_pair(query,
369 std::make_pair(QI, true)));
370 reverseDep[QI].insert(query);
378 // If we found nothing, return the non-local flag
379 if (!start && !block) {
380 depGraphLocal.insert(std::make_pair(query,
381 std::make_pair(NonLocal, true)));
382 reverseDep[NonLocal].insert(query);
388 /// removeInstruction - Remove an instruction from the dependence analysis,
389 /// updating the dependence of instructions that previously depended on it.
390 /// This method attempts to keep the cache coherent using the reverse map.
391 void MemoryDependenceAnalysis::removeInstruction(Instruction* rem) {
392 // Figure out the new dep for things that currently depend on rem
393 Instruction* newDep = NonLocal;
395 depMapType::iterator depGraphEntry = depGraphLocal.find(rem);
397 if (depGraphEntry != depGraphLocal.end()) {
398 if (depGraphEntry->second.first != NonLocal &&
399 depGraphEntry->second.second) {
400 // If we have dep info for rem, set them to it
401 BasicBlock::iterator RI = depGraphEntry->second.first;
404 } else if (depGraphEntry->second.first == NonLocal &&
405 depGraphEntry->second.second ) {
406 // If we have a confirmed non-local flag, use it
409 // Otherwise, use the immediate successor of rem
410 // NOTE: This is because, when getDependence is called, it will first
411 // check the immediate predecessor of what is in the cache.
412 BasicBlock::iterator RI = rem;
417 SmallPtrSet<Instruction*, 4>& set = reverseDep[rem];
418 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
420 // Insert the new dependencies
421 // Mark it as unconfirmed as long as it is not the non-local flag
422 depGraphLocal[*I] = std::make_pair(newDep, !newDep);
425 reverseDep.erase(rem);
428 if (depGraphNonLocal.count(rem)) {
429 SmallPtrSet<Instruction*, 4>& set = reverseDepNonLocal[rem];
430 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
432 depGraphNonLocal.erase(*I);
434 reverseDepNonLocal.erase(rem);
437 getAnalysis<AliasAnalysis>().deleteValue(rem);