2aad93133865a38239cb681a3daba8db00f31365
[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   typedef SmallDenseMap<const GlobalValue *, ModRefInfo, 16> GlobalInfoMapType;
68
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 {
73     AlignedMap() {}
74     AlignedMap(const AlignedMap &Arg) : Map(Arg.Map) {}
75     GlobalInfoMapType Map;
76   };
77
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;
83     }
84     enum { NumLowBitsAvailable = 3 };
85     static_assert(AlignOf<AlignedMap>::Alignment >= (1 << NumLowBitsAvailable),
86                   "AlignedMap insufficiently aligned to have enough low bits.");
87   };
88
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 };
92
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.");
99
100 public:
101   FunctionInfo() : Info() {}
102   ~FunctionInfo() {
103     delete Info.getPointer();
104   }
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
107   // pointer-int pair.
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));
112   }
113   FunctionInfo(FunctionInfo &&Arg)
114       : Info(Arg.Info.getPointer(), Arg.Info.getInt()) {
115     Arg.Info.setPointerAndInt(nullptr, 0);
116   }
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));
122     return *this;
123   }
124   FunctionInfo &operator=(FunctionInfo &&RHS) {
125     delete Info.getPointer();
126     Info.setPointerAndInt(RHS.Info.getPointer(), RHS.Info.getInt());
127     RHS.Info.setPointerAndInt(nullptr, 0);
128     return *this;
129   }
130
131   /// Returns the \c ModRefInfo info for this function.
132   ModRefInfo getModRefInfo() const {
133     return ModRefInfo(Info.getInt() & MRI_ModRef);
134   }
135
136   /// Adds new \c ModRefInfo for this function to its state.
137   void addModRefInfo(ModRefInfo NewMRI) {
138     Info.setInt(Info.getInt() | NewMRI);
139   }
140
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; }
144
145   /// Sets this function as potentially reading from any global.
146   void setMayReadAnyGlobal() { Info.setInt(Info.getInt() | MayReadAnyGlobal); }
147
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);
156     }
157     return GlobalMRI;
158   }
159
160   /// Add mod/ref info from another function into ours, saturating towards
161   /// MRI_ModRef.
162   void addFunctionInfo(const FunctionInfo &FI) {
163     addModRefInfo(FI.getModRefInfo());
164
165     if (FI.mayReadAnyGlobal())
166       setMayReadAnyGlobal();
167
168     if (AlignedMap *P = FI.Info.getPointer())
169       for (const auto &G : P->Map)
170         addModRefInfoForGlobal(*G.first, G.second);
171   }
172
173   void addModRefInfoForGlobal(const GlobalValue &GV, ModRefInfo NewMRI) {
174     AlignedMap *P = Info.getPointer();
175     if (!P) {
176       P = new AlignedMap();
177       Info.setPointer(P);
178     }
179     auto &GlobalMRI = P->Map[&GV];
180     GlobalMRI = ModRefInfo(GlobalMRI | NewMRI);
181   }
182
183 private:
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;
190 };
191
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;
196
197   /// IndirectGlobals - The memory pointed to by this global is known to be
198   /// 'owned' by the global.
199   SmallPtrSet<const GlobalValue *, 8> IndirectGlobals;
200
201   /// AllocsForIndirectGlobals - If an instruction allocates memory for an
202   /// indirect global, this map indicates which one.
203   DenseMap<const Value *, const GlobalValue *> AllocsForIndirectGlobals;
204
205   /// For each function, keep track of what globals are modified or read.
206   DenseMap<const Function *, FunctionInfo> FunctionInfos;
207
208   /// Handle to clear this analysis on deletion of values.
209   struct DeletionCallbackHandle final : CallbackVH {
210     GlobalsModRef &GMR;
211     std::list<DeletionCallbackHandle>::iterator I;
212
213     DeletionCallbackHandle(GlobalsModRef &GMR, Value *V)
214         : CallbackVH(V), GMR(GMR) {}
215
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
221           // remove
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();
227                  I != E; ++I)
228               if (I->second == GV)
229                 GMR.AllocsForIndirectGlobals.erase(I);
230           }
231         }
232       }
233
234       // If this is an allocation related to an indirect global, remove it.
235       GMR.AllocsForIndirectGlobals.erase(V);
236
237       // And clear out the handle.
238       setValPtr(nullptr);
239       GMR.Handles.erase(I);
240       // This object is now destroyed!
241     }
242   };
243
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;
249
250 public:
251   static char ID;
252   GlobalsModRef() : ModulePass(ID) {
253     initializeGlobalsModRefPass(*PassRegistry::getPassRegistry());
254   }
255
256   bool runOnModule(Module &M) override {
257     InitializeAliasAnalysis(this, &M.getDataLayout());
258
259     // Find non-addr taken globals.
260     AnalyzeGlobals(M);
261
262     // Propagate on CG.
263     AnalyzeCallGraph(getAnalysis<CallGraphWrapperPass>().getCallGraph(), M);
264     return false;
265   }
266
267   void getAnalysisUsage(AnalysisUsage &AU) const override {
268     AliasAnalysis::getAnalysisUsage(AU);
269     AU.addRequired<CallGraphWrapperPass>();
270     AU.setPreservesAll(); // Does not transform code
271   }
272
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;
280     return this;
281   }
282
283   //------------------------------------------------
284   // Implement the AliasAnalysis API
285   //
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);
293   }
294
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;
300
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;
306     }
307
308     return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
309   }
310
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;
316
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;
323       }
324
325     return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
326   }
327
328 private:
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())
334       return &I->second;
335     return nullptr;
336   }
337
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);
345 };
346 }
347
348 char GlobalsModRef::ID = 0;
349 INITIALIZE_AG_PASS_BEGIN(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
350                          "Simple mod/ref analysis for globals", false, true,
351                          false)
352 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
353 INITIALIZE_AG_PASS_END(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
354                        "Simple mod/ref analysis for globals", false, true,
355                        false)
356
357 Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
358
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;
372       }
373
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();
383
384         for (Function *Reader : Readers)
385           FunctionInfos[Reader].addModRefInfoForGlobal(GV, MRI_Ref);
386
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;
391
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;
396       }
397       Readers.clear();
398       Writers.clear();
399     }
400 }
401
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.
406 ///
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())
413     return true;
414
415   for (Use &U : V->uses()) {
416     User *I = U.getUser();
417     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
418       if (Readers)
419         Readers->insert(LI->getParent()->getParent());
420     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
421       if (V == SI->getOperand(1)) {
422         if (Writers)
423           Writers->insert(SI->getParent()->getParent());
424       } else if (SI->getOperand(1) != OkayStoreDest) {
425         return true; // Storing the pointer
426       }
427     } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
428       if (AnalyzeUsesOfPointer(I, Readers, Writers))
429         return true;
430     } else if (Operator::getOpcode(I) == Instruction::BitCast) {
431       if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
432         return true;
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)) {
439           if (Writers)
440             Writers->insert(CS->getParent()->getParent());
441         } else {
442           return true; // Argument of an unknown call.
443         }
444       }
445     } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
446       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
447         return true; // Allow comparison against null.
448     } else {
449       return true;
450     }
451   }
452
453   return false;
454 }
455
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;
467
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)
481         return false;
482
483       // If storing the null pointer, ignore it.
484       if (isa<ConstantPointerNull>(SI->getOperand(0)))
485         continue;
486
487       // Check the value being stored.
488       Value *Ptr = GetUnderlyingObject(SI->getOperand(0),
489                                        GV->getParent()->getDataLayout());
490
491       if (!isAllocLikeFn(Ptr, TLI))
492         return false; // Too hard to analyze.
493
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,
497                                GV))
498         return false; // Loaded pointer escapes.
499
500       // Remember that this allocation is related to the indirect global.
501       AllocRelatedValues.push_back(Ptr);
502     } else {
503       // Something complex, bail out.
504       return false;
505     }
506   }
507
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();
515   }
516   IndirectGlobals.insert(GV);
517   Handles.emplace_front(*this, GV);
518   Handles.front().I = Handles.begin();
519   return true;
520 }
521
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
525 /// function.
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?");
532
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());
538       continue;
539     }
540
541     FunctionInfo &FI = FunctionInfos[SCC[0]->getFunction()];
542     bool KnowNothing = false;
543
544     // Collect the mod/ref properties due to called functions.  We only compute
545     // one mod-ref set.
546     for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
547       Function *F = SCC[i]->getFunction();
548       if (!F) {
549         KnowNothing = true;
550         break;
551       }
552
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();
563         } else {
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();
568         }
569         continue;
570       }
571
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);
578           } else {
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())
583               KnowNothing = true;
584           }
585         } else {
586           KnowNothing = true;
587         }
588     }
589
590     // If we can't say anything useful about this SCC, remove all SCC functions
591     // from the FunctionInfos map.
592     if (KnowNothing) {
593       for (auto *Node : SCC)
594         FunctionInfos.erase(Node->getFunction());
595       continue;
596     }
597
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.
605
606         // We handle calls specially because the graph-relevant aspects are
607         // handled above.
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));
619             }
620           }
621           continue;
622         }
623
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);
630       }
631     }
632
633     if ((FI.getModRefInfo() & MRI_Mod) == 0)
634       ++NumReadMemFunctions;
635     if (FI.getModRefInfo() == MRI_NoModRef)
636       ++NumNoMemFunctions;
637
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;
642   }
643 }
644
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);
653
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);
658   if (GV1 || GV2) {
659     // If the global's address is taken, pretend we don't know it's a pointer to
660     // the global.
661     if (GV1 && !NonAddressTakenGlobals.count(GV1))
662       GV1 = nullptr;
663     if (GV2 && !NonAddressTakenGlobals.count(GV2))
664       GV2 = nullptr;
665
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)
669       return NoAlias;
670
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)
676         return NoAlias;
677
678     // Otherwise if they are both derived from the same addr-taken global, we
679     // can't know the two accesses don't overlap.
680   }
681
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.
685   GV1 = GV2 = nullptr;
686   if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
687     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
688       if (IndirectGlobals.count(GV))
689         GV1 = 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))
693         GV2 = GV;
694
695   // These pointers may also be from an allocation for the indirect global.  If
696   // so, also handle them.
697   if (!GV1)
698     GV1 = AllocsForIndirectGlobals.lookup(UV1);
699   if (!GV2)
700     GV2 = AllocsForIndirectGlobals.lookup(UV2);
701
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)
706     return NoAlias;
707
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)
713       return NoAlias;
714
715   return AliasAnalysis::alias(LocA, LocB);
716 }
717
718 ModRefInfo GlobalsModRef::getModRefInfo(ImmutableCallSite CS,
719                                         const MemoryLocation &Loc) {
720   unsigned Known = MRI_ModRef;
721
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);
732
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));
736 }