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