LLVM API Documentation
00001 //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file was developed by the LLVM research group and is distributed under 00006 // the University of Illinois Open Source License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This simple pass provides alias and mod/ref information for global values 00011 // that do not have their address taken, and keeps track of whether functions 00012 // read or write memory (are "pure"). For this simple (but very common) case, 00013 // we can provide pretty accurate and useful information. 00014 // 00015 //===----------------------------------------------------------------------===// 00016 00017 #include "llvm/Analysis/Passes.h" 00018 #include "llvm/Module.h" 00019 #include "llvm/Pass.h" 00020 #include "llvm/Instructions.h" 00021 #include "llvm/Constants.h" 00022 #include "llvm/Analysis/AliasAnalysis.h" 00023 #include "llvm/Analysis/CallGraph.h" 00024 #include "llvm/Support/InstIterator.h" 00025 #include "llvm/Support/CommandLine.h" 00026 #include "llvm/ADT/Statistic.h" 00027 #include "llvm/ADT/SCCIterator.h" 00028 #include <set> 00029 using namespace llvm; 00030 00031 namespace { 00032 Statistic<> 00033 NumNonAddrTakenGlobalVars("globalsmodref-aa", 00034 "Number of global vars without address taken"); 00035 Statistic<> 00036 NumNonAddrTakenFunctions("globalsmodref-aa", 00037 "Number of functions without address taken"); 00038 Statistic<> 00039 NumNoMemFunctions("globalsmodref-aa", 00040 "Number of functions that do not access memory"); 00041 Statistic<> 00042 NumReadMemFunctions("globalsmodref-aa", 00043 "Number of functions that only read memory"); 00044 00045 /// FunctionRecord - One instance of this structure is stored for every 00046 /// function in the program. Later, the entries for these functions are 00047 /// removed if the function is found to call an external function (in which 00048 /// case we know nothing about it. 00049 struct FunctionRecord { 00050 /// GlobalInfo - Maintain mod/ref info for all of the globals without 00051 /// addresses taken that are read or written (transitively) by this 00052 /// function. 00053 std::map<GlobalValue*, unsigned> GlobalInfo; 00054 00055 unsigned getInfoForGlobal(GlobalValue *GV) const { 00056 std::map<GlobalValue*, unsigned>::const_iterator I = GlobalInfo.find(GV); 00057 if (I != GlobalInfo.end()) 00058 return I->second; 00059 return 0; 00060 } 00061 00062 /// FunctionEffect - Capture whether or not this function reads or writes to 00063 /// ANY memory. If not, we can do a lot of aggressive analysis on it. 00064 unsigned FunctionEffect; 00065 00066 FunctionRecord() : FunctionEffect(0) {} 00067 }; 00068 00069 /// GlobalsModRef - The actual analysis pass. 00070 class GlobalsModRef : public ModulePass, public AliasAnalysis { 00071 /// NonAddressTakenGlobals - The globals that do not have their addresses 00072 /// taken. 00073 std::set<GlobalValue*> NonAddressTakenGlobals; 00074 00075 /// FunctionInfo - For each function, keep track of what globals are 00076 /// modified or read. 00077 std::map<Function*, FunctionRecord> FunctionInfo; 00078 00079 public: 00080 bool runOnModule(Module &M) { 00081 InitializeAliasAnalysis(this); // set up super class 00082 AnalyzeGlobals(M); // find non-addr taken globals 00083 AnalyzeCallGraph(getAnalysis<CallGraph>(), M); // Propagate on CG 00084 return false; 00085 } 00086 00087 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00088 AliasAnalysis::getAnalysisUsage(AU); 00089 AU.addRequired<CallGraph>(); 00090 AU.setPreservesAll(); // Does not transform code 00091 } 00092 00093 //------------------------------------------------ 00094 // Implement the AliasAnalysis API 00095 // 00096 AliasResult alias(const Value *V1, unsigned V1Size, 00097 const Value *V2, unsigned V2Size); 00098 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size); 00099 ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) { 00100 return AliasAnalysis::getModRefInfo(CS1,CS2); 00101 } 00102 bool hasNoModRefInfoForCalls() const { return false; } 00103 00104 /// getModRefBehavior - Return the behavior of the specified function if 00105 /// called from the specified call site. The call site may be null in which 00106 /// case the most generic behavior of this function should be returned. 00107 virtual ModRefBehavior getModRefBehavior(Function *F, CallSite CS, 00108 std::vector<PointerAccessInfo> *Info) { 00109 if (FunctionRecord *FR = getFunctionInfo(F)) 00110 if (FR->FunctionEffect == 0) 00111 return DoesNotAccessMemory; 00112 else if ((FR->FunctionEffect & Mod) == 0) 00113 return OnlyReadsMemory; 00114 return AliasAnalysis::getModRefBehavior(F, CS, Info); 00115 } 00116 00117 virtual void deleteValue(Value *V); 00118 virtual void copyValue(Value *From, Value *To); 00119 00120 private: 00121 /// getFunctionInfo - Return the function info for the function, or null if 00122 /// the function calls an external function (in which case we don't have 00123 /// anything useful to say about it). 00124 FunctionRecord *getFunctionInfo(Function *F) { 00125 std::map<Function*, FunctionRecord>::iterator I = FunctionInfo.find(F); 00126 if (I != FunctionInfo.end()) 00127 return &I->second; 00128 return 0; 00129 } 00130 00131 void AnalyzeGlobals(Module &M); 00132 void AnalyzeCallGraph(CallGraph &CG, Module &M); 00133 void AnalyzeSCC(std::vector<CallGraphNode *> &SCC); 00134 bool AnalyzeUsesOfGlobal(Value *V, std::vector<Function*> &Readers, 00135 std::vector<Function*> &Writers); 00136 }; 00137 00138 RegisterOpt<GlobalsModRef> X("globalsmodref-aa", 00139 "Simple mod/ref analysis for globals"); 00140 RegisterAnalysisGroup<AliasAnalysis, GlobalsModRef> Y; 00141 } 00142 00143 Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); } 00144 00145 00146 /// AnalyzeGlobalUses - Scan through the users of all of the internal 00147 /// GlobalValue's in the program. If none of them have their "Address taken" 00148 /// (really, their address passed to something nontrivial), record this fact, 00149 /// and record the functions that they are used directly in. 00150 void GlobalsModRef::AnalyzeGlobals(Module &M) { 00151 std::vector<Function*> Readers, Writers; 00152 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 00153 if (I->hasInternalLinkage()) { 00154 if (!AnalyzeUsesOfGlobal(I, Readers, Writers)) { 00155 // Remember that we are tracking this global. 00156 NonAddressTakenGlobals.insert(I); 00157 ++NumNonAddrTakenFunctions; 00158 } 00159 Readers.clear(); Writers.clear(); 00160 } 00161 00162 for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 00163 I != E; ++I) 00164 if (I->hasInternalLinkage()) { 00165 if (!AnalyzeUsesOfGlobal(I, Readers, Writers)) { 00166 // Remember that we are tracking this global, and the mod/ref fns 00167 NonAddressTakenGlobals.insert(I); 00168 for (unsigned i = 0, e = Readers.size(); i != e; ++i) 00169 FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref; 00170 00171 if (!I->isConstant()) // No need to keep track of writers to constants 00172 for (unsigned i = 0, e = Writers.size(); i != e; ++i) 00173 FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod; 00174 ++NumNonAddrTakenGlobalVars; 00175 } 00176 Readers.clear(); Writers.clear(); 00177 } 00178 } 00179 00180 /// AnalyzeUsesOfGlobal - Look at all of the users of the specified global value 00181 /// derived pointer. If this is used by anything complex (i.e., the address 00182 /// escapes), return true. Also, while we are at it, keep track of those 00183 /// functions that read and write to the value. 00184 bool GlobalsModRef::AnalyzeUsesOfGlobal(Value *V, 00185 std::vector<Function*> &Readers, 00186 std::vector<Function*> &Writers) { 00187 if (!isa<PointerType>(V->getType())) return true; 00188 00189 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI) 00190 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) { 00191 Readers.push_back(LI->getParent()->getParent()); 00192 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) { 00193 if (V == SI->getOperand(0)) return true; // Storing the pointer 00194 Writers.push_back(SI->getParent()->getParent()); 00195 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) { 00196 if (AnalyzeUsesOfGlobal(GEP, Readers, Writers)) return true; 00197 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) { 00198 // Make sure that this is just the function being called, not that it is 00199 // passing into the function. 00200 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i) 00201 if (CI->getOperand(i) == V) return true; 00202 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) { 00203 // Make sure that this is just the function being called, not that it is 00204 // passing into the function. 00205 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i) 00206 if (II->getOperand(i) == V) return true; 00207 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) { 00208 if (CE->getOpcode() == Instruction::GetElementPtr || 00209 CE->getOpcode() == Instruction::Cast) { 00210 if (AnalyzeUsesOfGlobal(CE, Readers, Writers)) 00211 return true; 00212 } else { 00213 return true; 00214 } 00215 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(*UI)) { 00216 if (AnalyzeUsesOfGlobal(GV, Readers, Writers)) return true; 00217 } else { 00218 return true; 00219 } 00220 return false; 00221 } 00222 00223 /// AnalyzeCallGraph - At this point, we know the functions where globals are 00224 /// immediately stored to and read from. Propagate this information up the call 00225 /// graph to all callers and compute the mod/ref info for all memory for each 00226 /// function. 00227 void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) { 00228 // We do a bottom-up SCC traversal of the call graph. In other words, we 00229 // visit all callees before callers (leaf-first). 00230 for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I!=E; ++I) 00231 if ((*I).size() != 1) { 00232 AnalyzeSCC(*I); 00233 } else if (Function *F = (*I)[0]->getFunction()) { 00234 if (!F->isExternal()) { 00235 // Nonexternal function. 00236 AnalyzeSCC(*I); 00237 } else { 00238 // Otherwise external function. Handle intrinsics and other special 00239 // cases here. 00240 if (getAnalysis<AliasAnalysis>().doesNotAccessMemory(F)) 00241 // If it does not access memory, process the function, causing us to 00242 // realize it doesn't do anything (the body is empty). 00243 AnalyzeSCC(*I); 00244 else { 00245 // Otherwise, don't process it. This will cause us to conservatively 00246 // assume the worst. 00247 } 00248 } 00249 } else { 00250 // Do not process the external node, assume the worst. 00251 } 00252 } 00253 00254 void GlobalsModRef::AnalyzeSCC(std::vector<CallGraphNode *> &SCC) { 00255 assert(!SCC.empty() && "SCC with no functions?"); 00256 FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()]; 00257 00258 bool CallsExternal = false; 00259 unsigned FunctionEffect = 0; 00260 00261 // Collect the mod/ref properties due to called functions. We only compute 00262 // one mod-ref set 00263 for (unsigned i = 0, e = SCC.size(); i != e && !CallsExternal; ++i) 00264 for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end(); 00265 CI != E; ++CI) 00266 if (Function *Callee = CI->second->getFunction()) { 00267 if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) { 00268 // Propagate function effect up. 00269 FunctionEffect |= CalleeFR->FunctionEffect; 00270 00271 // Incorporate callee's effects on globals into our info. 00272 for (std::map<GlobalValue*, unsigned>::iterator GI = 00273 CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end(); 00274 GI != E; ++GI) 00275 FR.GlobalInfo[GI->first] |= GI->second; 00276 00277 } else { 00278 // Okay, if we can't say anything about it, maybe some other alias 00279 // analysis can. 00280 ModRefBehavior MRB = 00281 AliasAnalysis::getModRefBehavior(Callee, CallSite()); 00282 if (MRB != DoesNotAccessMemory) { 00283 // FIXME: could make this more aggressive for functions that just 00284 // read memory. We should just say they read all globals. 00285 CallsExternal = true; 00286 break; 00287 } 00288 } 00289 } else { 00290 CallsExternal = true; 00291 break; 00292 } 00293 00294 // If this SCC calls an external function, we can't say anything about it, so 00295 // remove all SCC functions from the FunctionInfo map. 00296 if (CallsExternal) { 00297 for (unsigned i = 0, e = SCC.size(); i != e; ++i) 00298 FunctionInfo.erase(SCC[i]->getFunction()); 00299 return; 00300 } 00301 00302 // Otherwise, unless we already know that this function mod/refs memory, scan 00303 // the function bodies to see if there are any explicit loads or stores. 00304 if (FunctionEffect != ModRef) { 00305 for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i) 00306 for (inst_iterator II = inst_begin(SCC[i]->getFunction()), 00307 E = inst_end(SCC[i]->getFunction()); 00308 II != E && FunctionEffect != ModRef; ++II) 00309 if (isa<LoadInst>(*II)) 00310 FunctionEffect |= Ref; 00311 else if (isa<StoreInst>(*II)) 00312 FunctionEffect |= Mod; 00313 else if (isa<MallocInst>(*II) || isa<FreeInst>(*II)) 00314 FunctionEffect |= ModRef; 00315 } 00316 00317 if ((FunctionEffect & Mod) == 0) 00318 ++NumReadMemFunctions; 00319 if (FunctionEffect == 0) 00320 ++NumNoMemFunctions; 00321 FR.FunctionEffect = FunctionEffect; 00322 00323 // Finally, now that we know the full effect on this SCC, clone the 00324 // information to each function in the SCC. 00325 for (unsigned i = 1, e = SCC.size(); i != e; ++i) 00326 FunctionInfo[SCC[i]->getFunction()] = FR; 00327 } 00328 00329 00330 00331 /// getUnderlyingObject - This traverses the use chain to figure out what object 00332 /// the specified value points to. If the value points to, or is derived from, 00333 /// a global object, return it. 00334 static const GlobalValue *getUnderlyingObject(const Value *V) { 00335 if (!isa<PointerType>(V->getType())) return 0; 00336 00337 // If we are at some type of object... return it. 00338 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV; 00339 00340 // Traverse through different addressing mechanisms... 00341 if (const Instruction *I = dyn_cast<Instruction>(V)) { 00342 if (isa<CastInst>(I) || isa<GetElementPtrInst>(I)) 00343 return getUnderlyingObject(I->getOperand(0)); 00344 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 00345 if (CE->getOpcode() == Instruction::Cast || 00346 CE->getOpcode() == Instruction::GetElementPtr) 00347 return getUnderlyingObject(CE->getOperand(0)); 00348 } 00349 return 0; 00350 } 00351 00352 /// alias - If one of the pointers is to a global that we are tracking, and the 00353 /// other is some random pointer, we know there cannot be an alias, because the 00354 /// address of the global isn't taken. 00355 AliasAnalysis::AliasResult 00356 GlobalsModRef::alias(const Value *V1, unsigned V1Size, 00357 const Value *V2, unsigned V2Size) { 00358 GlobalValue *GV1 = const_cast<GlobalValue*>(getUnderlyingObject(V1)); 00359 GlobalValue *GV2 = const_cast<GlobalValue*>(getUnderlyingObject(V2)); 00360 00361 // If the global's address is taken, pretend we don't know it's a pointer to 00362 // the global. 00363 if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0; 00364 if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0; 00365 00366 if ((GV1 || GV2) && GV1 != GV2) 00367 return NoAlias; 00368 00369 return AliasAnalysis::alias(V1, V1Size, V2, V2Size); 00370 } 00371 00372 AliasAnalysis::ModRefResult 00373 GlobalsModRef::getModRefInfo(CallSite CS, Value *P, unsigned Size) { 00374 unsigned Known = ModRef; 00375 00376 // If we are asking for mod/ref info of a direct call with a pointer to a 00377 // global we are tracking, return information if we have it. 00378 if (GlobalValue *GV = const_cast<GlobalValue*>(getUnderlyingObject(P))) 00379 if (GV->hasInternalLinkage()) 00380 if (Function *F = CS.getCalledFunction()) 00381 if (NonAddressTakenGlobals.count(GV)) 00382 if (FunctionRecord *FR = getFunctionInfo(F)) 00383 Known = FR->getInfoForGlobal(GV); 00384 00385 if (Known == NoModRef) 00386 return NoModRef; // No need to query other mod/ref analyses 00387 return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, P, Size)); 00388 } 00389 00390 00391 //===----------------------------------------------------------------------===// 00392 // Methods to update the analysis as a result of the client transformation. 00393 // 00394 void GlobalsModRef::deleteValue(Value *V) { 00395 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) 00396 NonAddressTakenGlobals.erase(GV); 00397 } 00398 00399 void GlobalsModRef::copyValue(Value *From, Value *To) { 00400 }