8ffeecf155c8db91e2c0fa1e561a9fb8ee3047da
[oota-llvm.git] / lib / Analysis / IPA / GlobalsModRef.cpp
1 //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
15 //===----------------------------------------------------------------------===//
16
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"
33 #include <list>
34 using namespace llvm;
35
36 #define DEBUG_TYPE "globalsmodref-aa"
37
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");
44
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.
50 //
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);
58
59 namespace {
60 /// The mod/ref information collected for a particular function.
61 ///
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.
66 class FunctionInfo {
67 public:
68   FunctionInfo() : MayReadAnyGlobal(false), MRI(MRI_NoModRef) {}
69
70   /// Returns the \c ModRefInfo info for this function.
71   ModRefInfo getModRefInfo() const { return MRI; }
72
73   /// Adds new \c ModRefInfo for this function to its state.
74   void addModRefInfo(ModRefInfo NewMRI) { MRI = ModRefInfo(MRI | NewMRI); }
75
76   /// Returns whether this function may read any global variable, and we don't
77   /// know which global.
78   bool mayReadAnyGlobal() const { return MayReadAnyGlobal; }
79
80   /// Sets this function as potentially reading from any global.
81   void setMayReadAnyGlobal() { MayReadAnyGlobal = true; }
82
83   /// Returns the \c ModRefInfo info for this function w.r.t. a particular
84   /// global, which may be more precise than the general information above.
85   ModRefInfo getModRefInfoForGlobal(const GlobalValue &GV) const {
86     ModRefInfo GlobalMRI = MayReadAnyGlobal ? MRI_Ref : MRI_NoModRef;
87     auto I = GlobalInfo.find(&GV);
88     if (I != GlobalInfo.end())
89       GlobalMRI = ModRefInfo(GlobalMRI | I->second);
90     return GlobalMRI;
91   }
92
93   /// Access the entire map of mod/ref info for specific globals.
94   const std::map<const GlobalValue *, ModRefInfo> &getGlobalModRefInfo() const {
95     return GlobalInfo;
96   }
97
98   void addModRefInfoForGlobal(const GlobalValue &GV, ModRefInfo NewMRI) {
99     auto &GlobalMRI = GlobalInfo[&GV];
100     GlobalMRI = ModRefInfo(GlobalMRI | NewMRI);
101   }
102
103 private:
104   /// Maintain mod/ref info for all of the globals without addresses taken that
105   /// are read or written (transitively) by this function.
106   std::map<const GlobalValue *, ModRefInfo> GlobalInfo;
107
108   /// Flag indicating this function read global variables, but it is not known
109   /// which.
110   bool MayReadAnyGlobal;
111
112   /// Captures whether or not this function reads or writes to ANY memory. If
113   /// not, we can do a lot of aggressive analysis on it.
114   ModRefInfo MRI;
115 };
116
117 /// GlobalsModRef - The actual analysis pass.
118 class GlobalsModRef : public ModulePass, public AliasAnalysis {
119   /// The globals that do not have their addresses taken.
120   SmallPtrSet<const GlobalValue *, 8> NonAddressTakenGlobals;
121
122   /// IndirectGlobals - The memory pointed to by this global is known to be
123   /// 'owned' by the global.
124   SmallPtrSet<const GlobalValue *, 8> IndirectGlobals;
125
126   /// AllocsForIndirectGlobals - If an instruction allocates memory for an
127   /// indirect global, this map indicates which one.
128   DenseMap<const Value *, const GlobalValue *> AllocsForIndirectGlobals;
129
130   /// For each function, keep track of what globals are modified or read.
131   DenseMap<const Function *, FunctionInfo> FunctionInfos;
132
133   /// Handle to clear this analysis on deletion of values.
134   struct DeletionCallbackHandle final : CallbackVH {
135     GlobalsModRef &GMR;
136     std::list<DeletionCallbackHandle>::iterator I;
137
138     DeletionCallbackHandle(GlobalsModRef &GMR, Value *V)
139         : CallbackVH(V), GMR(GMR) {}
140
141     void deleted() override {
142       Value *V = getValPtr();
143       if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
144         if (GMR.NonAddressTakenGlobals.erase(GV)) {
145           // This global might be an indirect global.  If so, remove it and
146           // remove
147           // any AllocRelatedValues for it.
148           if (GMR.IndirectGlobals.erase(GV)) {
149             // Remove any entries in AllocsForIndirectGlobals for this global.
150             for (auto I = GMR.AllocsForIndirectGlobals.begin(),
151                       E = GMR.AllocsForIndirectGlobals.end();
152                  I != E; ++I)
153               if (I->second == GV)
154                 GMR.AllocsForIndirectGlobals.erase(I);
155           }
156         }
157       }
158
159       // If this is an allocation related to an indirect global, remove it.
160       GMR.AllocsForIndirectGlobals.erase(V);
161
162       // And clear out the handle.
163       setValPtr(nullptr);
164       GMR.Handles.erase(I);
165       // This object is now destroyed!
166     }
167   };
168
169   /// List of callbacks for globals being tracked by this analysis. Note that
170   /// these objects are quite large, but we only anticipate having one per
171   /// global tracked by this analysis. There are numerous optimizations we
172   /// could perform to the memory utilization here if this becomes a problem.
173   std::list<DeletionCallbackHandle> Handles;
174
175 public:
176   static char ID;
177   GlobalsModRef() : ModulePass(ID) {
178     initializeGlobalsModRefPass(*PassRegistry::getPassRegistry());
179   }
180
181   bool runOnModule(Module &M) override {
182     InitializeAliasAnalysis(this, &M.getDataLayout());
183
184     // Find non-addr taken globals.
185     AnalyzeGlobals(M);
186
187     // Propagate on CG.
188     AnalyzeCallGraph(getAnalysis<CallGraphWrapperPass>().getCallGraph(), M);
189     return false;
190   }
191
192   void getAnalysisUsage(AnalysisUsage &AU) const override {
193     AliasAnalysis::getAnalysisUsage(AU);
194     AU.addRequired<CallGraphWrapperPass>();
195     AU.setPreservesAll(); // Does not transform code
196   }
197
198   /// getAdjustedAnalysisPointer - This method is used when a pass implements
199   /// an analysis interface through multiple inheritance.  If needed, it
200   /// should override this to adjust the this pointer as needed for the
201   /// specified pass info.
202   void *getAdjustedAnalysisPointer(AnalysisID PI) override {
203     if (PI == &AliasAnalysis::ID)
204       return (AliasAnalysis *)this;
205     return this;
206   }
207
208   //------------------------------------------------
209   // Implement the AliasAnalysis API
210   //
211   AliasResult alias(const MemoryLocation &LocA,
212                     const MemoryLocation &LocB) override;
213   ModRefInfo getModRefInfo(ImmutableCallSite CS,
214                            const MemoryLocation &Loc) override;
215   ModRefInfo getModRefInfo(ImmutableCallSite CS1,
216                            ImmutableCallSite CS2) override {
217     return AliasAnalysis::getModRefInfo(CS1, CS2);
218   }
219
220   /// getModRefBehavior - Return the behavior of the specified function if
221   /// called from the specified call site.  The call site may be null in which
222   /// case the most generic behavior of this function should be returned.
223   FunctionModRefBehavior getModRefBehavior(const Function *F) override {
224     FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
225
226     if (FunctionInfo *FI = getFunctionInfo(F)) {
227       if (FI->getModRefInfo() == MRI_NoModRef)
228         Min = FMRB_DoesNotAccessMemory;
229       else if ((FI->getModRefInfo() & MRI_Mod) == 0)
230         Min = FMRB_OnlyReadsMemory;
231     }
232
233     return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
234   }
235
236   /// getModRefBehavior - Return the behavior of the specified function if
237   /// called from the specified call site.  The call site may be null in which
238   /// case the most generic behavior of this function should be returned.
239   FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) override {
240     FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
241
242     if (const Function *F = CS.getCalledFunction())
243       if (FunctionInfo *FI = getFunctionInfo(F)) {
244         if (FI->getModRefInfo() == MRI_NoModRef)
245           Min = FMRB_DoesNotAccessMemory;
246         else if ((FI->getModRefInfo() & MRI_Mod) == 0)
247           Min = FMRB_OnlyReadsMemory;
248       }
249
250     return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
251   }
252
253 private:
254   /// Returns the function info for the function, or null if we don't have
255   /// anything useful to say about it.
256   FunctionInfo *getFunctionInfo(const Function *F) {
257     auto I = FunctionInfos.find(F);
258     if (I != FunctionInfos.end())
259       return &I->second;
260     return nullptr;
261   }
262
263   void AnalyzeGlobals(Module &M);
264   void AnalyzeCallGraph(CallGraph &CG, Module &M);
265   bool AnalyzeUsesOfPointer(Value *V,
266                             SmallPtrSetImpl<Function *> *Readers = nullptr,
267                             SmallPtrSetImpl<Function *> *Writers = nullptr,
268                             GlobalValue *OkayStoreDest = nullptr);
269   bool AnalyzeIndirectGlobalMemory(GlobalValue *GV);
270 };
271 }
272
273 char GlobalsModRef::ID = 0;
274 INITIALIZE_AG_PASS_BEGIN(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
275                          "Simple mod/ref analysis for globals", false, true,
276                          false)
277 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
278 INITIALIZE_AG_PASS_END(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
279                        "Simple mod/ref analysis for globals", false, true,
280                        false)
281
282 Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
283
284 /// AnalyzeGlobals - Scan through the users of all of the internal
285 /// GlobalValue's in the program.  If none of them have their "address taken"
286 /// (really, their address passed to something nontrivial), record this fact,
287 /// and record the functions that they are used directly in.
288 void GlobalsModRef::AnalyzeGlobals(Module &M) {
289   for (Function &F : M)
290     if (F.hasLocalLinkage())
291       if (!AnalyzeUsesOfPointer(&F)) {
292         // Remember that we are tracking this global.
293         NonAddressTakenGlobals.insert(&F);
294         Handles.emplace_front(*this, &F);
295         Handles.front().I = Handles.begin();
296         ++NumNonAddrTakenFunctions;
297       }
298
299   SmallPtrSet<Function *, 64> Readers, Writers;
300   for (GlobalVariable &GV : M.globals())
301     if (GV.hasLocalLinkage()) {
302       if (!AnalyzeUsesOfPointer(&GV, &Readers,
303                                 GV.isConstant() ? nullptr : &Writers)) {
304         // Remember that we are tracking this global, and the mod/ref fns
305         NonAddressTakenGlobals.insert(&GV);
306         Handles.emplace_front(*this, &GV);
307         Handles.front().I = Handles.begin();
308
309         for (Function *Reader : Readers)
310           FunctionInfos[Reader].addModRefInfoForGlobal(GV, MRI_Ref);
311
312         if (!GV.isConstant()) // No need to keep track of writers to constants
313           for (Function *Writer : Writers)
314             FunctionInfos[Writer].addModRefInfoForGlobal(GV, MRI_Mod);
315         ++NumNonAddrTakenGlobalVars;
316
317         // If this global holds a pointer type, see if it is an indirect global.
318         if (GV.getType()->getElementType()->isPointerTy() &&
319             AnalyzeIndirectGlobalMemory(&GV))
320           ++NumIndirectGlobalVars;
321       }
322       Readers.clear();
323       Writers.clear();
324     }
325 }
326
327 /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
328 /// If this is used by anything complex (i.e., the address escapes), return
329 /// true.  Also, while we are at it, keep track of those functions that read and
330 /// write to the value.
331 ///
332 /// If OkayStoreDest is non-null, stores into this global are allowed.
333 bool GlobalsModRef::AnalyzeUsesOfPointer(Value *V,
334                                          SmallPtrSetImpl<Function *> *Readers,
335                                          SmallPtrSetImpl<Function *> *Writers,
336                                          GlobalValue *OkayStoreDest) {
337   if (!V->getType()->isPointerTy())
338     return true;
339
340   for (Use &U : V->uses()) {
341     User *I = U.getUser();
342     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
343       if (Readers)
344         Readers->insert(LI->getParent()->getParent());
345     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
346       if (V == SI->getOperand(1)) {
347         if (Writers)
348           Writers->insert(SI->getParent()->getParent());
349       } else if (SI->getOperand(1) != OkayStoreDest) {
350         return true; // Storing the pointer
351       }
352     } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
353       if (AnalyzeUsesOfPointer(I, Readers, Writers))
354         return true;
355     } else if (Operator::getOpcode(I) == Instruction::BitCast) {
356       if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
357         return true;
358     } else if (auto CS = CallSite(I)) {
359       // Make sure that this is just the function being called, not that it is
360       // passing into the function.
361       if (!CS.isCallee(&U)) {
362         // Detect calls to free.
363         if (isFreeCall(I, TLI)) {
364           if (Writers)
365             Writers->insert(CS->getParent()->getParent());
366         } else {
367           return true; // Argument of an unknown call.
368         }
369       }
370     } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
371       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
372         return true; // Allow comparison against null.
373     } else {
374       return true;
375     }
376   }
377
378   return false;
379 }
380
381 /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
382 /// which holds a pointer type.  See if the global always points to non-aliased
383 /// heap memory: that is, all initializers of the globals are allocations, and
384 /// those allocations have no use other than initialization of the global.
385 /// Further, all loads out of GV must directly use the memory, not store the
386 /// pointer somewhere.  If this is true, we consider the memory pointed to by
387 /// GV to be owned by GV and can disambiguate other pointers from it.
388 bool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
389   // Keep track of values related to the allocation of the memory, f.e. the
390   // value produced by the malloc call and any casts.
391   std::vector<Value *> AllocRelatedValues;
392
393   // Walk the user list of the global.  If we find anything other than a direct
394   // load or store, bail out.
395   for (User *U : GV->users()) {
396     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
397       // The pointer loaded from the global can only be used in simple ways:
398       // we allow addressing of it and loading storing to it.  We do *not* allow
399       // storing the loaded pointer somewhere else or passing to a function.
400       if (AnalyzeUsesOfPointer(LI))
401         return false; // Loaded pointer escapes.
402       // TODO: Could try some IP mod/ref of the loaded pointer.
403     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
404       // Storing the global itself.
405       if (SI->getOperand(0) == GV)
406         return false;
407
408       // If storing the null pointer, ignore it.
409       if (isa<ConstantPointerNull>(SI->getOperand(0)))
410         continue;
411
412       // Check the value being stored.
413       Value *Ptr = GetUnderlyingObject(SI->getOperand(0),
414                                        GV->getParent()->getDataLayout());
415
416       if (!isAllocLikeFn(Ptr, TLI))
417         return false; // Too hard to analyze.
418
419       // Analyze all uses of the allocation.  If any of them are used in a
420       // non-simple way (e.g. stored to another global) bail out.
421       if (AnalyzeUsesOfPointer(Ptr, /*Readers*/ nullptr, /*Writers*/ nullptr,
422                                GV))
423         return false; // Loaded pointer escapes.
424
425       // Remember that this allocation is related to the indirect global.
426       AllocRelatedValues.push_back(Ptr);
427     } else {
428       // Something complex, bail out.
429       return false;
430     }
431   }
432
433   // Okay, this is an indirect global.  Remember all of the allocations for
434   // this global in AllocsForIndirectGlobals.
435   while (!AllocRelatedValues.empty()) {
436     AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
437     Handles.emplace_front(*this, AllocRelatedValues.back());
438     Handles.front().I = Handles.begin();
439     AllocRelatedValues.pop_back();
440   }
441   IndirectGlobals.insert(GV);
442   Handles.emplace_front(*this, GV);
443   Handles.front().I = Handles.begin();
444   return true;
445 }
446
447 /// AnalyzeCallGraph - At this point, we know the functions where globals are
448 /// immediately stored to and read from.  Propagate this information up the call
449 /// graph to all callers and compute the mod/ref info for all memory for each
450 /// function.
451 void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
452   // We do a bottom-up SCC traversal of the call graph.  In other words, we
453   // visit all callees before callers (leaf-first).
454   for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
455     const std::vector<CallGraphNode *> &SCC = *I;
456     assert(!SCC.empty() && "SCC with no functions?");
457
458     if (!SCC[0]->getFunction()) {
459       // Calls externally - can't say anything useful.  Remove any existing
460       // function records (may have been created when scanning globals).
461       for (auto *Node : SCC)
462         FunctionInfos.erase(Node->getFunction());
463       continue;
464     }
465
466     FunctionInfo &FI = FunctionInfos[SCC[0]->getFunction()];
467
468     bool KnowNothing = false;
469     unsigned FunctionMRI = 0;
470
471     // Collect the mod/ref properties due to called functions.  We only compute
472     // one mod-ref set.
473     for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
474       Function *F = SCC[i]->getFunction();
475       if (!F) {
476         KnowNothing = true;
477         break;
478       }
479
480       if (F->isDeclaration()) {
481         // Try to get mod/ref behaviour from function attributes.
482         if (F->doesNotAccessMemory()) {
483           // Can't do better than that!
484         } else if (F->onlyReadsMemory()) {
485           FunctionMRI |= MRI_Ref;
486           if (!F->isIntrinsic())
487             // This function might call back into the module and read a global -
488             // consider every global as possibly being read by this function.
489             FI.setMayReadAnyGlobal();
490         } else {
491           FunctionMRI |= MRI_ModRef;
492           // Can't say anything useful unless it's an intrinsic - they don't
493           // read or write global variables of the kind considered here.
494           KnowNothing = !F->isIntrinsic();
495         }
496         continue;
497       }
498
499       for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
500            CI != E && !KnowNothing; ++CI)
501         if (Function *Callee = CI->second->getFunction()) {
502           if (FunctionInfo *CalleeFI = getFunctionInfo(Callee)) {
503             // Propagate function effect up.
504             FunctionMRI |= CalleeFI->getModRefInfo();
505
506             // Incorporate callee's effects on globals into our info.
507             for (const auto &G : CalleeFI->getGlobalModRefInfo())
508               FI.addModRefInfoForGlobal(*G.first, G.second);
509
510             if (CalleeFI->mayReadAnyGlobal())
511               FI.setMayReadAnyGlobal();
512           } else {
513             // Can't say anything about it.  However, if it is inside our SCC,
514             // then nothing needs to be done.
515             CallGraphNode *CalleeNode = CG[Callee];
516             if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end())
517               KnowNothing = true;
518           }
519         } else {
520           KnowNothing = true;
521         }
522     }
523
524     // If we can't say anything useful about this SCC, remove all SCC functions
525     // from the FunctionInfos map.
526     if (KnowNothing) {
527       for (auto *Node : SCC)
528         FunctionInfos.erase(Node->getFunction());
529       continue;
530     }
531
532     // Scan the function bodies for explicit loads or stores.
533     for (auto *Node : SCC) {
534       if (FunctionMRI == MRI_ModRef)
535         break; // The mod/ref lattice saturates here.
536       for (Instruction &I : inst_range(Node->getFunction())) {
537         if (FunctionMRI == MRI_ModRef)
538           break; // The mod/ref lattice saturates here.
539
540         // We handle calls specially because the graph-relevant aspects are
541         // handled above.
542         if (auto CS = CallSite(&I)) {
543           if (isAllocationFn(&I, TLI) || isFreeCall(&I, TLI)) {
544             // FIXME: It is completely unclear why this is necessary and not
545             // handled by the above graph code.
546             FunctionMRI |= MRI_ModRef;
547           } else if (Function *Callee = CS.getCalledFunction()) {
548             // The callgraph doesn't include intrinsic calls.
549             if (Callee->isIntrinsic()) {
550               FunctionModRefBehavior Behaviour =
551                   AliasAnalysis::getModRefBehavior(Callee);
552               FunctionMRI |= (Behaviour & MRI_ModRef);
553             }
554           }
555           continue;
556         }
557
558         // All non-call instructions we use the primary predicates for whether
559         // thay read or write memory.
560         if (I.mayReadFromMemory())
561           FunctionMRI |= MRI_Ref;
562         if (I.mayWriteToMemory())
563           FunctionMRI |= MRI_Mod;
564       }
565     }
566
567     if ((FunctionMRI & MRI_Mod) == 0)
568       ++NumReadMemFunctions;
569     if (FunctionMRI == MRI_NoModRef)
570       ++NumNoMemFunctions;
571     FI.addModRefInfo(ModRefInfo(FunctionMRI));
572
573     // Finally, now that we know the full effect on this SCC, clone the
574     // information to each function in the SCC.
575     for (unsigned i = 1, e = SCC.size(); i != e; ++i)
576       FunctionInfos[SCC[i]->getFunction()] = FI;
577   }
578 }
579
580 /// alias - If one of the pointers is to a global that we are tracking, and the
581 /// other is some random pointer, we know there cannot be an alias, because the
582 /// address of the global isn't taken.
583 AliasResult GlobalsModRef::alias(const MemoryLocation &LocA,
584                                  const MemoryLocation &LocB) {
585   // Get the base object these pointers point to.
586   const Value *UV1 = GetUnderlyingObject(LocA.Ptr, *DL);
587   const Value *UV2 = GetUnderlyingObject(LocB.Ptr, *DL);
588
589   // If either of the underlying values is a global, they may be non-addr-taken
590   // globals, which we can answer queries about.
591   const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
592   const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
593   if (GV1 || GV2) {
594     // If the global's address is taken, pretend we don't know it's a pointer to
595     // the global.
596     if (GV1 && !NonAddressTakenGlobals.count(GV1))
597       GV1 = nullptr;
598     if (GV2 && !NonAddressTakenGlobals.count(GV2))
599       GV2 = nullptr;
600
601     // If the two pointers are derived from two different non-addr-taken
602     // globals we know these can't alias.
603     if (GV1 && GV2 && GV1 != GV2)
604       return NoAlias;
605
606     // If one is and the other isn't, it isn't strictly safe but we can fake
607     // this result if necessary for performance. This does not appear to be
608     // a common problem in practice.
609     if (EnableUnsafeGlobalsModRefAliasResults)
610       if ((GV1 || GV2) && GV1 != GV2)
611         return NoAlias;
612
613     // Otherwise if they are both derived from the same addr-taken global, we
614     // can't know the two accesses don't overlap.
615   }
616
617   // These pointers may be based on the memory owned by an indirect global.  If
618   // so, we may be able to handle this.  First check to see if the base pointer
619   // is a direct load from an indirect global.
620   GV1 = GV2 = nullptr;
621   if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
622     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
623       if (IndirectGlobals.count(GV))
624         GV1 = GV;
625   if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
626     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
627       if (IndirectGlobals.count(GV))
628         GV2 = GV;
629
630   // These pointers may also be from an allocation for the indirect global.  If
631   // so, also handle them.
632   if (!GV1)
633     GV1 = AllocsForIndirectGlobals.lookup(UV1);
634   if (!GV2)
635     GV2 = AllocsForIndirectGlobals.lookup(UV2);
636
637   // Now that we know whether the two pointers are related to indirect globals,
638   // use this to disambiguate the pointers. If the pointers are based on
639   // different indirect globals they cannot alias.
640   if (GV1 && GV2 && GV1 != GV2)
641     return NoAlias;
642
643   // If one is based on an indirect global and the other isn't, it isn't
644   // strictly safe but we can fake this result if necessary for performance.
645   // This does not appear to be a common problem in practice.
646   if (EnableUnsafeGlobalsModRefAliasResults)
647     if ((GV1 || GV2) && GV1 != GV2)
648       return NoAlias;
649
650   return AliasAnalysis::alias(LocA, LocB);
651 }
652
653 ModRefInfo GlobalsModRef::getModRefInfo(ImmutableCallSite CS,
654                                         const MemoryLocation &Loc) {
655   unsigned Known = MRI_ModRef;
656
657   // If we are asking for mod/ref info of a direct call with a pointer to a
658   // global we are tracking, return information if we have it.
659   const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
660   if (const GlobalValue *GV =
661           dyn_cast<GlobalValue>(GetUnderlyingObject(Loc.Ptr, DL)))
662     if (GV->hasLocalLinkage())
663       if (const Function *F = CS.getCalledFunction())
664         if (NonAddressTakenGlobals.count(GV))
665           if (const FunctionInfo *FI = getFunctionInfo(F))
666             Known = FI->getModRefInfoForGlobal(*GV);
667
668   if (Known == MRI_NoModRef)
669     return MRI_NoModRef; // No need to query other mod/ref analyses
670   return ModRefInfo(Known & AliasAnalysis::getModRefInfo(CS, Loc));
671 }