1 //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
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 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/Analysis/MemoryBuiltins.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/InstIterator.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/SCCIterator.h"
34 STATISTIC(NumNonAddrTakenGlobalVars,
35 "Number of global vars without address taken");
36 STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
37 STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
38 STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
39 STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
42 /// FunctionRecord - One instance of this structure is stored for every
43 /// function in the program. Later, the entries for these functions are
44 /// removed if the function is found to call an external function (in which
45 /// case we know nothing about it.
46 struct FunctionRecord {
47 /// GlobalInfo - Maintain mod/ref info for all of the globals without
48 /// addresses taken that are read or written (transitively) by this
50 std::map<const GlobalValue*, unsigned> GlobalInfo;
52 /// MayReadAnyGlobal - May read global variables, but it is not known which.
53 bool MayReadAnyGlobal;
55 unsigned getInfoForGlobal(const GlobalValue *GV) const {
56 unsigned Effect = MayReadAnyGlobal ? AliasAnalysis::Ref : 0;
57 std::map<const GlobalValue*, unsigned>::const_iterator I =
59 if (I != GlobalInfo.end())
64 /// FunctionEffect - Capture whether or not this function reads or writes to
65 /// ANY memory. If not, we can do a lot of aggressive analysis on it.
66 unsigned FunctionEffect;
68 FunctionRecord() : MayReadAnyGlobal (false), FunctionEffect(0) {}
71 /// GlobalsModRef - The actual analysis pass.
72 class GlobalsModRef : public ModulePass, public AliasAnalysis {
73 /// NonAddressTakenGlobals - The globals that do not have their addresses
75 std::set<const GlobalValue*> NonAddressTakenGlobals;
77 /// IndirectGlobals - The memory pointed to by this global is known to be
78 /// 'owned' by the global.
79 std::set<const GlobalValue*> IndirectGlobals;
81 /// AllocsForIndirectGlobals - If an instruction allocates memory for an
82 /// indirect global, this map indicates which one.
83 std::map<const Value*, const GlobalValue*> AllocsForIndirectGlobals;
85 /// FunctionInfo - For each function, keep track of what globals are
87 std::map<const Function*, FunctionRecord> FunctionInfo;
91 GlobalsModRef() : ModulePass(ID) {}
93 bool runOnModule(Module &M) {
94 InitializeAliasAnalysis(this); // set up super class
95 AnalyzeGlobals(M); // find non-addr taken globals
96 AnalyzeCallGraph(getAnalysis<CallGraph>(), M); // Propagate on CG
100 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
101 AliasAnalysis::getAnalysisUsage(AU);
102 AU.addRequired<CallGraph>();
103 AU.setPreservesAll(); // Does not transform code
106 //------------------------------------------------
107 // Implement the AliasAnalysis API
109 AliasResult alias(const Location &LocA, const Location &LocB);
110 ModRefResult getModRefInfo(ImmutableCallSite CS,
111 const Location &Loc);
112 ModRefResult getModRefInfo(ImmutableCallSite CS1,
113 ImmutableCallSite CS2) {
114 return AliasAnalysis::getModRefInfo(CS1, CS2);
117 /// getModRefBehavior - Return the behavior of the specified function if
118 /// called from the specified call site. The call site may be null in which
119 /// case the most generic behavior of this function should be returned.
120 ModRefBehavior getModRefBehavior(const Function *F) {
121 if (FunctionRecord *FR = getFunctionInfo(F)) {
122 if (FR->FunctionEffect == 0)
123 return DoesNotAccessMemory;
124 else if ((FR->FunctionEffect & Mod) == 0)
125 return OnlyReadsMemory;
127 return AliasAnalysis::getModRefBehavior(F);
130 /// getModRefBehavior - Return the behavior of the specified function if
131 /// called from the specified call site. The call site may be null in which
132 /// case the most generic behavior of this function should be returned.
133 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) {
134 const Function* F = CS.getCalledFunction();
135 if (!F) return AliasAnalysis::getModRefBehavior(CS);
136 if (FunctionRecord *FR = getFunctionInfo(F)) {
137 if (FR->FunctionEffect == 0)
138 return DoesNotAccessMemory;
139 else if ((FR->FunctionEffect & Mod) == 0)
140 return OnlyReadsMemory;
142 return AliasAnalysis::getModRefBehavior(CS);
145 virtual void deleteValue(Value *V);
146 virtual void copyValue(Value *From, Value *To);
148 /// getAdjustedAnalysisPointer - This method is used when a pass implements
149 /// an analysis interface through multiple inheritance. If needed, it
150 /// should override this to adjust the this pointer as needed for the
151 /// specified pass info.
152 virtual void *getAdjustedAnalysisPointer(AnalysisID PI) {
153 if (PI == &AliasAnalysis::ID)
154 return (AliasAnalysis*)this;
159 /// getFunctionInfo - Return the function info for the function, or null if
160 /// we don't have anything useful to say about it.
161 FunctionRecord *getFunctionInfo(const Function *F) {
162 std::map<const Function*, FunctionRecord>::iterator I =
163 FunctionInfo.find(F);
164 if (I != FunctionInfo.end())
169 void AnalyzeGlobals(Module &M);
170 void AnalyzeCallGraph(CallGraph &CG, Module &M);
171 bool AnalyzeUsesOfPointer(Value *V, std::vector<Function*> &Readers,
172 std::vector<Function*> &Writers,
173 GlobalValue *OkayStoreDest = 0);
174 bool AnalyzeIndirectGlobalMemory(GlobalValue *GV);
178 char GlobalsModRef::ID = 0;
179 INITIALIZE_AG_PASS_BEGIN(GlobalsModRef, AliasAnalysis,
180 "globalsmodref-aa", "Simple mod/ref analysis for globals",
182 INITIALIZE_AG_DEPENDENCY(CallGraph)
183 INITIALIZE_AG_PASS_END(GlobalsModRef, AliasAnalysis,
184 "globalsmodref-aa", "Simple mod/ref analysis for globals",
187 Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
189 /// AnalyzeGlobals - Scan through the users of all of the internal
190 /// GlobalValue's in the program. If none of them have their "address taken"
191 /// (really, their address passed to something nontrivial), record this fact,
192 /// and record the functions that they are used directly in.
193 void GlobalsModRef::AnalyzeGlobals(Module &M) {
194 std::vector<Function*> Readers, Writers;
195 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
196 if (I->hasLocalLinkage()) {
197 if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
198 // Remember that we are tracking this global.
199 NonAddressTakenGlobals.insert(I);
200 ++NumNonAddrTakenFunctions;
202 Readers.clear(); Writers.clear();
205 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
207 if (I->hasLocalLinkage()) {
208 if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
209 // Remember that we are tracking this global, and the mod/ref fns
210 NonAddressTakenGlobals.insert(I);
212 for (unsigned i = 0, e = Readers.size(); i != e; ++i)
213 FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
215 if (!I->isConstant()) // No need to keep track of writers to constants
216 for (unsigned i = 0, e = Writers.size(); i != e; ++i)
217 FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
218 ++NumNonAddrTakenGlobalVars;
220 // If this global holds a pointer type, see if it is an indirect global.
221 if (I->getType()->getElementType()->isPointerTy() &&
222 AnalyzeIndirectGlobalMemory(I))
223 ++NumIndirectGlobalVars;
225 Readers.clear(); Writers.clear();
229 /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
230 /// If this is used by anything complex (i.e., the address escapes), return
231 /// true. Also, while we are at it, keep track of those functions that read and
232 /// write to the value.
234 /// If OkayStoreDest is non-null, stores into this global are allowed.
235 bool GlobalsModRef::AnalyzeUsesOfPointer(Value *V,
236 std::vector<Function*> &Readers,
237 std::vector<Function*> &Writers,
238 GlobalValue *OkayStoreDest) {
239 if (!V->getType()->isPointerTy()) return true;
241 for (Value::use_iterator UI = V->use_begin(), E=V->use_end(); UI != E; ++UI) {
243 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
244 Readers.push_back(LI->getParent()->getParent());
245 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
246 if (V == SI->getOperand(1)) {
247 Writers.push_back(SI->getParent()->getParent());
248 } else if (SI->getOperand(1) != OkayStoreDest) {
249 return true; // Storing the pointer
251 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
252 if (AnalyzeUsesOfPointer(GEP, Readers, Writers)) return true;
253 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
254 if (AnalyzeUsesOfPointer(BCI, Readers, Writers, OkayStoreDest))
256 } else if (isFreeCall(U)) {
257 Writers.push_back(cast<Instruction>(U)->getParent()->getParent());
258 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
259 // Make sure that this is just the function being called, not that it is
260 // passing into the function.
261 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
262 if (CI->getArgOperand(i) == V) return true;
263 } else if (InvokeInst *II = dyn_cast<InvokeInst>(U)) {
264 // Make sure that this is just the function being called, not that it is
265 // passing into the function.
266 for (unsigned i = 0, e = II->getNumArgOperands(); i != e; ++i)
267 if (II->getArgOperand(i) == V) return true;
268 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
269 if (CE->getOpcode() == Instruction::GetElementPtr ||
270 CE->getOpcode() == Instruction::BitCast) {
271 if (AnalyzeUsesOfPointer(CE, Readers, Writers))
276 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(U)) {
277 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
278 return true; // Allow comparison against null.
287 /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
288 /// which holds a pointer type. See if the global always points to non-aliased
289 /// heap memory: that is, all initializers of the globals are allocations, and
290 /// those allocations have no use other than initialization of the global.
291 /// Further, all loads out of GV must directly use the memory, not store the
292 /// pointer somewhere. If this is true, we consider the memory pointed to by
293 /// GV to be owned by GV and can disambiguate other pointers from it.
294 bool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
295 // Keep track of values related to the allocation of the memory, f.e. the
296 // value produced by the malloc call and any casts.
297 std::vector<Value*> AllocRelatedValues;
299 // Walk the user list of the global. If we find anything other than a direct
300 // load or store, bail out.
301 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
303 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
304 // The pointer loaded from the global can only be used in simple ways:
305 // we allow addressing of it and loading storing to it. We do *not* allow
306 // storing the loaded pointer somewhere else or passing to a function.
307 std::vector<Function*> ReadersWriters;
308 if (AnalyzeUsesOfPointer(LI, ReadersWriters, ReadersWriters))
309 return false; // Loaded pointer escapes.
310 // TODO: Could try some IP mod/ref of the loaded pointer.
311 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
312 // Storing the global itself.
313 if (SI->getOperand(0) == GV) return false;
315 // If storing the null pointer, ignore it.
316 if (isa<ConstantPointerNull>(SI->getOperand(0)))
319 // Check the value being stored.
320 Value *Ptr = SI->getOperand(0)->getUnderlyingObject();
324 } else if (CallInst *CI = dyn_cast<CallInst>(Ptr)) {
325 Function *F = CI->getCalledFunction();
326 if (!F || !F->isDeclaration()) return false; // Too hard to analyze.
327 if (F->getName() != "calloc") return false; // Not calloc.
329 return false; // Too hard to analyze.
332 // Analyze all uses of the allocation. If any of them are used in a
333 // non-simple way (e.g. stored to another global) bail out.
334 std::vector<Function*> ReadersWriters;
335 if (AnalyzeUsesOfPointer(Ptr, ReadersWriters, ReadersWriters, GV))
336 return false; // Loaded pointer escapes.
338 // Remember that this allocation is related to the indirect global.
339 AllocRelatedValues.push_back(Ptr);
341 // Something complex, bail out.
346 // Okay, this is an indirect global. Remember all of the allocations for
347 // this global in AllocsForIndirectGlobals.
348 while (!AllocRelatedValues.empty()) {
349 AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
350 AllocRelatedValues.pop_back();
352 IndirectGlobals.insert(GV);
356 /// AnalyzeCallGraph - At this point, we know the functions where globals are
357 /// immediately stored to and read from. Propagate this information up the call
358 /// graph to all callers and compute the mod/ref info for all memory for each
360 void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
361 // We do a bottom-up SCC traversal of the call graph. In other words, we
362 // visit all callees before callers (leaf-first).
363 for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I != E;
365 std::vector<CallGraphNode *> &SCC = *I;
366 assert(!SCC.empty() && "SCC with no functions?");
368 if (!SCC[0]->getFunction()) {
369 // Calls externally - can't say anything useful. Remove any existing
370 // function records (may have been created when scanning globals).
371 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
372 FunctionInfo.erase(SCC[i]->getFunction());
376 FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
378 bool KnowNothing = false;
379 unsigned FunctionEffect = 0;
381 // Collect the mod/ref properties due to called functions. We only compute
383 for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
384 Function *F = SCC[i]->getFunction();
390 if (F->isDeclaration()) {
391 // Try to get mod/ref behaviour from function attributes.
392 if (F->doesNotAccessMemory()) {
393 // Can't do better than that!
394 } else if (F->onlyReadsMemory()) {
395 FunctionEffect |= Ref;
396 if (!F->isIntrinsic())
397 // This function might call back into the module and read a global -
398 // consider every global as possibly being read by this function.
399 FR.MayReadAnyGlobal = true;
401 FunctionEffect |= ModRef;
402 // Can't say anything useful unless it's an intrinsic - they don't
403 // read or write global variables of the kind considered here.
404 KnowNothing = !F->isIntrinsic();
409 for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
410 CI != E && !KnowNothing; ++CI)
411 if (Function *Callee = CI->second->getFunction()) {
412 if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
413 // Propagate function effect up.
414 FunctionEffect |= CalleeFR->FunctionEffect;
416 // Incorporate callee's effects on globals into our info.
417 for (std::map<const GlobalValue*, unsigned>::iterator GI =
418 CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end();
420 FR.GlobalInfo[GI->first] |= GI->second;
421 FR.MayReadAnyGlobal |= CalleeFR->MayReadAnyGlobal;
423 // Can't say anything about it. However, if it is inside our SCC,
424 // then nothing needs to be done.
425 CallGraphNode *CalleeNode = CG[Callee];
426 if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end())
434 // If we can't say anything useful about this SCC, remove all SCC functions
435 // from the FunctionInfo map.
437 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
438 FunctionInfo.erase(SCC[i]->getFunction());
442 // Scan the function bodies for explicit loads or stores.
443 for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i)
444 for (inst_iterator II = inst_begin(SCC[i]->getFunction()),
445 E = inst_end(SCC[i]->getFunction());
446 II != E && FunctionEffect != ModRef; ++II)
447 if (isa<LoadInst>(*II)) {
448 FunctionEffect |= Ref;
449 if (cast<LoadInst>(*II).isVolatile())
450 // Volatile loads may have side-effects, so mark them as writing
451 // memory (for example, a flag inside the processor).
452 FunctionEffect |= Mod;
453 } else if (isa<StoreInst>(*II)) {
454 FunctionEffect |= Mod;
455 if (cast<StoreInst>(*II).isVolatile())
456 // Treat volatile stores as reading memory somewhere.
457 FunctionEffect |= Ref;
458 } else if (isMalloc(&cast<Instruction>(*II)) ||
459 isFreeCall(&cast<Instruction>(*II))) {
460 FunctionEffect |= ModRef;
463 if ((FunctionEffect & Mod) == 0)
464 ++NumReadMemFunctions;
465 if (FunctionEffect == 0)
467 FR.FunctionEffect = FunctionEffect;
469 // Finally, now that we know the full effect on this SCC, clone the
470 // information to each function in the SCC.
471 for (unsigned i = 1, e = SCC.size(); i != e; ++i)
472 FunctionInfo[SCC[i]->getFunction()] = FR;
478 /// alias - If one of the pointers is to a global that we are tracking, and the
479 /// other is some random pointer, we know there cannot be an alias, because the
480 /// address of the global isn't taken.
481 AliasAnalysis::AliasResult
482 GlobalsModRef::alias(const Location &LocA,
483 const Location &LocB) {
484 // Get the base object these pointers point to.
485 const Value *UV1 = LocA.Ptr->getUnderlyingObject();
486 const Value *UV2 = LocB.Ptr->getUnderlyingObject();
488 // If either of the underlying values is a global, they may be non-addr-taken
489 // globals, which we can answer queries about.
490 const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
491 const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
493 // If the global's address is taken, pretend we don't know it's a pointer to
495 if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0;
496 if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0;
498 // If the two pointers are derived from two different non-addr-taken
499 // globals, or if one is and the other isn't, we know these can't alias.
500 if ((GV1 || GV2) && GV1 != GV2)
503 // Otherwise if they are both derived from the same addr-taken global, we
504 // can't know the two accesses don't overlap.
507 // These pointers may be based on the memory owned by an indirect global. If
508 // so, we may be able to handle this. First check to see if the base pointer
509 // is a direct load from an indirect global.
511 if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
512 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
513 if (IndirectGlobals.count(GV))
515 if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
516 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
517 if (IndirectGlobals.count(GV))
520 // These pointers may also be from an allocation for the indirect global. If
521 // so, also handle them.
522 if (AllocsForIndirectGlobals.count(UV1))
523 GV1 = AllocsForIndirectGlobals[UV1];
524 if (AllocsForIndirectGlobals.count(UV2))
525 GV2 = AllocsForIndirectGlobals[UV2];
527 // Now that we know whether the two pointers are related to indirect globals,
528 // use this to disambiguate the pointers. If either pointer is based on an
529 // indirect global and if they are not both based on the same indirect global,
530 // they cannot alias.
531 if ((GV1 || GV2) && GV1 != GV2)
534 return AliasAnalysis::alias(LocA, LocB);
537 AliasAnalysis::ModRefResult
538 GlobalsModRef::getModRefInfo(ImmutableCallSite CS,
539 const Location &Loc) {
540 unsigned Known = ModRef;
542 // If we are asking for mod/ref info of a direct call with a pointer to a
543 // global we are tracking, return information if we have it.
544 if (const GlobalValue *GV =
545 dyn_cast<GlobalValue>(Loc.Ptr->getUnderlyingObject()))
546 if (GV->hasLocalLinkage())
547 if (const Function *F = CS.getCalledFunction())
548 if (NonAddressTakenGlobals.count(GV))
549 if (const FunctionRecord *FR = getFunctionInfo(F))
550 Known = FR->getInfoForGlobal(GV);
552 if (Known == NoModRef)
553 return NoModRef; // No need to query other mod/ref analyses
554 return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, Loc));
558 //===----------------------------------------------------------------------===//
559 // Methods to update the analysis as a result of the client transformation.
561 void GlobalsModRef::deleteValue(Value *V) {
562 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
563 if (NonAddressTakenGlobals.erase(GV)) {
564 // This global might be an indirect global. If so, remove it and remove
565 // any AllocRelatedValues for it.
566 if (IndirectGlobals.erase(GV)) {
567 // Remove any entries in AllocsForIndirectGlobals for this global.
568 for (std::map<const Value*, const GlobalValue*>::iterator
569 I = AllocsForIndirectGlobals.begin(),
570 E = AllocsForIndirectGlobals.end(); I != E; ) {
571 if (I->second == GV) {
572 AllocsForIndirectGlobals.erase(I++);
581 // Otherwise, if this is an allocation related to an indirect global, remove
583 AllocsForIndirectGlobals.erase(V);
585 AliasAnalysis::deleteValue(V);
588 void GlobalsModRef::copyValue(Value *From, Value *To) {
589 AliasAnalysis::copyValue(From, To);