GlobalsModRef.cpp revision 234353
1193323Sed//===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===// 2193323Sed// 3193323Sed// The LLVM Compiler Infrastructure 4193323Sed// 5193323Sed// This file is distributed under the University of Illinois Open Source 6193323Sed// License. See LICENSE.TXT for details. 7193323Sed// 8193323Sed//===----------------------------------------------------------------------===// 9193323Sed// 10193323Sed// This simple pass provides alias and mod/ref information for global values 11193323Sed// that do not have their address taken, and keeps track of whether functions 12193323Sed// read or write memory (are "pure"). For this simple (but very common) case, 13193323Sed// we can provide pretty accurate and useful information. 14193323Sed// 15193323Sed//===----------------------------------------------------------------------===// 16193323Sed 17193323Sed#define DEBUG_TYPE "globalsmodref-aa" 18234353Sdim#include "llvm/Analysis/Passes.h" 19193323Sed#include "llvm/Module.h" 20249423Sdim#include "llvm/Pass.h" 21249423Sdim#include "llvm/Instructions.h" 22249423Sdim#include "llvm/Constants.h" 23193323Sed#include "llvm/DerivedTypes.h" 24212904Sdim#include "llvm/IntrinsicInst.h" 25193323Sed#include "llvm/Analysis/AliasAnalysis.h" 26193323Sed#include "llvm/Analysis/CallGraph.h" 27193323Sed#include "llvm/Analysis/MemoryBuiltins.h" 28193323Sed#include "llvm/Analysis/ValueTracking.h" 29193323Sed#include "llvm/Support/CommandLine.h" 30193323Sed#include "llvm/Support/InstIterator.h" 31193323Sed#include "llvm/ADT/Statistic.h" 32193323Sed#include "llvm/ADT/SCCIterator.h" 33193323Sed#include <set> 34193323Sedusing namespace llvm; 35193323Sed 36193323SedSTATISTIC(NumNonAddrTakenGlobalVars, 37193323Sed "Number of global vars without address taken"); 38218893SdimSTATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken"); 39218893SdimSTATISTIC(NumNoMemFunctions, "Number of functions that do not access memory"); 40218893SdimSTATISTIC(NumReadMemFunctions, "Number of functions that only read memory"); 41218893SdimSTATISTIC(NumIndirectGlobalVars, "Number of indirect global objects"); 42193323Sed 43193323Sednamespace { 44239462Sdim /// FunctionRecord - One instance of this structure is stored for every 45239462Sdim /// function in the program. Later, the entries for these functions are 46239462Sdim /// removed if the function is found to call an external function (in which 47193323Sed /// case we know nothing about it. 48193323Sed struct FunctionRecord { 49193323Sed /// GlobalInfo - Maintain mod/ref info for all of the globals without 50193323Sed /// addresses taken that are read or written (transitively) by this 51193323Sed /// function. 52193323Sed std::map<const GlobalValue*, unsigned> GlobalInfo; 53198090Srdivacky 54193323Sed /// MayReadAnyGlobal - May read global variables, but it is not known which. 55193323Sed bool MayReadAnyGlobal; 56193323Sed 57193323Sed unsigned getInfoForGlobal(const GlobalValue *GV) const { 58193323Sed unsigned Effect = MayReadAnyGlobal ? AliasAnalysis::Ref : 0; 59239462Sdim std::map<const GlobalValue*, unsigned>::const_iterator I = 60195340Sed GlobalInfo.find(GV); 61193323Sed if (I != GlobalInfo.end()) 62193323Sed Effect |= I->second; 63193323Sed return Effect; 64234353Sdim } 65193323Sed 66193323Sed /// FunctionEffect - Capture whether or not this function reads or writes to 67210299Sed /// ANY memory. If not, we can do a lot of aggressive analysis on it. 68210299Sed unsigned FunctionEffect; 69202878Srdivacky 70202878Srdivacky FunctionRecord() : MayReadAnyGlobal (false), FunctionEffect(0) {} 71193323Sed }; 72193323Sed 73193323Sed /// GlobalsModRef - The actual analysis pass. 74193323Sed class GlobalsModRef : public ModulePass, public AliasAnalysis { 75193323Sed /// NonAddressTakenGlobals - The globals that do not have their addresses 76193323Sed /// taken. 77193323Sed std::set<const GlobalValue*> NonAddressTakenGlobals; 78193323Sed 79193323Sed /// IndirectGlobals - The memory pointed to by this global is known to be 80226633Sdim /// 'owned' by the global. 81226633Sdim std::set<const GlobalValue*> IndirectGlobals; 82226633Sdim 83226633Sdim /// AllocsForIndirectGlobals - If an instruction allocates memory for an 84226633Sdim /// indirect global, this map indicates which one. 85199481Srdivacky std::map<const Value*, const GlobalValue*> AllocsForIndirectGlobals; 86199481Srdivacky 87193323Sed /// FunctionInfo - For each function, keep track of what globals are 88218893Sdim /// modified or read. 89218893Sdim std::map<const Function*, FunctionRecord> FunctionInfo; 90193323Sed 91210299Sed public: 92210299Sed static char ID; 93194710Sed GlobalsModRef() : ModulePass(ID) { 94194710Sed initializeGlobalsModRefPass(*PassRegistry::getPassRegistry()); 95198090Srdivacky } 96198090Srdivacky 97218893Sdim bool runOnModule(Module &M) { 98218893Sdim InitializeAliasAnalysis(this); // set up super class 99218893Sdim AnalyzeGlobals(M); // find non-addr taken globals 100218893Sdim AnalyzeCallGraph(getAnalysis<CallGraph>(), M); // Propagate on CG 101221345Sdim return false; 102194710Sed } 103218893Sdim 104194710Sed virtual void getAnalysisUsage(AnalysisUsage &AU) const { 105218893Sdim AliasAnalysis::getAnalysisUsage(AU); 106218893Sdim AU.addRequired<CallGraph>(); 107194710Sed AU.setPreservesAll(); // Does not transform code 108194710Sed } 109218893Sdim 110218893Sdim //------------------------------------------------ 111194710Sed // Implement the AliasAnalysis API 112194710Sed // 113194710Sed AliasResult alias(const Location &LocA, const Location &LocB); 114194710Sed ModRefResult getModRefInfo(ImmutableCallSite CS, 115194710Sed const Location &Loc); 116194710Sed ModRefResult getModRefInfo(ImmutableCallSite CS1, 117194710Sed ImmutableCallSite CS2) { 118194710Sed return AliasAnalysis::getModRefInfo(CS1, CS2); 119194710Sed } 120194710Sed 121194710Sed /// getModRefBehavior - Return the behavior of the specified function if 122194710Sed /// called from the specified call site. The call site may be null in which 123194710Sed /// case the most generic behavior of this function should be returned. 124194710Sed ModRefBehavior getModRefBehavior(const Function *F) { 125194710Sed ModRefBehavior Min = UnknownModRefBehavior; 126194710Sed 127194710Sed if (FunctionRecord *FR = getFunctionInfo(F)) { 128194710Sed if (FR->FunctionEffect == 0) 129194710Sed Min = DoesNotAccessMemory; 130194710Sed else if ((FR->FunctionEffect & Mod) == 0) 131194710Sed Min = OnlyReadsMemory; 132194710Sed } 133194710Sed 134194710Sed return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min); 135194710Sed } 136194710Sed 137194710Sed /// getModRefBehavior - Return the behavior of the specified function if 138194710Sed /// called from the specified call site. The call site may be null in which 139194710Sed /// case the most generic behavior of this function should be returned. 140194710Sed ModRefBehavior getModRefBehavior(ImmutableCallSite CS) { 141194710Sed ModRefBehavior Min = UnknownModRefBehavior; 142194710Sed 143194710Sed if (const Function* F = CS.getCalledFunction()) 144194710Sed if (FunctionRecord *FR = getFunctionInfo(F)) { 145194710Sed if (FR->FunctionEffect == 0) 146194710Sed Min = DoesNotAccessMemory; 147194710Sed else if ((FR->FunctionEffect & Mod) == 0) 148194710Sed Min = OnlyReadsMemory; 149194710Sed } 150210299Sed 151210299Sed return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min); 152210299Sed } 153210299Sed 154234353Sdim virtual void deleteValue(Value *V); 155234353Sdim virtual void copyValue(Value *From, Value *To); 156234353Sdim virtual void addEscapingUse(Use &U); 157198090Srdivacky 158198090Srdivacky /// getAdjustedAnalysisPointer - This method is used when a pass implements 159198090Srdivacky /// an analysis interface through multiple inheritance. If needed, it 160198090Srdivacky /// should override this to adjust the this pointer as needed for the 161198090Srdivacky /// specified pass info. 162198090Srdivacky virtual void *getAdjustedAnalysisPointer(AnalysisID PI) { 163198090Srdivacky if (PI == &AliasAnalysis::ID) 164198090Srdivacky return (AliasAnalysis*)this; 165198090Srdivacky return this; 166198090Srdivacky } 167198090Srdivacky 168204642Srdivacky private: 169221345Sdim /// getFunctionInfo - Return the function info for the function, or null if 170221345Sdim /// we don't have anything useful to say about it. 171204642Srdivacky FunctionRecord *getFunctionInfo(const Function *F) { 172212904Sdim std::map<const Function*, FunctionRecord>::iterator I = 173212904Sdim FunctionInfo.find(F); 174212904Sdim if (I != FunctionInfo.end()) 175212904Sdim return &I->second; 176243830Sdim return 0; 177243830Sdim } 178243830Sdim 179210299Sed void AnalyzeGlobals(Module &M); 180210299Sed void AnalyzeCallGraph(CallGraph &CG, Module &M); 181210299Sed bool AnalyzeUsesOfPointer(Value *V, std::vector<Function*> &Readers, 182210299Sed std::vector<Function*> &Writers, 183210299Sed GlobalValue *OkayStoreDest = 0); 184210299Sed bool AnalyzeIndirectGlobalMemory(GlobalValue *GV); 185210299Sed }; 186204642Srdivacky} 187204642Srdivacky 188212904Sdimchar GlobalsModRef::ID = 0; 189212904SdimINITIALIZE_AG_PASS_BEGIN(GlobalsModRef, AliasAnalysis, 190212904Sdim "globalsmodref-aa", "Simple mod/ref analysis for globals", 191218893Sdim false, true, false) 192221345SdimINITIALIZE_AG_DEPENDENCY(CallGraph) 193218893SdimINITIALIZE_AG_PASS_END(GlobalsModRef, AliasAnalysis, 194218893Sdim "globalsmodref-aa", "Simple mod/ref analysis for globals", 195218893Sdim false, true, false) 196218893Sdim 197218893SdimPass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); } 198221345Sdim 199221345Sdim/// AnalyzeGlobals - Scan through the users of all of the internal 200221345Sdim/// GlobalValue's in the program. If none of them have their "address taken" 201218893Sdim/// (really, their address passed to something nontrivial), record this fact, 202218893Sdim/// and record the functions that they are used directly in. 203218893Sdimvoid GlobalsModRef::AnalyzeGlobals(Module &M) { 204218893Sdim std::vector<Function*> Readers, Writers; 205218893Sdim for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 206218893Sdim if (I->hasLocalLinkage()) { 207218893Sdim if (!AnalyzeUsesOfPointer(I, Readers, Writers)) { 208218893Sdim // Remember that we are tracking this global. 209218893Sdim NonAddressTakenGlobals.insert(I); 210218893Sdim ++NumNonAddrTakenFunctions; 211218893Sdim } 212218893Sdim Readers.clear(); Writers.clear(); 213218893Sdim } 214218893Sdim 215218893Sdim for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 216218893Sdim I != E; ++I) 217218893Sdim if (I->hasLocalLinkage()) { 218218893Sdim if (!AnalyzeUsesOfPointer(I, Readers, Writers)) { 219218893Sdim // Remember that we are tracking this global, and the mod/ref fns 220218893Sdim NonAddressTakenGlobals.insert(I); 221218893Sdim 222218893Sdim for (unsigned i = 0, e = Readers.size(); i != e; ++i) 223218893Sdim FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref; 224218893Sdim 225226633Sdim if (!I->isConstant()) // No need to keep track of writers to constants 226226633Sdim for (unsigned i = 0, e = Writers.size(); i != e; ++i) 227226633Sdim FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod; 228226633Sdim ++NumNonAddrTakenGlobalVars; 229226633Sdim 230226633Sdim // If this global holds a pointer type, see if it is an indirect global. 231226633Sdim if (I->getType()->getElementType()->isPointerTy() && 232226633Sdim AnalyzeIndirectGlobalMemory(I)) 233226633Sdim ++NumIndirectGlobalVars; 234226633Sdim } 235249423Sdim Readers.clear(); Writers.clear(); 236249423Sdim } 237249423Sdim} 238249423Sdim 239249423Sdim/// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer. 240193323Sed/// If this is used by anything complex (i.e., the address escapes), return 241193323Sed/// true. Also, while we are at it, keep track of those functions that read and 242193323Sed/// write to the value. 243194710Sed/// 244194710Sed/// If OkayStoreDest is non-null, stores into this global are allowed. 245212904Sdimbool GlobalsModRef::AnalyzeUsesOfPointer(Value *V, 246194710Sed std::vector<Function*> &Readers, 247194710Sed std::vector<Function*> &Writers, 248193323Sed GlobalValue *OkayStoreDest) { 249193323Sed if (!V->getType()->isPointerTy()) return true; 250193323Sed 251193323Sed for (Value::use_iterator UI = V->use_begin(), E=V->use_end(); UI != E; ++UI) { 252193323Sed User *U = *UI; 253193323Sed if (LoadInst *LI = dyn_cast<LoadInst>(U)) { 254193323Sed Readers.push_back(LI->getParent()->getParent()); 255249423Sdim } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 256212904Sdim if (V == SI->getOperand(1)) { 257207618Srdivacky Writers.push_back(SI->getParent()->getParent()); 258193323Sed } else if (SI->getOperand(1) != OkayStoreDest) { 259193323Sed return true; // Storing the pointer 260193323Sed } 261193323Sed } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { 262193323Sed if (AnalyzeUsesOfPointer(GEP, Readers, Writers)) return true; 263207618Srdivacky } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) { 264193323Sed if (AnalyzeUsesOfPointer(BCI, Readers, Writers, OkayStoreDest)) 265193323Sed return true; 266193323Sed } else if (isFreeCall(U)) { 267243830Sdim Writers.push_back(cast<Instruction>(U)->getParent()->getParent()); 268243830Sdim } else if (CallInst *CI = dyn_cast<CallInst>(U)) { 269243830Sdim // Make sure that this is just the function being called, not that it is 270243830Sdim // passing into the function. 271243830Sdim for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) 272226633Sdim if (CI->getArgOperand(i) == V) return true; 273226633Sdim } else if (InvokeInst *II = dyn_cast<InvokeInst>(U)) { 274226633Sdim // Make sure that this is just the function being called, not that it is 275207618Srdivacky // passing into the function. 276207618Srdivacky for (unsigned i = 0, e = II->getNumArgOperands(); i != e; ++i) 277207618Srdivacky if (II->getArgOperand(i) == V) return true; 278193323Sed } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) { 279226633Sdim if (CE->getOpcode() == Instruction::GetElementPtr || 280226633Sdim CE->getOpcode() == Instruction::BitCast) { 281226633Sdim if (AnalyzeUsesOfPointer(CE, Readers, Writers)) 282224145Sdim return true; 283218893Sdim } else { 284218893Sdim return true; 285218893Sdim } 286218893Sdim } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(U)) { 287198090Srdivacky if (!isa<ConstantPointerNull>(ICI->getOperand(1))) 288249423Sdim return true; // Allow comparison against null. 289249423Sdim } else { 290249423Sdim return true; 291198090Srdivacky } 292234353Sdim } 293234353Sdim 294249423Sdim return false; 295234353Sdim} 296234353Sdim 297234353Sdim/// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable 298249423Sdim/// which holds a pointer type. See if the global always points to non-aliased 299249423Sdim/// heap memory: that is, all initializers of the globals are allocations, and 300249423Sdim/// those allocations have no use other than initialization of the global. 301193323Sed/// Further, all loads out of GV must directly use the memory, not store the 302193323Sed/// pointer somewhere. If this is true, we consider the memory pointed to by 303226633Sdim/// GV to be owned by GV and can disambiguate other pointers from it. 304198090Srdivackybool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) { 305193323Sed // Keep track of values related to the allocation of the memory, f.e. the 306199481Srdivacky // value produced by the malloc call and any casts. 307210299Sed std::vector<Value*> AllocRelatedValues; 308210299Sed 309210299Sed // Walk the user list of the global. If we find anything other than a direct 310199481Srdivacky // load or store, bail out. 311199481Srdivacky for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){ 312223017Sdim User *U = *I; 313223017Sdim if (LoadInst *LI = dyn_cast<LoadInst>(U)) { 314223017Sdim // The pointer loaded from the global can only be used in simple ways: 315223017Sdim // we allow addressing of it and loading storing to it. We do *not* allow 316223017Sdim // storing the loaded pointer somewhere else or passing to a function. 317223017Sdim std::vector<Function*> ReadersWriters; 318193323Sed if (AnalyzeUsesOfPointer(LI, ReadersWriters, ReadersWriters)) 319193323Sed return false; // Loaded pointer escapes. 320193323Sed // TODO: Could try some IP mod/ref of the loaded pointer. 321193323Sed } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 322193323Sed // Storing the global itself. 323193323Sed if (SI->getOperand(0) == GV) return false; 324193323Sed 325193323Sed // If storing the null pointer, ignore it. 326193323Sed if (isa<ConstantPointerNull>(SI->getOperand(0))) 327193323Sed continue; 328193323Sed 329193323Sed // Check the value being stored. 330193323Sed Value *Ptr = GetUnderlyingObject(SI->getOperand(0)); 331193323Sed 332193323Sed if (isMalloc(Ptr)) { 333193323Sed // Okay, easy case. 334193323Sed } else if (CallInst *CI = dyn_cast<CallInst>(Ptr)) { 335193323Sed Function *F = CI->getCalledFunction(); 336193323Sed if (!F || !F->isDeclaration()) return false; // Too hard to analyze. 337193323Sed if (F->getName() != "calloc") return false; // Not calloc. 338193323Sed } else { 339198090Srdivacky return false; // Too hard to analyze. 340198090Srdivacky } 341218893Sdim 342218893Sdim // Analyze all uses of the allocation. If any of them are used in a 343193323Sed // non-simple way (e.g. stored to another global) bail out. 344218893Sdim std::vector<Function*> ReadersWriters; 345218893Sdim if (AnalyzeUsesOfPointer(Ptr, ReadersWriters, ReadersWriters, GV)) 346218893Sdim return false; // Loaded pointer escapes. 347218893Sdim 348218893Sdim // Remember that this allocation is related to the indirect global. 349218893Sdim AllocRelatedValues.push_back(Ptr); 350193323Sed } else { 351193323Sed // Something complex, bail out. 352198090Srdivacky return false; 353193323Sed } 354193323Sed } 355193323Sed 356193323Sed // Okay, this is an indirect global. Remember all of the allocations for 357193323Sed // this global in AllocsForIndirectGlobals. 358193323Sed while (!AllocRelatedValues.empty()) { 359223017Sdim AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV; 360193323Sed AllocRelatedValues.pop_back(); 361193323Sed } 362193323Sed IndirectGlobals.insert(GV); 363208599Srdivacky return true; 364193323Sed} 365193323Sed 366193323Sed/// AnalyzeCallGraph - At this point, we know the functions where globals are 367208599Srdivacky/// immediately stored to and read from. Propagate this information up the call 368208599Srdivacky/// graph to all callers and compute the mod/ref info for all memory for each 369249423Sdim/// function. 370208599Srdivackyvoid GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) { 371212904Sdim // We do a bottom-up SCC traversal of the call graph. In other words, we 372212904Sdim // visit all callees before callers (leaf-first). 373212904Sdim for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I != E; 374212904Sdim ++I) { 375212904Sdim std::vector<CallGraphNode *> &SCC = *I; 376212904Sdim assert(!SCC.empty() && "SCC with no functions?"); 377239462Sdim 378239462Sdim if (!SCC[0]->getFunction()) { 379212904Sdim // Calls externally - can't say anything useful. Remove any existing 380208599Srdivacky // function records (may have been created when scanning globals). 381208599Srdivacky for (unsigned i = 0, e = SCC.size(); i != e; ++i) 382198090Srdivacky FunctionInfo.erase(SCC[i]->getFunction()); 383198090Srdivacky continue; 384198892Srdivacky } 385198892Srdivacky 386198892Srdivacky FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()]; 387198892Srdivacky 388198892Srdivacky bool KnowNothing = false; 389198892Srdivacky unsigned FunctionEffect = 0; 390218893Sdim 391218893Sdim // Collect the mod/ref properties due to called functions. We only compute 392218893Sdim // one mod-ref set. 393212904Sdim for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) { 394212904Sdim Function *F = SCC[i]->getFunction(); 395249423Sdim if (!F) { 396212904Sdim KnowNothing = true; 397193323Sed break; 398193323Sed } 399193323Sed 400193323Sed if (F->isDeclaration()) { 401193323Sed // Try to get mod/ref behaviour from function attributes. 402212904Sdim if (F->doesNotAccessMemory()) { 403212904Sdim // Can't do better than that! 404218893Sdim } else if (F->onlyReadsMemory()) { 405218893Sdim FunctionEffect |= Ref; 406198090Srdivacky if (!F->isIntrinsic()) 407193323Sed // This function might call back into the module and read a global - 408193323Sed // consider every global as possibly being read by this function. 409193323Sed FR.MayReadAnyGlobal = true; 410239462Sdim } else { 411239462Sdim FunctionEffect |= ModRef; 412239462Sdim // Can't say anything useful unless it's an intrinsic - they don't 413194710Sed // read or write global variables of the kind considered here. 414194710Sed KnowNothing = !F->isIntrinsic(); 415198090Srdivacky } 416194710Sed continue; 417194710Sed } 418194710Sed 419194710Sed for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end(); 420194710Sed CI != E && !KnowNothing; ++CI) 421207618Srdivacky if (Function *Callee = CI->second->getFunction()) { 422194710Sed if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) { 423207618Srdivacky // Propagate function effect up. 424207618Srdivacky FunctionEffect |= CalleeFR->FunctionEffect; 425194710Sed 426210299Sed // Incorporate callee's effects on globals into our info. 427210299Sed for (std::map<const GlobalValue*, unsigned>::iterator GI = 428198090Srdivacky CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end(); 429198090Srdivacky GI != E; ++GI) 430198090Srdivacky FR.GlobalInfo[GI->first] |= GI->second; 431207618Srdivacky FR.MayReadAnyGlobal |= CalleeFR->MayReadAnyGlobal; 432208599Srdivacky } else { 433208599Srdivacky // Can't say anything about it. However, if it is inside our SCC, 434203954Srdivacky // then nothing needs to be done. 435207618Srdivacky CallGraphNode *CalleeNode = CG[Callee]; 436207618Srdivacky if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end()) 437207618Srdivacky KnowNothing = true; 438207618Srdivacky } 439207618Srdivacky } else { 440193323Sed KnowNothing = true; 441207618Srdivacky } 442193323Sed } 443239462Sdim 444239462Sdim // If we can't say anything useful about this SCC, remove all SCC functions 445207618Srdivacky // from the FunctionInfo map. 446207618Srdivacky if (KnowNothing) { 447212904Sdim for (unsigned i = 0, e = SCC.size(); i != e; ++i) 448207618Srdivacky FunctionInfo.erase(SCC[i]->getFunction()); 449207618Srdivacky continue; 450210299Sed } 451208599Srdivacky 452207618Srdivacky // Scan the function bodies for explicit loads or stores. 453207618Srdivacky for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i) 454207618Srdivacky for (inst_iterator II = inst_begin(SCC[i]->getFunction()), 455212904Sdim E = inst_end(SCC[i]->getFunction()); 456234353Sdim II != E && FunctionEffect != ModRef; ++II) 457234353Sdim if (isa<LoadInst>(*II)) { 458221345Sdim FunctionEffect |= Ref; 459218893Sdim if (cast<LoadInst>(*II).isVolatile()) 460193323Sed // Volatile loads may have side-effects, so mark them as writing 461218893Sdim // memory (for example, a flag inside the processor). 462218893Sdim FunctionEffect |= Mod; 463198090Srdivacky } else if (isa<StoreInst>(*II)) { 464198090Srdivacky FunctionEffect |= Mod; 465198090Srdivacky if (cast<StoreInst>(*II).isVolatile()) 466198090Srdivacky // Treat volatile stores as reading memory somewhere. 467251662Sdim FunctionEffect |= Ref; 468251662Sdim } else if (isMalloc(&cast<Instruction>(*II)) || 469198090Srdivacky isFreeCall(&cast<Instruction>(*II))) { 470198090Srdivacky FunctionEffect |= ModRef; 471198090Srdivacky } else if (IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(&*II)) { 472198090Srdivacky // The callgraph doesn't include intrinsic calls. 473198090Srdivacky Function *Callee = Intrinsic->getCalledFunction(); 474198090Srdivacky ModRefBehavior Behaviour = AliasAnalysis::getModRefBehavior(Callee); 475207618Srdivacky FunctionEffect |= (Behaviour & ModRef); 476198090Srdivacky } 477251662Sdim 478251662Sdim if ((FunctionEffect & Mod) == 0) 479251662Sdim ++NumReadMemFunctions; 480251662Sdim if (FunctionEffect == 0) 481251662Sdim ++NumNoMemFunctions; 482251662Sdim FR.FunctionEffect = FunctionEffect; 483251662Sdim 484251662Sdim // Finally, now that we know the full effect on this SCC, clone the 485221345Sdim // information to each function in the SCC. 486243830Sdim for (unsigned i = 1, e = SCC.size(); i != e; ++i) 487243830Sdim FunctionInfo[SCC[i]->getFunction()] = FR; 488251662Sdim } 489221345Sdim} 490221345Sdim 491251662Sdim 492251662Sdim 493251662Sdim/// alias - If one of the pointers is to a global that we are tracking, and the 494221345Sdim/// other is some random pointer, we know there cannot be an alias, because the 495198090Srdivacky/// address of the global isn't taken. 496239462SdimAliasAnalysis::AliasResult 497207618SrdivackyGlobalsModRef::alias(const Location &LocA, 498198090Srdivacky const Location &LocB) { 499221345Sdim // Get the base object these pointers point to. 500243830Sdim const Value *UV1 = GetUnderlyingObject(LocA.Ptr); 501221345Sdim const Value *UV2 = GetUnderlyingObject(LocB.Ptr); 502210299Sed 503210299Sed // If either of the underlying values is a global, they may be non-addr-taken 504210299Sed // globals, which we can answer queries about. 505210299Sed const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1); 506210299Sed const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2); 507210299Sed if (GV1 || GV2) { 508210299Sed // If the global's address is taken, pretend we don't know it's a pointer to 509210299Sed // the global. 510210299Sed if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0; 511210299Sed if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0; 512210299Sed 513210299Sed // If the two pointers are derived from two different non-addr-taken 514249423Sdim // globals, or if one is and the other isn't, we know these can't alias. 515249423Sdim if ((GV1 || GV2) && GV1 != GV2) 516249423Sdim return NoAlias; 517249423Sdim 518249423Sdim // Otherwise if they are both derived from the same addr-taken global, we 519249423Sdim // can't know the two accesses don't overlap. 520198090Srdivacky } 521198090Srdivacky 522198090Srdivacky // These pointers may be based on the memory owned by an indirect global. If 523198090Srdivacky // so, we may be able to handle this. First check to see if the base pointer 524210299Sed // is a direct load from an indirect global. 525207618Srdivacky GV1 = GV2 = 0; 526199481Srdivacky if (const LoadInst *LI = dyn_cast<LoadInst>(UV1)) 527234353Sdim if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0))) 528218893Sdim if (IndirectGlobals.count(GV)) 529221345Sdim GV1 = GV; 530221345Sdim if (const LoadInst *LI = dyn_cast<LoadInst>(UV2)) 531199481Srdivacky if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0))) 532210299Sed if (IndirectGlobals.count(GV)) 533210299Sed GV2 = GV; 534210299Sed 535221345Sdim // These pointers may also be from an allocation for the indirect global. If 536200581Srdivacky // so, also handle them. 537210299Sed if (AllocsForIndirectGlobals.count(UV1)) 538210299Sed GV1 = AllocsForIndirectGlobals[UV1]; 539200581Srdivacky if (AllocsForIndirectGlobals.count(UV2)) 540200581Srdivacky GV2 = AllocsForIndirectGlobals[UV2]; 541200581Srdivacky 542200581Srdivacky // Now that we know whether the two pointers are related to indirect globals, 543200581Srdivacky // use this to disambiguate the pointers. If either pointer is based on an 544200581Srdivacky // indirect global and if they are not both based on the same indirect global, 545200581Srdivacky // they cannot alias. 546226633Sdim if ((GV1 || GV2) && GV1 != GV2) 547226633Sdim return NoAlias; 548226633Sdim 549226633Sdim return AliasAnalysis::alias(LocA, LocB); 550226633Sdim} 551249423Sdim 552249423SdimAliasAnalysis::ModRefResult 553249423SdimGlobalsModRef::getModRefInfo(ImmutableCallSite CS, 554221345Sdim const Location &Loc) { 555221345Sdim unsigned Known = ModRef; 556221345Sdim 557221345Sdim // If we are asking for mod/ref info of a direct call with a pointer to a 558221345Sdim // global we are tracking, return information if we have it. 559200581Srdivacky if (const GlobalValue *GV = 560226633Sdim dyn_cast<GlobalValue>(GetUnderlyingObject(Loc.Ptr))) 561226633Sdim if (GV->hasLocalLinkage()) 562226633Sdim if (const Function *F = CS.getCalledFunction()) 563226633Sdim if (NonAddressTakenGlobals.count(GV)) 564226633Sdim if (const FunctionRecord *FR = getFunctionInfo(F)) 565226633Sdim Known = FR->getInfoForGlobal(GV); 566226633Sdim 567221345Sdim if (Known == NoModRef) 568239462Sdim return NoModRef; // No need to query other mod/ref analyses 569239462Sdim return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, Loc)); 570239462Sdim} 571193323Sed 572221345Sdim 573218893Sdim//===----------------------------------------------------------------------===// 574218893Sdim// Methods to update the analysis as a result of the client transformation. 575218893Sdim// 576218893Sdimvoid GlobalsModRef::deleteValue(Value *V) { 577218893Sdim if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 578221345Sdim if (NonAddressTakenGlobals.erase(GV)) { 579221345Sdim // This global might be an indirect global. If so, remove it and remove 580212904Sdim // any AllocRelatedValues for it. 581239462Sdim if (IndirectGlobals.erase(GV)) { 582239462Sdim // Remove any entries in AllocsForIndirectGlobals for this global. 583212904Sdim for (std::map<const Value*, const GlobalValue*>::iterator 584193323Sed I = AllocsForIndirectGlobals.begin(), 585193323Sed E = AllocsForIndirectGlobals.end(); I != E; ) { 586193323Sed if (I->second == GV) { 587 AllocsForIndirectGlobals.erase(I++); 588 } else { 589 ++I; 590 } 591 } 592 } 593 } 594 } 595 596 // Otherwise, if this is an allocation related to an indirect global, remove 597 // it. 598 AllocsForIndirectGlobals.erase(V); 599 600 AliasAnalysis::deleteValue(V); 601} 602 603void GlobalsModRef::copyValue(Value *From, Value *To) { 604 AliasAnalysis::copyValue(From, To); 605} 606 607void GlobalsModRef::addEscapingUse(Use &U) { 608 // For the purposes of this analysis, it is conservatively correct to treat 609 // a newly escaping value equivalently to a deleted one. We could perhaps 610 // be more precise by processing the new use and attempting to update our 611 // saved analysis results to accommodate it. 612 deleteValue(U); 613 614 AliasAnalysis::addEscapingUse(U); 615} 616