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 #include "llvm/Analysis/Passes.h"
18 #include "llvm/ADT/SCCIterator.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/CallGraph.h"
22 #include "llvm/Analysis/MemoryBuiltins.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/InstIterator.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/CommandLine.h"
35 #define DEBUG_TYPE "globalsmodref-aa"
37 STATISTIC(NumNonAddrTakenGlobalVars,
38 "Number of global vars without address taken");
39 STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
40 STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
41 STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
42 STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
45 /// FunctionRecord - One instance of this structure is stored for every
46 /// function in the program. Later, the entries for these functions are
47 /// removed if the function is found to call an external function (in which
48 /// case we know nothing about it.
49 struct FunctionRecord {
50 /// GlobalInfo - Maintain mod/ref info for all of the globals without
51 /// addresses taken that are read or written (transitively) by this
53 std::map<const GlobalValue *, unsigned> GlobalInfo;
55 /// MayReadAnyGlobal - May read global variables, but it is not known which.
56 bool MayReadAnyGlobal;
58 unsigned getInfoForGlobal(const GlobalValue *GV) const {
59 unsigned Effect = MayReadAnyGlobal ? AliasAnalysis::Ref : 0;
60 std::map<const GlobalValue *, unsigned>::const_iterator I =
62 if (I != GlobalInfo.end())
67 /// FunctionEffect - Capture whether or not this function reads or writes to
68 /// ANY memory. If not, we can do a lot of aggressive analysis on it.
69 unsigned FunctionEffect;
71 FunctionRecord() : MayReadAnyGlobal(false), FunctionEffect(0) {}
74 /// GlobalsModRef - The actual analysis pass.
75 class GlobalsModRef : public ModulePass, public AliasAnalysis {
76 /// NonAddressTakenGlobals - The globals that do not have their addresses
78 std::set<const GlobalValue *> NonAddressTakenGlobals;
80 /// IndirectGlobals - The memory pointed to by this global is known to be
81 /// 'owned' by the global.
82 std::set<const GlobalValue *> IndirectGlobals;
84 /// AllocsForIndirectGlobals - If an instruction allocates memory for an
85 /// indirect global, this map indicates which one.
86 std::map<const Value *, const GlobalValue *> AllocsForIndirectGlobals;
88 /// FunctionInfo - For each function, keep track of what globals are
90 std::map<const Function *, FunctionRecord> FunctionInfo;
94 GlobalsModRef() : ModulePass(ID) {
95 initializeGlobalsModRefPass(*PassRegistry::getPassRegistry());
98 bool runOnModule(Module &M) override {
99 InitializeAliasAnalysis(this, &M.getDataLayout());
101 // Find non-addr taken globals.
105 AnalyzeCallGraph(getAnalysis<CallGraphWrapperPass>().getCallGraph(), M);
109 void getAnalysisUsage(AnalysisUsage &AU) const override {
110 AliasAnalysis::getAnalysisUsage(AU);
111 AU.addRequired<CallGraphWrapperPass>();
112 AU.setPreservesAll(); // Does not transform code
115 //------------------------------------------------
116 // Implement the AliasAnalysis API
118 AliasResult alias(const MemoryLocation &LocA,
119 const MemoryLocation &LocB) override;
120 ModRefResult getModRefInfo(ImmutableCallSite CS,
121 const MemoryLocation &Loc) override;
122 ModRefResult getModRefInfo(ImmutableCallSite CS1,
123 ImmutableCallSite CS2) override {
124 return AliasAnalysis::getModRefInfo(CS1, CS2);
127 /// getModRefBehavior - Return the behavior of the specified function if
128 /// called from the specified call site. The call site may be null in which
129 /// case the most generic behavior of this function should be returned.
130 ModRefBehavior getModRefBehavior(const Function *F) override {
131 ModRefBehavior Min = UnknownModRefBehavior;
133 if (FunctionRecord *FR = getFunctionInfo(F)) {
134 if (FR->FunctionEffect == 0)
135 Min = DoesNotAccessMemory;
136 else if ((FR->FunctionEffect & Mod) == 0)
137 Min = OnlyReadsMemory;
140 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
143 /// getModRefBehavior - Return the behavior of the specified function if
144 /// called from the specified call site. The call site may be null in which
145 /// case the most generic behavior of this function should be returned.
146 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override {
147 ModRefBehavior Min = UnknownModRefBehavior;
149 if (const Function *F = CS.getCalledFunction())
150 if (FunctionRecord *FR = getFunctionInfo(F)) {
151 if (FR->FunctionEffect == 0)
152 Min = DoesNotAccessMemory;
153 else if ((FR->FunctionEffect & Mod) == 0)
154 Min = OnlyReadsMemory;
157 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
160 void deleteValue(Value *V) override;
161 void addEscapingUse(Use &U) override;
163 /// getAdjustedAnalysisPointer - This method is used when a pass implements
164 /// an analysis interface through multiple inheritance. If needed, it
165 /// should override this to adjust the this pointer as needed for the
166 /// specified pass info.
167 void *getAdjustedAnalysisPointer(AnalysisID PI) override {
168 if (PI == &AliasAnalysis::ID)
169 return (AliasAnalysis *)this;
174 /// getFunctionInfo - Return the function info for the function, or null if
175 /// we don't have anything useful to say about it.
176 FunctionRecord *getFunctionInfo(const Function *F) {
177 std::map<const Function *, FunctionRecord>::iterator I =
178 FunctionInfo.find(F);
179 if (I != FunctionInfo.end())
184 void AnalyzeGlobals(Module &M);
185 void AnalyzeCallGraph(CallGraph &CG, Module &M);
186 bool AnalyzeUsesOfPointer(Value *V, std::vector<Function *> &Readers,
187 std::vector<Function *> &Writers,
188 GlobalValue *OkayStoreDest = nullptr);
189 bool AnalyzeIndirectGlobalMemory(GlobalValue *GV);
193 char GlobalsModRef::ID = 0;
194 INITIALIZE_AG_PASS_BEGIN(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
195 "Simple mod/ref analysis for globals", false, true,
197 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
198 INITIALIZE_AG_PASS_END(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
199 "Simple mod/ref analysis for globals", false, true,
202 Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
204 /// AnalyzeGlobals - Scan through the users of all of the internal
205 /// GlobalValue's in the program. If none of them have their "address taken"
206 /// (really, their address passed to something nontrivial), record this fact,
207 /// and record the functions that they are used directly in.
208 void GlobalsModRef::AnalyzeGlobals(Module &M) {
209 std::vector<Function *> Readers, Writers;
210 for (Function &F : M)
211 if (F.hasLocalLinkage()) {
212 if (!AnalyzeUsesOfPointer(&F, Readers, Writers)) {
213 // Remember that we are tracking this global.
214 NonAddressTakenGlobals.insert(&F);
215 ++NumNonAddrTakenFunctions;
221 for (GlobalVariable &GV : M.globals())
222 if (GV.hasLocalLinkage()) {
223 if (!AnalyzeUsesOfPointer(&GV, Readers, Writers)) {
224 // Remember that we are tracking this global, and the mod/ref fns
225 NonAddressTakenGlobals.insert(&GV);
227 for (Function *Reader : Readers)
228 FunctionInfo[Reader].GlobalInfo[&GV] |= Ref;
230 if (!GV.isConstant()) // No need to keep track of writers to constants
231 for (Function *Writer : Writers)
232 FunctionInfo[Writer].GlobalInfo[&GV] |= Mod;
233 ++NumNonAddrTakenGlobalVars;
235 // If this global holds a pointer type, see if it is an indirect global.
236 if (GV.getType()->getElementType()->isPointerTy() &&
237 AnalyzeIndirectGlobalMemory(&GV))
238 ++NumIndirectGlobalVars;
245 /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
246 /// If this is used by anything complex (i.e., the address escapes), return
247 /// true. Also, while we are at it, keep track of those functions that read and
248 /// write to the value.
250 /// If OkayStoreDest is non-null, stores into this global are allowed.
251 bool GlobalsModRef::AnalyzeUsesOfPointer(Value *V,
252 std::vector<Function *> &Readers,
253 std::vector<Function *> &Writers,
254 GlobalValue *OkayStoreDest) {
255 if (!V->getType()->isPointerTy())
258 for (Use &U : V->uses()) {
259 User *I = U.getUser();
260 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
261 Readers.push_back(LI->getParent()->getParent());
262 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
263 if (V == SI->getOperand(1)) {
264 Writers.push_back(SI->getParent()->getParent());
265 } else if (SI->getOperand(1) != OkayStoreDest) {
266 return true; // Storing the pointer
268 } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
269 if (AnalyzeUsesOfPointer(I, Readers, Writers))
271 } else if (Operator::getOpcode(I) == Instruction::BitCast) {
272 if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
274 } else if (auto CS = CallSite(I)) {
275 // Make sure that this is just the function being called, not that it is
276 // passing into the function.
277 if (!CS.isCallee(&U)) {
278 // Detect calls to free.
279 if (isFreeCall(I, TLI))
280 Writers.push_back(CS->getParent()->getParent());
282 return true; // Argument of an unknown call.
284 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
285 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
286 return true; // Allow comparison against null.
295 /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
296 /// which holds a pointer type. See if the global always points to non-aliased
297 /// heap memory: that is, all initializers of the globals are allocations, and
298 /// those allocations have no use other than initialization of the global.
299 /// Further, all loads out of GV must directly use the memory, not store the
300 /// pointer somewhere. If this is true, we consider the memory pointed to by
301 /// GV to be owned by GV and can disambiguate other pointers from it.
302 bool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
303 // Keep track of values related to the allocation of the memory, f.e. the
304 // value produced by the malloc call and any casts.
305 std::vector<Value *> AllocRelatedValues;
307 // Walk the user list of the global. If we find anything other than a direct
308 // load or store, bail out.
309 for (User *U : GV->users()) {
310 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
311 // The pointer loaded from the global can only be used in simple ways:
312 // we allow addressing of it and loading storing to it. We do *not* allow
313 // storing the loaded pointer somewhere else or passing to a function.
314 std::vector<Function *> ReadersWriters;
315 if (AnalyzeUsesOfPointer(LI, ReadersWriters, ReadersWriters))
316 return false; // Loaded pointer escapes.
317 // TODO: Could try some IP mod/ref of the loaded pointer.
318 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
319 // Storing the global itself.
320 if (SI->getOperand(0) == GV)
323 // If storing the null pointer, ignore it.
324 if (isa<ConstantPointerNull>(SI->getOperand(0)))
327 // Check the value being stored.
328 Value *Ptr = GetUnderlyingObject(SI->getOperand(0),
329 GV->getParent()->getDataLayout());
331 if (!isAllocLikeFn(Ptr, TLI))
332 return false; // Too hard to analyze.
334 // Analyze all uses of the allocation. If any of them are used in a
335 // non-simple way (e.g. stored to another global) bail out.
336 std::vector<Function *> ReadersWriters;
337 if (AnalyzeUsesOfPointer(Ptr, ReadersWriters, ReadersWriters, GV))
338 return false; // Loaded pointer escapes.
340 // Remember that this allocation is related to the indirect global.
341 AllocRelatedValues.push_back(Ptr);
343 // Something complex, bail out.
348 // Okay, this is an indirect global. Remember all of the allocations for
349 // this global in AllocsForIndirectGlobals.
350 while (!AllocRelatedValues.empty()) {
351 AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
352 AllocRelatedValues.pop_back();
354 IndirectGlobals.insert(GV);
358 /// AnalyzeCallGraph - At this point, we know the functions where globals are
359 /// immediately stored to and read from. Propagate this information up the call
360 /// graph to all callers and compute the mod/ref info for all memory for each
362 void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
363 // We do a bottom-up SCC traversal of the call graph. In other words, we
364 // visit all callees before callers (leaf-first).
365 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
366 const std::vector<CallGraphNode *> &SCC = *I;
367 assert(!SCC.empty() && "SCC with no functions?");
369 if (!SCC[0]->getFunction()) {
370 // Calls externally - can't say anything useful. Remove any existing
371 // function records (may have been created when scanning globals).
372 for (auto *Node : SCC)
373 FunctionInfo.erase(Node->getFunction());
377 FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
379 bool KnowNothing = false;
380 unsigned FunctionEffect = 0;
382 // Collect the mod/ref properties due to called functions. We only compute
384 for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
385 Function *F = SCC[i]->getFunction();
391 if (F->isDeclaration()) {
392 // Try to get mod/ref behaviour from function attributes.
393 if (F->doesNotAccessMemory()) {
394 // Can't do better than that!
395 } else if (F->onlyReadsMemory()) {
396 FunctionEffect |= Ref;
397 if (!F->isIntrinsic())
398 // This function might call back into the module and read a global -
399 // consider every global as possibly being read by this function.
400 FR.MayReadAnyGlobal = true;
402 FunctionEffect |= ModRef;
403 // Can't say anything useful unless it's an intrinsic - they don't
404 // read or write global variables of the kind considered here.
405 KnowNothing = !F->isIntrinsic();
410 for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
411 CI != E && !KnowNothing; ++CI)
412 if (Function *Callee = CI->second->getFunction()) {
413 if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
414 // Propagate function effect up.
415 FunctionEffect |= CalleeFR->FunctionEffect;
417 // Incorporate callee's effects on globals into our info.
418 for (const auto &G : CalleeFR->GlobalInfo)
419 FR.GlobalInfo[G.first] |= G.second;
420 FR.MayReadAnyGlobal |= CalleeFR->MayReadAnyGlobal;
422 // Can't say anything about it. However, if it is inside our SCC,
423 // then nothing needs to be done.
424 CallGraphNode *CalleeNode = CG[Callee];
425 if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end())
433 // If we can't say anything useful about this SCC, remove all SCC functions
434 // from the FunctionInfo map.
436 for (auto *Node : SCC)
437 FunctionInfo.erase(Node->getFunction());
441 // Scan the function bodies for explicit loads or stores.
442 for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;
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 (LoadInst *LI = dyn_cast<LoadInst>(&*II)) {
448 FunctionEffect |= Ref;
449 if (LI->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 (StoreInst *SI = dyn_cast<StoreInst>(&*II)) {
454 FunctionEffect |= Mod;
455 if (SI->isVolatile())
456 // Treat volatile stores as reading memory somewhere.
457 FunctionEffect |= Ref;
458 } else if (isAllocationFn(&*II, TLI) || isFreeCall(&*II, TLI)) {
459 FunctionEffect |= ModRef;
460 } else if (IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(&*II)) {
461 // The callgraph doesn't include intrinsic calls.
462 Function *Callee = Intrinsic->getCalledFunction();
463 ModRefBehavior Behaviour = AliasAnalysis::getModRefBehavior(Callee);
464 FunctionEffect |= (Behaviour & ModRef);
467 if ((FunctionEffect & Mod) == 0)
468 ++NumReadMemFunctions;
469 if (FunctionEffect == 0)
471 FR.FunctionEffect = FunctionEffect;
473 // Finally, now that we know the full effect on this SCC, clone the
474 // information to each function in the SCC.
475 for (unsigned i = 1, e = SCC.size(); i != e; ++i)
476 FunctionInfo[SCC[i]->getFunction()] = FR;
480 /// alias - If one of the pointers is to a global that we are tracking, and the
481 /// other is some random pointer, we know there cannot be an alias, because the
482 /// address of the global isn't taken.
483 AliasResult GlobalsModRef::alias(const MemoryLocation &LocA,
484 const MemoryLocation &LocB) {
485 // Get the base object these pointers point to.
486 const Value *UV1 = GetUnderlyingObject(LocA.Ptr, *DL);
487 const Value *UV2 = GetUnderlyingObject(LocB.Ptr, *DL);
489 // If either of the underlying values is a global, they may be non-addr-taken
490 // globals, which we can answer queries about.
491 const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
492 const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
494 // If the global's address is taken, pretend we don't know it's a pointer to
496 if (GV1 && !NonAddressTakenGlobals.count(GV1))
498 if (GV2 && !NonAddressTakenGlobals.count(GV2))
501 // If the two pointers are derived from two different non-addr-taken
502 // globals, or if one is and the other isn't, we know these can't alias.
503 if ((GV1 || GV2) && GV1 != GV2)
506 // Otherwise if they are both derived from the same addr-taken global, we
507 // can't know the two accesses don't overlap.
510 // These pointers may be based on the memory owned by an indirect global. If
511 // so, we may be able to handle this. First check to see if the base pointer
512 // is a direct load from an indirect global.
514 if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
515 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
516 if (IndirectGlobals.count(GV))
518 if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
519 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
520 if (IndirectGlobals.count(GV))
523 // These pointers may also be from an allocation for the indirect global. If
524 // so, also handle them.
525 if (AllocsForIndirectGlobals.count(UV1))
526 GV1 = AllocsForIndirectGlobals[UV1];
527 if (AllocsForIndirectGlobals.count(UV2))
528 GV2 = AllocsForIndirectGlobals[UV2];
530 // Now that we know whether the two pointers are related to indirect globals,
531 // use this to disambiguate the pointers. If either pointer is based on an
532 // indirect global and if they are not both based on the same indirect global,
533 // they cannot alias.
534 if ((GV1 || GV2) && GV1 != GV2)
537 return AliasAnalysis::alias(LocA, LocB);
540 AliasAnalysis::ModRefResult
541 GlobalsModRef::getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc) {
542 unsigned Known = ModRef;
544 // If we are asking for mod/ref info of a direct call with a pointer to a
545 // global we are tracking, return information if we have it.
546 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
547 if (const GlobalValue *GV =
548 dyn_cast<GlobalValue>(GetUnderlyingObject(Loc.Ptr, DL)))
549 if (GV->hasLocalLinkage())
550 if (const Function *F = CS.getCalledFunction())
551 if (NonAddressTakenGlobals.count(GV))
552 if (const FunctionRecord *FR = getFunctionInfo(F))
553 Known = FR->getInfoForGlobal(GV);
555 if (Known == NoModRef)
556 return NoModRef; // No need to query other mod/ref analyses
557 return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, Loc));
560 //===----------------------------------------------------------------------===//
561 // Methods to update the analysis as a result of the client transformation.
563 void GlobalsModRef::deleteValue(Value *V) {
564 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
565 if (NonAddressTakenGlobals.erase(GV)) {
566 // This global might be an indirect global. If so, remove it and remove
567 // any AllocRelatedValues for it.
568 if (IndirectGlobals.erase(GV)) {
569 // Remove any entries in AllocsForIndirectGlobals for this global.
570 for (std::map<const Value *, const GlobalValue *>::iterator
571 I = AllocsForIndirectGlobals.begin(),
572 E = AllocsForIndirectGlobals.end();
574 if (I->second == GV) {
575 AllocsForIndirectGlobals.erase(I++);
584 // Otherwise, if this is an allocation related to an indirect global, remove
586 AllocsForIndirectGlobals.erase(V);
588 AliasAnalysis::deleteValue(V);
591 void GlobalsModRef::addEscapingUse(Use &U) {
592 // For the purposes of this analysis, it is conservatively correct to treat
593 // a newly escaping value equivalently to a deleted one. We could perhaps
594 // be more precise by processing the new use and attempting to update our
595 // saved analysis results to accommodate it.
598 AliasAnalysis::addEscapingUse(U);