1 //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This simple pass provides alias and mod/ref information for global values
11 // that do not have their address taken, and keeps track of whether functions
12 // read or write memory (are "pure"). For this simple (but very common) case,
13 // we can provide pretty accurate and useful information.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "globalsmodref-aa"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/CallGraph.h"
26 #include "llvm/Support/InstIterator.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/SCCIterator.h"
33 STATISTIC(NumNonAddrTakenGlobalVars,
34 "Number of global vars without address taken");
35 STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
36 STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
37 STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
38 STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
41 /// FunctionRecord - One instance of this structure is stored for every
42 /// function in the program. Later, the entries for these functions are
43 /// removed if the function is found to call an external function (in which
44 /// case we know nothing about it.
45 struct FunctionRecord {
46 /// GlobalInfo - Maintain mod/ref info for all of the globals without
47 /// addresses taken that are read or written (transitively) by this
49 std::map<GlobalValue*, unsigned> GlobalInfo;
51 unsigned getInfoForGlobal(GlobalValue *GV) const {
52 std::map<GlobalValue*, unsigned>::const_iterator I = GlobalInfo.find(GV);
53 if (I != GlobalInfo.end())
58 /// FunctionEffect - Capture whether or not this function reads or writes to
59 /// ANY memory. If not, we can do a lot of aggressive analysis on it.
60 unsigned FunctionEffect;
62 FunctionRecord() : FunctionEffect(0) {}
65 /// GlobalsModRef - The actual analysis pass.
66 class GlobalsModRef : public ModulePass, public AliasAnalysis {
67 /// NonAddressTakenGlobals - The globals that do not have their addresses
69 std::set<GlobalValue*> NonAddressTakenGlobals;
71 /// IndirectGlobals - The memory pointed to by this global is known to be
72 /// 'owned' by the global.
73 std::set<GlobalValue*> IndirectGlobals;
75 /// AllocsForIndirectGlobals - If an instruction allocates memory for an
76 /// indirect global, this map indicates which one.
77 std::map<Value*, GlobalValue*> AllocsForIndirectGlobals;
79 /// FunctionInfo - For each function, keep track of what globals are
81 std::map<Function*, FunctionRecord> FunctionInfo;
84 bool runOnModule(Module &M) {
85 InitializeAliasAnalysis(this); // set up super class
86 AnalyzeGlobals(M); // find non-addr taken globals
87 AnalyzeCallGraph(getAnalysis<CallGraph>(), M); // Propagate on CG
91 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92 AliasAnalysis::getAnalysisUsage(AU);
93 AU.addRequired<CallGraph>();
94 AU.setPreservesAll(); // Does not transform code
97 //------------------------------------------------
98 // Implement the AliasAnalysis API
100 AliasResult alias(const Value *V1, unsigned V1Size,
101 const Value *V2, unsigned V2Size);
102 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
103 ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
104 return AliasAnalysis::getModRefInfo(CS1,CS2);
106 bool hasNoModRefInfoForCalls() const { return false; }
108 /// getModRefBehavior - Return the behavior of the specified function if
109 /// called from the specified call site. The call site may be null in which
110 /// case the most generic behavior of this function should be returned.
111 virtual ModRefBehavior getModRefBehavior(Function *F, CallSite CS,
112 std::vector<PointerAccessInfo> *Info) {
113 if (FunctionRecord *FR = getFunctionInfo(F))
114 if (FR->FunctionEffect == 0)
115 return DoesNotAccessMemory;
116 else if ((FR->FunctionEffect & Mod) == 0)
117 return OnlyReadsMemory;
118 return AliasAnalysis::getModRefBehavior(F, CS, Info);
121 virtual void deleteValue(Value *V);
122 virtual void copyValue(Value *From, Value *To);
125 /// getFunctionInfo - Return the function info for the function, or null if
126 /// the function calls an external function (in which case we don't have
127 /// anything useful to say about it).
128 FunctionRecord *getFunctionInfo(Function *F) {
129 std::map<Function*, FunctionRecord>::iterator I = FunctionInfo.find(F);
130 if (I != FunctionInfo.end())
135 void AnalyzeGlobals(Module &M);
136 void AnalyzeCallGraph(CallGraph &CG, Module &M);
137 void AnalyzeSCC(std::vector<CallGraphNode *> &SCC);
138 bool AnalyzeUsesOfPointer(Value *V, std::vector<Function*> &Readers,
139 std::vector<Function*> &Writers,
140 GlobalValue *OkayStoreDest = 0);
141 bool AnalyzeIndirectGlobalMemory(GlobalValue *GV);
144 RegisterPass<GlobalsModRef> X("globalsmodref-aa",
145 "Simple mod/ref analysis for globals");
146 RegisterAnalysisGroup<AliasAnalysis> Y(X);
149 Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
151 /// getUnderlyingObject - This traverses the use chain to figure out what object
152 /// the specified value points to. If the value points to, or is derived from,
153 /// a global object, return it.
154 static Value *getUnderlyingObject(Value *V) {
155 if (!isa<PointerType>(V->getType())) return V;
157 // If we are at some type of object... return it.
158 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
160 // Traverse through different addressing mechanisms.
161 if (Instruction *I = dyn_cast<Instruction>(V)) {
162 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I))
163 return getUnderlyingObject(I->getOperand(0));
164 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
165 if (CE->getOpcode() == Instruction::BitCast ||
166 CE->getOpcode() == Instruction::GetElementPtr)
167 return getUnderlyingObject(CE->getOperand(0));
170 // Othewise, we don't know what this is, return it as the base pointer.
174 /// AnalyzeGlobals - Scan through the users of all of the internal
175 /// GlobalValue's in the program. If none of them have their "Address taken"
176 /// (really, their address passed to something nontrivial), record this fact,
177 /// and record the functions that they are used directly in.
178 void GlobalsModRef::AnalyzeGlobals(Module &M) {
179 std::vector<Function*> Readers, Writers;
180 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
181 if (I->hasInternalLinkage()) {
182 if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
183 // Remember that we are tracking this global.
184 NonAddressTakenGlobals.insert(I);
185 ++NumNonAddrTakenFunctions;
187 Readers.clear(); Writers.clear();
190 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
192 if (I->hasInternalLinkage()) {
193 if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
194 // Remember that we are tracking this global, and the mod/ref fns
195 NonAddressTakenGlobals.insert(I);
196 for (unsigned i = 0, e = Readers.size(); i != e; ++i)
197 FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
199 if (!I->isConstant()) // No need to keep track of writers to constants
200 for (unsigned i = 0, e = Writers.size(); i != e; ++i)
201 FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
202 ++NumNonAddrTakenGlobalVars;
204 // If this global holds a pointer type, see if it is an indirect global.
205 if (isa<PointerType>(I->getType()->getElementType()) &&
206 AnalyzeIndirectGlobalMemory(I))
207 ++NumIndirectGlobalVars;
209 Readers.clear(); Writers.clear();
213 /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
214 /// If this is used by anything complex (i.e., the address escapes), return
215 /// true. Also, while we are at it, keep track of those functions that read and
216 /// write to the value.
218 /// If OkayStoreDest is non-null, stores into this global are allowed.
219 bool GlobalsModRef::AnalyzeUsesOfPointer(Value *V,
220 std::vector<Function*> &Readers,
221 std::vector<Function*> &Writers,
222 GlobalValue *OkayStoreDest) {
223 if (!isa<PointerType>(V->getType())) return true;
225 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
226 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
227 Readers.push_back(LI->getParent()->getParent());
228 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
229 if (V == SI->getOperand(1)) {
230 Writers.push_back(SI->getParent()->getParent());
231 } else if (SI->getOperand(1) != OkayStoreDest) {
232 return true; // Storing the pointer
234 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
235 if (AnalyzeUsesOfPointer(GEP, Readers, Writers)) return true;
236 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
237 // Make sure that this is just the function being called, not that it is
238 // passing into the function.
239 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
240 if (CI->getOperand(i) == V) return true;
241 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
242 // Make sure that this is just the function being called, not that it is
243 // passing into the function.
244 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
245 if (II->getOperand(i) == V) return true;
246 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
247 if (CE->getOpcode() == Instruction::GetElementPtr ||
248 CE->getOpcode() == Instruction::BitCast) {
249 if (AnalyzeUsesOfPointer(CE, Readers, Writers))
254 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
255 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
256 return true; // Allow comparison against null.
257 } else if (FreeInst *F = dyn_cast<FreeInst>(*UI)) {
258 Writers.push_back(F->getParent()->getParent());
265 /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
266 /// which holds a pointer type. See if the global always points to non-aliased
267 /// heap memory: that is, all initializers of the globals are allocations, and
268 /// those allocations have no use other than initialization of the global.
269 /// Further, all loads out of GV must directly use the memory, not store the
270 /// pointer somewhere. If this is true, we consider the memory pointed to by
271 /// GV to be owned by GV and can disambiguate other pointers from it.
272 bool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
273 // Keep track of values related to the allocation of the memory, f.e. the
274 // value produced by the malloc call and any casts.
275 std::vector<Value*> AllocRelatedValues;
277 // Walk the user list of the global. If we find anything other than a direct
278 // load or store, bail out.
279 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
280 if (LoadInst *LI = dyn_cast<LoadInst>(*I)) {
281 // The pointer loaded from the global can only be used in simple ways:
282 // we allow addressing of it and loading storing to it. We do *not* allow
283 // storing the loaded pointer somewhere else or passing to a function.
284 std::vector<Function*> ReadersWriters;
285 if (AnalyzeUsesOfPointer(LI, ReadersWriters, ReadersWriters))
286 return false; // Loaded pointer escapes.
287 // TODO: Could try some IP mod/ref of the loaded pointer.
288 } else if (StoreInst *SI = dyn_cast<StoreInst>(*I)) {
289 // Storing the global itself.
290 if (SI->getOperand(0) == GV) return false;
292 // If storing the null pointer, ignore it.
293 if (isa<ConstantPointerNull>(SI->getOperand(0)))
296 // Check the value being stored.
297 Value *Ptr = getUnderlyingObject(SI->getOperand(0));
299 if (isa<MallocInst>(Ptr)) {
301 } else if (CallInst *CI = dyn_cast<CallInst>(Ptr)) {
302 Function *F = CI->getCalledFunction();
303 if (!F || !F->isExternal()) return false; // Too hard to analyze.
304 if (F->getName() != "calloc") return false; // Not calloc.
306 return false; // Too hard to analyze.
309 // Analyze all uses of the allocation. If any of them are used in a
310 // non-simple way (e.g. stored to another global) bail out.
311 std::vector<Function*> ReadersWriters;
312 if (AnalyzeUsesOfPointer(Ptr, ReadersWriters, ReadersWriters, GV))
313 return false; // Loaded pointer escapes.
315 // Remember that this allocation is related to the indirect global.
316 AllocRelatedValues.push_back(Ptr);
318 // Something complex, bail out.
323 // Okay, this is an indirect global. Remember all of the allocations for
324 // this global in AllocsForIndirectGlobals.
325 while (!AllocRelatedValues.empty()) {
326 AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
327 AllocRelatedValues.pop_back();
329 IndirectGlobals.insert(GV);
333 /// AnalyzeCallGraph - At this point, we know the functions where globals are
334 /// immediately stored to and read from. Propagate this information up the call
335 /// graph to all callers and compute the mod/ref info for all memory for each
337 void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
338 // We do a bottom-up SCC traversal of the call graph. In other words, we
339 // visit all callees before callers (leaf-first).
340 for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I!=E; ++I)
341 if ((*I).size() != 1) {
343 } else if (Function *F = (*I)[0]->getFunction()) {
344 if (!F->isExternal()) {
345 // Nonexternal function.
348 // Otherwise external function. Handle intrinsics and other special
350 if (getAnalysis<AliasAnalysis>().doesNotAccessMemory(F))
351 // If it does not access memory, process the function, causing us to
352 // realize it doesn't do anything (the body is empty).
355 // Otherwise, don't process it. This will cause us to conservatively
360 // Do not process the external node, assume the worst.
364 void GlobalsModRef::AnalyzeSCC(std::vector<CallGraphNode *> &SCC) {
365 assert(!SCC.empty() && "SCC with no functions?");
366 FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
368 bool CallsExternal = false;
369 unsigned FunctionEffect = 0;
371 // Collect the mod/ref properties due to called functions. We only compute
373 for (unsigned i = 0, e = SCC.size(); i != e && !CallsExternal; ++i)
374 for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
376 if (Function *Callee = CI->second->getFunction()) {
377 if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
378 // Propagate function effect up.
379 FunctionEffect |= CalleeFR->FunctionEffect;
381 // Incorporate callee's effects on globals into our info.
382 for (std::map<GlobalValue*, unsigned>::iterator GI =
383 CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end();
385 FR.GlobalInfo[GI->first] |= GI->second;
388 // Okay, if we can't say anything about it, maybe some other alias
391 AliasAnalysis::getModRefBehavior(Callee, CallSite());
392 if (MRB != DoesNotAccessMemory) {
393 // FIXME: could make this more aggressive for functions that just
394 // read memory. We should just say they read all globals.
395 CallsExternal = true;
400 CallsExternal = true;
404 // If this SCC calls an external function, we can't say anything about it, so
405 // remove all SCC functions from the FunctionInfo map.
407 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
408 FunctionInfo.erase(SCC[i]->getFunction());
412 // Otherwise, unless we already know that this function mod/refs memory, scan
413 // the function bodies to see if there are any explicit loads or stores.
414 if (FunctionEffect != ModRef) {
415 for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i)
416 for (inst_iterator II = inst_begin(SCC[i]->getFunction()),
417 E = inst_end(SCC[i]->getFunction());
418 II != E && FunctionEffect != ModRef; ++II)
419 if (isa<LoadInst>(*II))
420 FunctionEffect |= Ref;
421 else if (isa<StoreInst>(*II))
422 FunctionEffect |= Mod;
423 else if (isa<MallocInst>(*II) || isa<FreeInst>(*II))
424 FunctionEffect |= ModRef;
427 if ((FunctionEffect & Mod) == 0)
428 ++NumReadMemFunctions;
429 if (FunctionEffect == 0)
431 FR.FunctionEffect = FunctionEffect;
433 // Finally, now that we know the full effect on this SCC, clone the
434 // information to each function in the SCC.
435 for (unsigned i = 1, e = SCC.size(); i != e; ++i)
436 FunctionInfo[SCC[i]->getFunction()] = FR;
441 /// alias - If one of the pointers is to a global that we are tracking, and the
442 /// other is some random pointer, we know there cannot be an alias, because the
443 /// address of the global isn't taken.
444 AliasAnalysis::AliasResult
445 GlobalsModRef::alias(const Value *V1, unsigned V1Size,
446 const Value *V2, unsigned V2Size) {
447 // Get the base object these pointers point to.
448 Value *UV1 = getUnderlyingObject(const_cast<Value*>(V1));
449 Value *UV2 = getUnderlyingObject(const_cast<Value*>(V2));
451 // If either of the underlying values is a global, they may be non-addr-taken
452 // globals, which we can answer queries about.
453 GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
454 GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
456 // If the global's address is taken, pretend we don't know it's a pointer to
458 if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0;
459 if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0;
461 // If the the two pointers are derived from two different non-addr-taken
462 // globals, or if one is and the other isn't, we know these can't alias.
463 if ((GV1 || GV2) && GV1 != GV2)
466 // Otherwise if they are both derived from the same addr-taken global, we
467 // can't know the two accesses don't overlap.
470 // These pointers may be based on the memory owned by an indirect global. If
471 // so, we may be able to handle this. First check to see if the base pointer
472 // is a direct load from an indirect global.
474 if (LoadInst *LI = dyn_cast<LoadInst>(UV1))
475 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
476 if (IndirectGlobals.count(GV))
478 if (LoadInst *LI = dyn_cast<LoadInst>(UV2))
479 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
480 if (IndirectGlobals.count(GV))
483 // These pointers may also be from an allocation for the indirect global. If
484 // so, also handle them.
485 if (AllocsForIndirectGlobals.count(UV1))
486 GV1 = AllocsForIndirectGlobals[UV1];
487 if (AllocsForIndirectGlobals.count(UV2))
488 GV2 = AllocsForIndirectGlobals[UV2];
490 // Now that we know whether the two pointers are related to indirect globals,
491 // use this to disambiguate the pointers. If either pointer is based on an
492 // indirect global and if they are not both based on the same indirect global,
493 // they cannot alias.
494 if ((GV1 || GV2) && GV1 != GV2)
497 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
500 AliasAnalysis::ModRefResult
501 GlobalsModRef::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
502 unsigned Known = ModRef;
504 // If we are asking for mod/ref info of a direct call with a pointer to a
505 // global we are tracking, return information if we have it.
506 if (GlobalValue *GV = dyn_cast<GlobalValue>(getUnderlyingObject(P)))
507 if (GV->hasInternalLinkage())
508 if (Function *F = CS.getCalledFunction())
509 if (NonAddressTakenGlobals.count(GV))
510 if (FunctionRecord *FR = getFunctionInfo(F))
511 Known = FR->getInfoForGlobal(GV);
513 if (Known == NoModRef)
514 return NoModRef; // No need to query other mod/ref analyses
515 return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, P, Size));
519 //===----------------------------------------------------------------------===//
520 // Methods to update the analysis as a result of the client transformation.
522 void GlobalsModRef::deleteValue(Value *V) {
523 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
524 if (NonAddressTakenGlobals.erase(GV)) {
525 // This global might be an indirect global. If so, remove it and remove
526 // any AllocRelatedValues for it.
527 if (IndirectGlobals.erase(GV)) {
528 // Remove any entries in AllocsForIndirectGlobals for this global.
529 for (std::map<Value*, GlobalValue*>::iterator
530 I = AllocsForIndirectGlobals.begin(),
531 E = AllocsForIndirectGlobals.end(); I != E; ) {
532 if (I->second == GV) {
533 AllocsForIndirectGlobals.erase(I++);
542 // Otherwise, if this is an allocation related to an indirect global, remove
544 AllocsForIndirectGlobals.erase(V);
547 void GlobalsModRef::copyValue(Value *From, Value *To) {