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/SmallPtrSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/CallGraph.h"
23 #include "llvm/Analysis/MemoryBuiltins.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/InstIterator.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
36 #define DEBUG_TYPE "globalsmodref-aa"
38 STATISTIC(NumNonAddrTakenGlobalVars,
39 "Number of global vars without address taken");
40 STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
41 STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
42 STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
43 STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
45 // An option to enable unsafe alias results from the GlobalsModRef analysis.
46 // When enabled, GlobalsModRef will provide no-alias results which in extremely
47 // rare cases may not be conservatively correct. In particular, in the face of
48 // transforms which cause assymetry between how effective GetUnderlyingObject
49 // is for two pointers, it may produce incorrect results.
51 // These unsafe results have been returned by GMR for many years without
52 // causing significant issues in the wild and so we provide a mechanism to
53 // re-enable them for users of LLVM that have a particular performance
54 // sensitivity and no known issues. The option also makes it easy to evaluate
55 // the performance impact of these results.
56 static cl::opt<bool> EnableUnsafeGlobalsModRefAliasResults(
57 "enable-unsafe-globalsmodref-alias-results", cl::init(false), cl::Hidden);
60 /// The mod/ref information collected for a particular function.
62 /// We collect information about mod/ref behavior of a function here, both in
63 /// general and as pertains to specific globals. We only have this detailed
64 /// information when we know *something* useful about the behavior. If we
65 /// saturate to fully general mod/ref, we remove the info for the function.
67 typedef SmallDenseMap<const GlobalValue *, ModRefInfo, 16> GlobalInfoMapType;
69 /// Build a wrapper struct that has 8-byte alignment. All heap allocations
70 /// should provide this much alignment at least, but this makes it clear we
71 /// specifically rely on this amount of alignment.
72 struct LLVM_ALIGNAS(8) AlignedMap {
74 AlignedMap(const AlignedMap &Arg) : Map(Arg.Map) {}
75 GlobalInfoMapType Map;
78 /// Pointer traits for our aligned map.
79 struct AlignedMapPointerTraits {
80 static inline void *getAsVoidPointer(AlignedMap *P) { return P; }
81 static inline AlignedMap *getFromVoidPointer(void *P) {
82 return (AlignedMap *)P;
84 enum { NumLowBitsAvailable = 3 };
85 static_assert(AlignOf<AlignedMap>::Alignment >= (1 << NumLowBitsAvailable),
86 "AlignedMap insufficiently aligned to have enough low bits.");
89 /// The bit that flags that this function may read any global. This is
90 /// chosen to mix together with ModRefInfo bits.
91 enum { MayReadAnyGlobal = 4 };
93 /// Checks to document the invariants of the bit packing here.
94 static_assert((MayReadAnyGlobal & MRI_ModRef) == 0,
95 "ModRef and the MayReadAnyGlobal flag bits overlap.");
96 static_assert(((MayReadAnyGlobal | MRI_ModRef) >>
97 AlignedMapPointerTraits::NumLowBitsAvailable) == 0,
98 "Insufficient low bits to store our flag and ModRef info.");
101 FunctionInfo() : Info() {}
103 delete Info.getPointer();
105 // Spell out the copy ond move constructors and assignment operators to get
106 // deep copy semantics and correct move semantics in the face of the
108 FunctionInfo(const FunctionInfo &Arg)
109 : Info(nullptr, Arg.Info.getInt()) {
110 if (const auto *ArgPtr = Arg.Info.getPointer())
111 Info.setPointer(new AlignedMap(*ArgPtr));
113 FunctionInfo(FunctionInfo &&Arg)
114 : Info(Arg.Info.getPointer(), Arg.Info.getInt()) {
115 Arg.Info.setPointerAndInt(nullptr, 0);
117 FunctionInfo &operator=(const FunctionInfo &RHS) {
118 delete Info.getPointer();
119 Info.setPointerAndInt(nullptr, RHS.Info.getInt());
120 if (const auto *RHSPtr = RHS.Info.getPointer())
121 Info.setPointer(new AlignedMap(*RHSPtr));
124 FunctionInfo &operator=(FunctionInfo &&RHS) {
125 delete Info.getPointer();
126 Info.setPointerAndInt(RHS.Info.getPointer(), RHS.Info.getInt());
127 RHS.Info.setPointerAndInt(nullptr, 0);
131 /// Returns the \c ModRefInfo info for this function.
132 ModRefInfo getModRefInfo() const {
133 return ModRefInfo(Info.getInt() & MRI_ModRef);
136 /// Adds new \c ModRefInfo for this function to its state.
137 void addModRefInfo(ModRefInfo NewMRI) {
138 Info.setInt(Info.getInt() | NewMRI);
141 /// Returns whether this function may read any global variable, and we don't
142 /// know which global.
143 bool mayReadAnyGlobal() const { return Info.getInt() & MayReadAnyGlobal; }
145 /// Sets this function as potentially reading from any global.
146 void setMayReadAnyGlobal() { Info.setInt(Info.getInt() | MayReadAnyGlobal); }
148 /// Returns the \c ModRefInfo info for this function w.r.t. a particular
149 /// global, which may be more precise than the general information above.
150 ModRefInfo getModRefInfoForGlobal(const GlobalValue &GV) const {
151 ModRefInfo GlobalMRI = mayReadAnyGlobal() ? MRI_Ref : MRI_NoModRef;
152 if (AlignedMap *P = Info.getPointer()) {
153 auto I = P->Map.find(&GV);
154 if (I != P->Map.end())
155 GlobalMRI = ModRefInfo(GlobalMRI | I->second);
160 /// Add mod/ref info from another function into ours, saturating towards
162 void addFunctionInfo(const FunctionInfo &FI) {
163 addModRefInfo(FI.getModRefInfo());
165 if (FI.mayReadAnyGlobal())
166 setMayReadAnyGlobal();
168 if (AlignedMap *P = FI.Info.getPointer())
169 for (const auto &G : P->Map)
170 addModRefInfoForGlobal(*G.first, G.second);
173 void addModRefInfoForGlobal(const GlobalValue &GV, ModRefInfo NewMRI) {
174 AlignedMap *P = Info.getPointer();
176 P = new AlignedMap();
179 auto &GlobalMRI = P->Map[&GV];
180 GlobalMRI = ModRefInfo(GlobalMRI | NewMRI);
184 /// All of the information is encoded into a single pointer, with a three bit
185 /// integer in the low three bits. The high bit provides a flag for when this
186 /// function may read any global. The low two bits are the ModRefInfo. And
187 /// the pointer, when non-null, points to a map from GlobalValue to
188 /// ModRefInfo specific to that GlobalValue.
189 PointerIntPair<AlignedMap *, 3, unsigned, AlignedMapPointerTraits> Info;
192 /// GlobalsModRef - The actual analysis pass.
193 class GlobalsModRef : public ModulePass, public AliasAnalysis {
194 /// The globals that do not have their addresses taken.
195 SmallPtrSet<const GlobalValue *, 8> NonAddressTakenGlobals;
197 /// IndirectGlobals - The memory pointed to by this global is known to be
198 /// 'owned' by the global.
199 SmallPtrSet<const GlobalValue *, 8> IndirectGlobals;
201 /// AllocsForIndirectGlobals - If an instruction allocates memory for an
202 /// indirect global, this map indicates which one.
203 DenseMap<const Value *, const GlobalValue *> AllocsForIndirectGlobals;
205 /// For each function, keep track of what globals are modified or read.
206 DenseMap<const Function *, FunctionInfo> FunctionInfos;
208 /// Handle to clear this analysis on deletion of values.
209 struct DeletionCallbackHandle final : CallbackVH {
211 std::list<DeletionCallbackHandle>::iterator I;
213 DeletionCallbackHandle(GlobalsModRef &GMR, Value *V)
214 : CallbackVH(V), GMR(GMR) {}
216 void deleted() override {
217 Value *V = getValPtr();
218 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
219 if (GMR.NonAddressTakenGlobals.erase(GV)) {
220 // This global might be an indirect global. If so, remove it and
222 // any AllocRelatedValues for it.
223 if (GMR.IndirectGlobals.erase(GV)) {
224 // Remove any entries in AllocsForIndirectGlobals for this global.
225 for (auto I = GMR.AllocsForIndirectGlobals.begin(),
226 E = GMR.AllocsForIndirectGlobals.end();
229 GMR.AllocsForIndirectGlobals.erase(I);
234 // If this is an allocation related to an indirect global, remove it.
235 GMR.AllocsForIndirectGlobals.erase(V);
237 // And clear out the handle.
239 GMR.Handles.erase(I);
240 // This object is now destroyed!
244 /// List of callbacks for globals being tracked by this analysis. Note that
245 /// these objects are quite large, but we only anticipate having one per
246 /// global tracked by this analysis. There are numerous optimizations we
247 /// could perform to the memory utilization here if this becomes a problem.
248 std::list<DeletionCallbackHandle> Handles;
252 GlobalsModRef() : ModulePass(ID) {
253 initializeGlobalsModRefPass(*PassRegistry::getPassRegistry());
256 bool runOnModule(Module &M) override {
257 InitializeAliasAnalysis(this, &M.getDataLayout());
259 // Find non-addr taken globals.
263 AnalyzeCallGraph(getAnalysis<CallGraphWrapperPass>().getCallGraph(), M);
267 void getAnalysisUsage(AnalysisUsage &AU) const override {
268 AliasAnalysis::getAnalysisUsage(AU);
269 AU.addRequired<CallGraphWrapperPass>();
270 AU.setPreservesAll(); // Does not transform code
273 /// getAdjustedAnalysisPointer - This method is used when a pass implements
274 /// an analysis interface through multiple inheritance. If needed, it
275 /// should override this to adjust the this pointer as needed for the
276 /// specified pass info.
277 void *getAdjustedAnalysisPointer(AnalysisID PI) override {
278 if (PI == &AliasAnalysis::ID)
279 return (AliasAnalysis *)this;
283 //------------------------------------------------
284 // Implement the AliasAnalysis API
286 AliasResult alias(const MemoryLocation &LocA,
287 const MemoryLocation &LocB) override;
288 ModRefInfo getModRefInfo(ImmutableCallSite CS,
289 const MemoryLocation &Loc) override;
290 ModRefInfo getModRefInfo(ImmutableCallSite CS1,
291 ImmutableCallSite CS2) override {
292 return AliasAnalysis::getModRefInfo(CS1, CS2);
295 /// getModRefBehavior - Return the behavior of the specified function if
296 /// called from the specified call site. The call site may be null in which
297 /// case the most generic behavior of this function should be returned.
298 FunctionModRefBehavior getModRefBehavior(const Function *F) override {
299 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
301 if (FunctionInfo *FI = getFunctionInfo(F)) {
302 if (FI->getModRefInfo() == MRI_NoModRef)
303 Min = FMRB_DoesNotAccessMemory;
304 else if ((FI->getModRefInfo() & MRI_Mod) == 0)
305 Min = FMRB_OnlyReadsMemory;
308 return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
311 /// getModRefBehavior - Return the behavior of the specified function if
312 /// called from the specified call site. The call site may be null in which
313 /// case the most generic behavior of this function should be returned.
314 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) override {
315 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
317 if (const Function *F = CS.getCalledFunction())
318 if (FunctionInfo *FI = getFunctionInfo(F)) {
319 if (FI->getModRefInfo() == MRI_NoModRef)
320 Min = FMRB_DoesNotAccessMemory;
321 else if ((FI->getModRefInfo() & MRI_Mod) == 0)
322 Min = FMRB_OnlyReadsMemory;
325 return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
329 /// Returns the function info for the function, or null if we don't have
330 /// anything useful to say about it.
331 FunctionInfo *getFunctionInfo(const Function *F) {
332 auto I = FunctionInfos.find(F);
333 if (I != FunctionInfos.end())
338 void AnalyzeGlobals(Module &M);
339 void AnalyzeCallGraph(CallGraph &CG, Module &M);
340 bool AnalyzeUsesOfPointer(Value *V,
341 SmallPtrSetImpl<Function *> *Readers = nullptr,
342 SmallPtrSetImpl<Function *> *Writers = nullptr,
343 GlobalValue *OkayStoreDest = nullptr);
344 bool AnalyzeIndirectGlobalMemory(GlobalValue *GV);
348 char GlobalsModRef::ID = 0;
349 INITIALIZE_AG_PASS_BEGIN(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
350 "Simple mod/ref analysis for globals", false, true,
352 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
353 INITIALIZE_AG_PASS_END(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
354 "Simple mod/ref analysis for globals", false, true,
357 Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
359 /// AnalyzeGlobals - Scan through the users of all of the internal
360 /// GlobalValue's in the program. If none of them have their "address taken"
361 /// (really, their address passed to something nontrivial), record this fact,
362 /// and record the functions that they are used directly in.
363 void GlobalsModRef::AnalyzeGlobals(Module &M) {
364 for (Function &F : M)
365 if (F.hasLocalLinkage())
366 if (!AnalyzeUsesOfPointer(&F)) {
367 // Remember that we are tracking this global.
368 NonAddressTakenGlobals.insert(&F);
369 Handles.emplace_front(*this, &F);
370 Handles.front().I = Handles.begin();
371 ++NumNonAddrTakenFunctions;
374 SmallPtrSet<Function *, 64> Readers, Writers;
375 for (GlobalVariable &GV : M.globals())
376 if (GV.hasLocalLinkage()) {
377 if (!AnalyzeUsesOfPointer(&GV, &Readers,
378 GV.isConstant() ? nullptr : &Writers)) {
379 // Remember that we are tracking this global, and the mod/ref fns
380 NonAddressTakenGlobals.insert(&GV);
381 Handles.emplace_front(*this, &GV);
382 Handles.front().I = Handles.begin();
384 for (Function *Reader : Readers)
385 FunctionInfos[Reader].addModRefInfoForGlobal(GV, MRI_Ref);
387 if (!GV.isConstant()) // No need to keep track of writers to constants
388 for (Function *Writer : Writers)
389 FunctionInfos[Writer].addModRefInfoForGlobal(GV, MRI_Mod);
390 ++NumNonAddrTakenGlobalVars;
392 // If this global holds a pointer type, see if it is an indirect global.
393 if (GV.getType()->getElementType()->isPointerTy() &&
394 AnalyzeIndirectGlobalMemory(&GV))
395 ++NumIndirectGlobalVars;
402 /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
403 /// If this is used by anything complex (i.e., the address escapes), return
404 /// true. Also, while we are at it, keep track of those functions that read and
405 /// write to the value.
407 /// If OkayStoreDest is non-null, stores into this global are allowed.
408 bool GlobalsModRef::AnalyzeUsesOfPointer(Value *V,
409 SmallPtrSetImpl<Function *> *Readers,
410 SmallPtrSetImpl<Function *> *Writers,
411 GlobalValue *OkayStoreDest) {
412 if (!V->getType()->isPointerTy())
415 for (Use &U : V->uses()) {
416 User *I = U.getUser();
417 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
419 Readers->insert(LI->getParent()->getParent());
420 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
421 if (V == SI->getOperand(1)) {
423 Writers->insert(SI->getParent()->getParent());
424 } else if (SI->getOperand(1) != OkayStoreDest) {
425 return true; // Storing the pointer
427 } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
428 if (AnalyzeUsesOfPointer(I, Readers, Writers))
430 } else if (Operator::getOpcode(I) == Instruction::BitCast) {
431 if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
433 } else if (auto CS = CallSite(I)) {
434 // Make sure that this is just the function being called, not that it is
435 // passing into the function.
436 if (!CS.isCallee(&U)) {
437 // Detect calls to free.
438 if (isFreeCall(I, TLI)) {
440 Writers->insert(CS->getParent()->getParent());
442 return true; // Argument of an unknown call.
445 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
446 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
447 return true; // Allow comparison against null.
456 /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
457 /// which holds a pointer type. See if the global always points to non-aliased
458 /// heap memory: that is, all initializers of the globals are allocations, and
459 /// those allocations have no use other than initialization of the global.
460 /// Further, all loads out of GV must directly use the memory, not store the
461 /// pointer somewhere. If this is true, we consider the memory pointed to by
462 /// GV to be owned by GV and can disambiguate other pointers from it.
463 bool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
464 // Keep track of values related to the allocation of the memory, f.e. the
465 // value produced by the malloc call and any casts.
466 std::vector<Value *> AllocRelatedValues;
468 // Walk the user list of the global. If we find anything other than a direct
469 // load or store, bail out.
470 for (User *U : GV->users()) {
471 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
472 // The pointer loaded from the global can only be used in simple ways:
473 // we allow addressing of it and loading storing to it. We do *not* allow
474 // storing the loaded pointer somewhere else or passing to a function.
475 if (AnalyzeUsesOfPointer(LI))
476 return false; // Loaded pointer escapes.
477 // TODO: Could try some IP mod/ref of the loaded pointer.
478 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
479 // Storing the global itself.
480 if (SI->getOperand(0) == GV)
483 // If storing the null pointer, ignore it.
484 if (isa<ConstantPointerNull>(SI->getOperand(0)))
487 // Check the value being stored.
488 Value *Ptr = GetUnderlyingObject(SI->getOperand(0),
489 GV->getParent()->getDataLayout());
491 if (!isAllocLikeFn(Ptr, TLI))
492 return false; // Too hard to analyze.
494 // Analyze all uses of the allocation. If any of them are used in a
495 // non-simple way (e.g. stored to another global) bail out.
496 if (AnalyzeUsesOfPointer(Ptr, /*Readers*/ nullptr, /*Writers*/ nullptr,
498 return false; // Loaded pointer escapes.
500 // Remember that this allocation is related to the indirect global.
501 AllocRelatedValues.push_back(Ptr);
503 // Something complex, bail out.
508 // Okay, this is an indirect global. Remember all of the allocations for
509 // this global in AllocsForIndirectGlobals.
510 while (!AllocRelatedValues.empty()) {
511 AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
512 Handles.emplace_front(*this, AllocRelatedValues.back());
513 Handles.front().I = Handles.begin();
514 AllocRelatedValues.pop_back();
516 IndirectGlobals.insert(GV);
517 Handles.emplace_front(*this, GV);
518 Handles.front().I = Handles.begin();
522 /// AnalyzeCallGraph - At this point, we know the functions where globals are
523 /// immediately stored to and read from. Propagate this information up the call
524 /// graph to all callers and compute the mod/ref info for all memory for each
526 void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
527 // We do a bottom-up SCC traversal of the call graph. In other words, we
528 // visit all callees before callers (leaf-first).
529 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
530 const std::vector<CallGraphNode *> &SCC = *I;
531 assert(!SCC.empty() && "SCC with no functions?");
533 if (!SCC[0]->getFunction()) {
534 // Calls externally - can't say anything useful. Remove any existing
535 // function records (may have been created when scanning globals).
536 for (auto *Node : SCC)
537 FunctionInfos.erase(Node->getFunction());
541 FunctionInfo &FI = FunctionInfos[SCC[0]->getFunction()];
542 bool KnowNothing = false;
544 // Collect the mod/ref properties due to called functions. We only compute
546 for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
547 Function *F = SCC[i]->getFunction();
553 if (F->isDeclaration()) {
554 // Try to get mod/ref behaviour from function attributes.
555 if (F->doesNotAccessMemory()) {
556 // Can't do better than that!
557 } else if (F->onlyReadsMemory()) {
558 FI.addModRefInfo(MRI_Ref);
559 if (!F->isIntrinsic())
560 // This function might call back into the module and read a global -
561 // consider every global as possibly being read by this function.
562 FI.setMayReadAnyGlobal();
564 FI.addModRefInfo(MRI_ModRef);
565 // Can't say anything useful unless it's an intrinsic - they don't
566 // read or write global variables of the kind considered here.
567 KnowNothing = !F->isIntrinsic();
572 for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
573 CI != E && !KnowNothing; ++CI)
574 if (Function *Callee = CI->second->getFunction()) {
575 if (FunctionInfo *CalleeFI = getFunctionInfo(Callee)) {
576 // Propagate function effect up.
577 FI.addFunctionInfo(*CalleeFI);
579 // Can't say anything about it. However, if it is inside our SCC,
580 // then nothing needs to be done.
581 CallGraphNode *CalleeNode = CG[Callee];
582 if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end())
590 // If we can't say anything useful about this SCC, remove all SCC functions
591 // from the FunctionInfos map.
593 for (auto *Node : SCC)
594 FunctionInfos.erase(Node->getFunction());
598 // Scan the function bodies for explicit loads or stores.
599 for (auto *Node : SCC) {
600 if (FI.getModRefInfo() == MRI_ModRef)
601 break; // The mod/ref lattice saturates here.
602 for (Instruction &I : inst_range(Node->getFunction())) {
603 if (FI.getModRefInfo() == MRI_ModRef)
604 break; // The mod/ref lattice saturates here.
606 // We handle calls specially because the graph-relevant aspects are
608 if (auto CS = CallSite(&I)) {
609 if (isAllocationFn(&I, TLI) || isFreeCall(&I, TLI)) {
610 // FIXME: It is completely unclear why this is necessary and not
611 // handled by the above graph code.
612 FI.addModRefInfo(MRI_ModRef);
613 } else if (Function *Callee = CS.getCalledFunction()) {
614 // The callgraph doesn't include intrinsic calls.
615 if (Callee->isIntrinsic()) {
616 FunctionModRefBehavior Behaviour =
617 AliasAnalysis::getModRefBehavior(Callee);
618 FI.addModRefInfo(ModRefInfo(Behaviour & MRI_ModRef));
624 // All non-call instructions we use the primary predicates for whether
625 // thay read or write memory.
626 if (I.mayReadFromMemory())
627 FI.addModRefInfo(MRI_Ref);
628 if (I.mayWriteToMemory())
629 FI.addModRefInfo(MRI_Mod);
633 if ((FI.getModRefInfo() & MRI_Mod) == 0)
634 ++NumReadMemFunctions;
635 if (FI.getModRefInfo() == MRI_NoModRef)
638 // Finally, now that we know the full effect on this SCC, clone the
639 // information to each function in the SCC.
640 for (unsigned i = 1, e = SCC.size(); i != e; ++i)
641 FunctionInfos[SCC[i]->getFunction()] = FI;
645 /// alias - If one of the pointers is to a global that we are tracking, and the
646 /// other is some random pointer, we know there cannot be an alias, because the
647 /// address of the global isn't taken.
648 AliasResult GlobalsModRef::alias(const MemoryLocation &LocA,
649 const MemoryLocation &LocB) {
650 // Get the base object these pointers point to.
651 const Value *UV1 = GetUnderlyingObject(LocA.Ptr, *DL);
652 const Value *UV2 = GetUnderlyingObject(LocB.Ptr, *DL);
654 // If either of the underlying values is a global, they may be non-addr-taken
655 // globals, which we can answer queries about.
656 const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
657 const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
659 // If the global's address is taken, pretend we don't know it's a pointer to
661 if (GV1 && !NonAddressTakenGlobals.count(GV1))
663 if (GV2 && !NonAddressTakenGlobals.count(GV2))
666 // If the two pointers are derived from two different non-addr-taken
667 // globals we know these can't alias.
668 if (GV1 && GV2 && GV1 != GV2)
671 // If one is and the other isn't, it isn't strictly safe but we can fake
672 // this result if necessary for performance. This does not appear to be
673 // a common problem in practice.
674 if (EnableUnsafeGlobalsModRefAliasResults)
675 if ((GV1 || GV2) && GV1 != GV2)
678 // Otherwise if they are both derived from the same addr-taken global, we
679 // can't know the two accesses don't overlap.
682 // These pointers may be based on the memory owned by an indirect global. If
683 // so, we may be able to handle this. First check to see if the base pointer
684 // is a direct load from an indirect global.
686 if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
687 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
688 if (IndirectGlobals.count(GV))
690 if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
691 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
692 if (IndirectGlobals.count(GV))
695 // These pointers may also be from an allocation for the indirect global. If
696 // so, also handle them.
698 GV1 = AllocsForIndirectGlobals.lookup(UV1);
700 GV2 = AllocsForIndirectGlobals.lookup(UV2);
702 // Now that we know whether the two pointers are related to indirect globals,
703 // use this to disambiguate the pointers. If the pointers are based on
704 // different indirect globals they cannot alias.
705 if (GV1 && GV2 && GV1 != GV2)
708 // If one is based on an indirect global and the other isn't, it isn't
709 // strictly safe but we can fake this result if necessary for performance.
710 // This does not appear to be a common problem in practice.
711 if (EnableUnsafeGlobalsModRefAliasResults)
712 if ((GV1 || GV2) && GV1 != GV2)
715 return AliasAnalysis::alias(LocA, LocB);
718 ModRefInfo GlobalsModRef::getModRefInfo(ImmutableCallSite CS,
719 const MemoryLocation &Loc) {
720 unsigned Known = MRI_ModRef;
722 // If we are asking for mod/ref info of a direct call with a pointer to a
723 // global we are tracking, return information if we have it.
724 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
725 if (const GlobalValue *GV =
726 dyn_cast<GlobalValue>(GetUnderlyingObject(Loc.Ptr, DL)))
727 if (GV->hasLocalLinkage())
728 if (const Function *F = CS.getCalledFunction())
729 if (NonAddressTakenGlobals.count(GV))
730 if (const FunctionInfo *FI = getFunctionInfo(F))
731 Known = FI->getModRefInfoForGlobal(*GV);
733 if (Known == MRI_NoModRef)
734 return MRI_NoModRef; // No need to query other mod/ref analyses
735 return ModRefInfo(Known & AliasAnalysis::getModRefInfo(CS, Loc));