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"
27 char MemoryDependenceAnalysis::ID = 0;
29 const Instruction* MemoryDependenceAnalysis::NonLocal = (Instruction*)-3;
30 const Instruction* MemoryDependenceAnalysis::None = (Instruction*)-4;
32 // Register this pass...
33 static RegisterPass<MemoryDependenceAnalysis> X("memdep",
34 "Memory Dependence Analysis");
36 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
38 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
40 AU.addRequiredTransitive<AliasAnalysis>();
41 AU.addRequiredTransitive<TargetData>();
44 /// getCallSiteDependency - Private helper for finding the local dependencies
46 const Instruction* MemoryDependenceAnalysis::getCallSiteDependency(CallSite C,
50 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
51 TargetData& TD = getAnalysis<TargetData>();
52 BasicBlock::iterator blockBegin = C.getInstruction()->getParent()->begin();
53 BasicBlock::iterator QI = C.getInstruction();
55 // If the starting point was specifiy, use it
58 blockBegin = start->getParent()->end();
59 // If the starting point wasn't specified, but the block was, use it
60 } else if (!start && block) {
62 blockBegin = block->end();
65 // Walk backwards through the block, looking for dependencies
66 while (QI != blockBegin) {
69 // If this inst is a memory op, get the pointer it accessed
71 uint64_t pointerSize = 0;
72 if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
73 pointer = S->getPointerOperand();
74 pointerSize = TD.getTypeSize(S->getOperand(0)->getType());
75 } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
76 pointer = L->getPointerOperand();
77 pointerSize = TD.getTypeSize(L->getType());
78 } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
80 if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
81 pointerSize = C->getZExtValue() * \
82 TD.getTypeSize(AI->getAllocatedType());
85 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
86 pointer = V->getOperand(0);
87 pointerSize = TD.getTypeSize(V->getType());
88 } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
89 pointer = F->getPointerOperand();
91 // FreeInsts erase the entire structure
93 } else if (CallSite::get(QI).getInstruction() != 0) {
94 if (AA.getModRefInfo(C, CallSite::get(QI)) != AliasAnalysis::NoModRef) {
95 if (!start && !block) {
96 depGraphLocal.insert(std::make_pair(C.getInstruction(),
97 std::make_pair(QI, true)));
98 reverseDep[QI].insert(C.getInstruction());
107 if (AA.getModRefInfo(C, pointer, pointerSize) != AliasAnalysis::NoModRef) {
108 if (!start && !block) {
109 depGraphLocal.insert(std::make_pair(C.getInstruction(),
110 std::make_pair(QI, true)));
111 reverseDep[QI].insert(C.getInstruction());
117 // No dependence found
118 depGraphLocal.insert(std::make_pair(C.getInstruction(),
119 std::make_pair(NonLocal, true)));
120 reverseDep[NonLocal].insert(C.getInstruction());
124 /// nonLocalHelper - Private helper used to calculate non-local dependencies
125 /// by doing DFS on the predecessors of a block to find its dependencies
126 void MemoryDependenceAnalysis::nonLocalHelper(Instruction* query,
128 DenseMap<BasicBlock*, Value*>& resp) {
129 // Set of blocks that we've already visited in our DFS
130 SmallPtrSet<BasicBlock*, 4> visited;
131 // Current stack of the DFS
132 SmallVector<BasicBlock*, 4> stack;
133 stack.push_back(block);
136 while (!stack.empty()) {
137 BasicBlock* BB = stack.back();
139 // If we've already visited this block, no need to revist
140 if (visited.count(BB)) {
145 // If we find a new block with a local dependency for query,
146 // then we insert the new dependency and backtrack.
150 const Instruction* localDep = getDependency(query, 0, BB);
151 if (localDep != NonLocal) {
152 resp.insert(std::make_pair(BB, const_cast<Instruction*>(localDep)));
157 // If we re-encounter the starting block, we still need to search it
158 // because there might be a dependency in the starting block AFTER
159 // the position of the query. This is necessary to get loops right.
160 } else if (BB == block && stack.size() > 1) {
163 const Instruction* localDep = getDependency(query, 0, BB);
164 if (localDep != query)
165 resp.insert(std::make_pair(BB, const_cast<Instruction*>(localDep)));
172 // If we didn't find anything, recurse on the precessors of this block
173 bool predOnStack = false;
174 bool inserted = false;
175 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
177 if (!visited.count(*PI)) {
178 stack.push_back(*PI);
183 // If we inserted a new predecessor, then we'll come back to this block
186 // If we didn't insert because we have no predecessors, then this
187 // query has no dependency at all.
188 else if (!inserted && !predOnStack) {
189 resp.insert(std::make_pair(BB, const_cast<Instruction*>(None)));
190 // If we didn't insert because our predecessors are already on the stack,
191 // then we might still have a dependency, but it will be discovered during
193 } else if (!inserted && predOnStack){
194 resp.insert(std::make_pair(BB, const_cast<Instruction*>(NonLocal)));
201 /// getNonLocalDependency - Fills the passed-in map with the non-local
202 /// dependencies of the queries. The map will contain NonLocal for
203 /// blocks between the query and its dependencies.
204 void MemoryDependenceAnalysis::getNonLocalDependency(Instruction* query,
205 DenseMap<BasicBlock*, Value*>& resp) {
206 // First check that we don't actually have a local dependency.
207 const Instruction* localDep = getDependency(query);
208 if (localDep != NonLocal) {
209 resp.insert(std::make_pair(query->getParent(),
210 const_cast<Instruction*>(localDep)));
214 // If not, go ahead and search for non-local ones.
215 nonLocalHelper(query, query->getParent(), resp);
218 /// getDependency - Return the instruction on which a memory operation
219 /// depends. The local paramter indicates if the query should only
220 /// evaluate dependencies within the same basic block.
221 const Instruction* MemoryDependenceAnalysis::getDependency(Instruction* query,
224 // Start looking for dependencies with the queried inst
225 BasicBlock::iterator QI = query;
227 // Check for a cached result
228 std::pair<const Instruction*, bool> cachedResult = depGraphLocal[query];
229 // If we have a _confirmed_ cached entry, return it
230 if (cachedResult.second)
231 return cachedResult.first;
232 else if (cachedResult.first && cachedResult.first != NonLocal)
233 // If we have an unconfirmed cached entry, we can start our search from there
234 QI = const_cast<Instruction*>(cachedResult.first);
238 else if (!start && block)
241 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
242 TargetData& TD = getAnalysis<TargetData>();
244 // Get the pointer value for which dependence will be determined
246 uint64_t dependeeSize = 0;
247 bool queryIsVolatile = false;
248 if (StoreInst* S = dyn_cast<StoreInst>(query)) {
249 dependee = S->getPointerOperand();
250 dependeeSize = TD.getTypeSize(S->getOperand(0)->getType());
251 queryIsVolatile = S->isVolatile();
252 } else if (LoadInst* L = dyn_cast<LoadInst>(query)) {
253 dependee = L->getPointerOperand();
254 dependeeSize = TD.getTypeSize(L->getType());
255 queryIsVolatile = L->isVolatile();
256 } else if (VAArgInst* V = dyn_cast<VAArgInst>(query)) {
257 dependee = V->getOperand(0);
258 dependeeSize = TD.getTypeSize(V->getType());
259 } else if (FreeInst* F = dyn_cast<FreeInst>(query)) {
260 dependee = F->getPointerOperand();
262 // FreeInsts erase the entire structure, not just a field
264 } else if (CallSite::get(query).getInstruction() != 0)
265 return getCallSiteDependency(CallSite::get(query), start, block);
266 else if (isa<AllocationInst>(query))
271 BasicBlock::iterator blockBegin = block ? block->begin()
272 : query->getParent()->begin();
274 // Walk backwards through the basic block, looking for dependencies
275 while (QI != blockBegin) {
278 // If this inst is a memory op, get the pointer it accessed
280 uint64_t pointerSize = 0;
281 if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
282 // All volatile loads/stores depend on each other
283 if (queryIsVolatile && S->isVolatile()) {
284 if (!start && !block) {
285 depGraphLocal.insert(std::make_pair(query, std::make_pair(S, true)));
286 reverseDep[S].insert(query);
292 pointer = S->getPointerOperand();
293 pointerSize = TD.getTypeSize(S->getOperand(0)->getType());
294 } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
295 // All volatile loads/stores depend on each other
296 if (queryIsVolatile && L->isVolatile()) {
297 if (!start && !block) {
298 depGraphLocal.insert(std::make_pair(query, std::make_pair(L, true)));
299 reverseDep[L].insert(query);
305 pointer = L->getPointerOperand();
306 pointerSize = TD.getTypeSize(L->getType());
307 } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
309 if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
310 pointerSize = C->getZExtValue() * \
311 TD.getTypeSize(AI->getAllocatedType());
314 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
315 pointer = V->getOperand(0);
316 pointerSize = TD.getTypeSize(V->getType());
317 } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
318 pointer = F->getPointerOperand();
320 // FreeInsts erase the entire structure
322 } else if (CallSite::get(QI).getInstruction() != 0) {
323 // Call insts need special handling. Check if they can modify our pointer
324 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(CallSite::get(QI),
325 dependee, dependeeSize);
327 if (MR != AliasAnalysis::NoModRef) {
328 // Loads don't depend on read-only calls
329 if (isa<LoadInst>(query) && MR == AliasAnalysis::Ref)
332 if (!start && !block) {
333 depGraphLocal.insert(std::make_pair(query,
334 std::make_pair(QI, true)));
335 reverseDep[QI].insert(query);
344 // If we found a pointer, check if it could be the same as our pointer
346 AliasAnalysis::AliasResult R = AA.alias(pointer, pointerSize,
347 dependee, dependeeSize);
349 if (R != AliasAnalysis::NoAlias) {
350 // May-alias loads don't depend on each other
351 if (isa<LoadInst>(query) && isa<LoadInst>(QI) &&
352 R == AliasAnalysis::MayAlias)
355 if (!start && !block) {
356 depGraphLocal.insert(std::make_pair(query,
357 std::make_pair(QI, true)));
358 reverseDep[QI].insert(query);
366 // If we found nothing, return the non-local flag
367 if (!start && !block) {
368 depGraphLocal.insert(std::make_pair(query,
369 std::make_pair(NonLocal, true)));
370 reverseDep[NonLocal].insert(query);
376 /// removeInstruction - Remove an instruction from the dependence analysis,
377 /// updating the dependence of instructions that previously depended on it.
378 /// This method attempts to keep the cache coherent using the reverse map.
379 void MemoryDependenceAnalysis::removeInstruction(Instruction* rem) {
380 // Figure out the new dep for things that currently depend on rem
381 const Instruction* newDep = NonLocal;
383 depMapType::iterator depGraphEntry = depGraphLocal.find(rem);
384 // We assume here that it's not in the reverse map if it's not in
385 // the dep map. Checking it could be expensive, so don't do it.
387 if (depGraphEntry != depGraphLocal.end()) {
388 if (depGraphEntry->second.first != NonLocal &&
389 depGraphEntry->second.second) {
390 // If we have dep info for rem, set them to it
391 BasicBlock::iterator RI =
392 const_cast<Instruction*>(depGraphEntry->second.first);
395 } else if (depGraphEntry->second.first == NonLocal &&
396 depGraphEntry->second.second ) {
397 // If we have a confirmed non-local flag, use it
400 // Otherwise, use the immediate successor of rem
401 // NOTE: This is because, when getDependence is called, it will first
402 // check the immediate predecessor of what is in the cache.
403 BasicBlock::iterator RI = rem;
408 SmallPtrSet<Instruction*, 4>& set = reverseDep[rem];
409 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
411 // Insert the new dependencies
412 // Mark it as unconfirmed as long as it is not the non-local flag
413 depGraphLocal[*I] = std::make_pair(newDep, !newDep);
415 reverseDep.erase(rem);
418 getAnalysis<AliasAnalysis>().deleteValue(rem);