xref: /llvm-project/llvm/lib/Analysis/GlobalsModRef.cpp (revision 1a9d9823c5feb6336adb6d0ad1042b81350e4e20)
1 //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This simple pass provides alias and mod/ref information for global values
10 // that do not have their address taken, and keeps track of whether functions
11 // read or write memory (are "pure").  For this simple (but very common) case,
12 // we can provide pretty accurate and useful information.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Analysis/GlobalsModRef.h"
17 #include "llvm/ADT/SCCIterator.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/CallGraph.h"
21 #include "llvm/Analysis/MemoryBuiltins.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/InstIterator.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/PassManager.h"
29 #include "llvm/InitializePasses.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/CommandLine.h"
32 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "globalsmodref-aa"
36 
37 STATISTIC(NumNonAddrTakenGlobalVars,
38           "Number of global vars without address taken");
39 STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
40 STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
41 STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
42 STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
43 
44 // An option to enable unsafe alias results from the GlobalsModRef analysis.
45 // When enabled, GlobalsModRef will provide no-alias results which in extremely
46 // rare cases may not be conservatively correct. In particular, in the face of
47 // transforms which cause asymmetry between how effective getUnderlyingObject
48 // is for two pointers, it may produce incorrect results.
49 //
50 // These unsafe results have been returned by GMR for many years without
51 // causing significant issues in the wild and so we provide a mechanism to
52 // re-enable them for users of LLVM that have a particular performance
53 // sensitivity and no known issues. The option also makes it easy to evaluate
54 // the performance impact of these results.
55 static cl::opt<bool> EnableUnsafeGlobalsModRefAliasResults(
56     "enable-unsafe-globalsmodref-alias-results", cl::init(false), cl::Hidden);
57 
58 /// The mod/ref information collected for a particular function.
59 ///
60 /// We collect information about mod/ref behavior of a function here, both in
61 /// general and as pertains to specific globals. We only have this detailed
62 /// information when we know *something* useful about the behavior. If we
63 /// saturate to fully general mod/ref, we remove the info for the function.
64 class GlobalsAAResult::FunctionInfo {
65   typedef SmallDenseMap<const GlobalValue *, ModRefInfo, 16> GlobalInfoMapType;
66 
67   /// Build a wrapper struct that has 8-byte alignment. All heap allocations
68   /// should provide this much alignment at least, but this makes it clear we
69   /// specifically rely on this amount of alignment.
70   struct alignas(8) AlignedMap {
71     AlignedMap() = default;
72     AlignedMap(const AlignedMap &Arg) = default;
73     GlobalInfoMapType Map;
74   };
75 
76   /// Pointer traits for our aligned map.
77   struct AlignedMapPointerTraits {
78     static inline void *getAsVoidPointer(AlignedMap *P) { return P; }
79     static inline AlignedMap *getFromVoidPointer(void *P) {
80       return (AlignedMap *)P;
81     }
82     static constexpr int NumLowBitsAvailable = 3;
83     static_assert(alignof(AlignedMap) >= (1 << NumLowBitsAvailable),
84                   "AlignedMap insufficiently aligned to have enough low bits.");
85   };
86 
87   /// The bit that flags that this function may read any global. This is
88   /// chosen to mix together with ModRefInfo bits.
89   /// FIXME: This assumes ModRefInfo lattice will remain 4 bits!
90   /// FunctionInfo.getModRefInfo() masks out everything except ModRef so
91   /// this remains correct.
92   enum { MayReadAnyGlobal = 4 };
93 
94   /// Checks to document the invariants of the bit packing here.
95   static_assert((MayReadAnyGlobal & static_cast<int>(ModRefInfo::ModRef)) == 0,
96                 "ModRef and the MayReadAnyGlobal flag bits overlap.");
97   static_assert(((MayReadAnyGlobal | static_cast<int>(ModRefInfo::ModRef)) >>
98                  AlignedMapPointerTraits::NumLowBitsAvailable) == 0,
99                 "Insufficient low bits to store our flag and ModRef info.");
100 
101 public:
102   FunctionInfo() = default;
103   ~FunctionInfo() {
104     delete Info.getPointer();
105   }
106   // Spell out the copy ond move constructors and assignment operators to get
107   // deep copy semantics and correct move semantics in the face of the
108   // pointer-int pair.
109   FunctionInfo(const FunctionInfo &Arg)
110       : Info(nullptr, Arg.Info.getInt()) {
111     if (const auto *ArgPtr = Arg.Info.getPointer())
112       Info.setPointer(new AlignedMap(*ArgPtr));
113   }
114   FunctionInfo(FunctionInfo &&Arg)
115       : Info(Arg.Info.getPointer(), Arg.Info.getInt()) {
116     Arg.Info.setPointerAndInt(nullptr, 0);
117   }
118   FunctionInfo &operator=(const FunctionInfo &RHS) {
119     delete Info.getPointer();
120     Info.setPointerAndInt(nullptr, RHS.Info.getInt());
121     if (const auto *RHSPtr = RHS.Info.getPointer())
122       Info.setPointer(new AlignedMap(*RHSPtr));
123     return *this;
124   }
125   FunctionInfo &operator=(FunctionInfo &&RHS) {
126     delete Info.getPointer();
127     Info.setPointerAndInt(RHS.Info.getPointer(), RHS.Info.getInt());
128     RHS.Info.setPointerAndInt(nullptr, 0);
129     return *this;
130   }
131 
132   /// This method clears MayReadAnyGlobal bit added by GlobalsAAResult to return
133   /// the corresponding ModRefInfo.
134   ModRefInfo globalClearMayReadAnyGlobal(int I) const {
135     return ModRefInfo(I & static_cast<int>(ModRefInfo::ModRef));
136   }
137 
138   /// Returns the \c ModRefInfo info for this function.
139   ModRefInfo getModRefInfo() const {
140     return globalClearMayReadAnyGlobal(Info.getInt());
141   }
142 
143   /// Adds new \c ModRefInfo for this function to its state.
144   void addModRefInfo(ModRefInfo NewMRI) {
145     Info.setInt(Info.getInt() | static_cast<int>(NewMRI));
146   }
147 
148   /// Returns whether this function may read any global variable, and we don't
149   /// know which global.
150   bool mayReadAnyGlobal() const { return Info.getInt() & MayReadAnyGlobal; }
151 
152   /// Sets this function as potentially reading from any global.
153   void setMayReadAnyGlobal() { Info.setInt(Info.getInt() | MayReadAnyGlobal); }
154 
155   /// Returns the \c ModRefInfo info for this function w.r.t. a particular
156   /// global, which may be more precise than the general information above.
157   ModRefInfo getModRefInfoForGlobal(const GlobalValue &GV) const {
158     ModRefInfo GlobalMRI =
159         mayReadAnyGlobal() ? ModRefInfo::Ref : ModRefInfo::NoModRef;
160     if (AlignedMap *P = Info.getPointer()) {
161       auto I = P->Map.find(&GV);
162       if (I != P->Map.end())
163         GlobalMRI |= I->second;
164     }
165     return GlobalMRI;
166   }
167 
168   /// Add mod/ref info from another function into ours, saturating towards
169   /// ModRef.
170   void addFunctionInfo(const FunctionInfo &FI) {
171     addModRefInfo(FI.getModRefInfo());
172 
173     if (FI.mayReadAnyGlobal())
174       setMayReadAnyGlobal();
175 
176     if (AlignedMap *P = FI.Info.getPointer())
177       for (const auto &G : P->Map)
178         addModRefInfoForGlobal(*G.first, G.second);
179   }
180 
181   void addModRefInfoForGlobal(const GlobalValue &GV, ModRefInfo NewMRI) {
182     AlignedMap *P = Info.getPointer();
183     if (!P) {
184       P = new AlignedMap();
185       Info.setPointer(P);
186     }
187     auto &GlobalMRI = P->Map[&GV];
188     GlobalMRI |= NewMRI;
189   }
190 
191   /// Clear a global's ModRef info. Should be used when a global is being
192   /// deleted.
193   void eraseModRefInfoForGlobal(const GlobalValue &GV) {
194     if (AlignedMap *P = Info.getPointer())
195       P->Map.erase(&GV);
196   }
197 
198 private:
199   /// All of the information is encoded into a single pointer, with a three bit
200   /// integer in the low three bits. The high bit provides a flag for when this
201   /// function may read any global. The low two bits are the ModRefInfo. And
202   /// the pointer, when non-null, points to a map from GlobalValue to
203   /// ModRefInfo specific to that GlobalValue.
204   PointerIntPair<AlignedMap *, 3, unsigned, AlignedMapPointerTraits> Info;
205 };
206 
207 void GlobalsAAResult::DeletionCallbackHandle::deleted() {
208   Value *V = getValPtr();
209   if (auto *F = dyn_cast<Function>(V))
210     GAR->FunctionInfos.erase(F);
211 
212   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
213     if (GAR->NonAddressTakenGlobals.erase(GV)) {
214       // This global might be an indirect global.  If so, remove it and
215       // remove any AllocRelatedValues for it.
216       if (GAR->IndirectGlobals.erase(GV)) {
217         // Remove any entries in AllocsForIndirectGlobals for this global.
218         for (auto I = GAR->AllocsForIndirectGlobals.begin(),
219                   E = GAR->AllocsForIndirectGlobals.end();
220              I != E; ++I)
221           if (I->second == GV)
222             GAR->AllocsForIndirectGlobals.erase(I);
223       }
224 
225       // Scan the function info we have collected and remove this global
226       // from all of them.
227       for (auto &FIPair : GAR->FunctionInfos)
228         FIPair.second.eraseModRefInfoForGlobal(*GV);
229     }
230   }
231 
232   // If this is an allocation related to an indirect global, remove it.
233   GAR->AllocsForIndirectGlobals.erase(V);
234 
235   // And clear out the handle.
236   setValPtr(nullptr);
237   GAR->Handles.erase(I);
238   // This object is now destroyed!
239 }
240 
241 MemoryEffects GlobalsAAResult::getModRefBehavior(const Function *F) {
242   if (FunctionInfo *FI = getFunctionInfo(F))
243     return MemoryEffects(FI->getModRefInfo());
244 
245   return AAResultBase::getModRefBehavior(F);
246 }
247 
248 /// Returns the function info for the function, or null if we don't have
249 /// anything useful to say about it.
250 GlobalsAAResult::FunctionInfo *
251 GlobalsAAResult::getFunctionInfo(const Function *F) {
252   auto I = FunctionInfos.find(F);
253   if (I != FunctionInfos.end())
254     return &I->second;
255   return nullptr;
256 }
257 
258 /// AnalyzeGlobals - Scan through the users of all of the internal
259 /// GlobalValue's in the program.  If none of them have their "address taken"
260 /// (really, their address passed to something nontrivial), record this fact,
261 /// and record the functions that they are used directly in.
262 void GlobalsAAResult::AnalyzeGlobals(Module &M) {
263   SmallPtrSet<Function *, 32> TrackedFunctions;
264   for (Function &F : M)
265     if (F.hasLocalLinkage()) {
266       if (!AnalyzeUsesOfPointer(&F)) {
267         // Remember that we are tracking this global.
268         NonAddressTakenGlobals.insert(&F);
269         TrackedFunctions.insert(&F);
270         Handles.emplace_front(*this, &F);
271         Handles.front().I = Handles.begin();
272         ++NumNonAddrTakenFunctions;
273       } else
274         UnknownFunctionsWithLocalLinkage = true;
275     }
276 
277   SmallPtrSet<Function *, 16> Readers, Writers;
278   for (GlobalVariable &GV : M.globals())
279     if (GV.hasLocalLinkage()) {
280       if (!AnalyzeUsesOfPointer(&GV, &Readers,
281                                 GV.isConstant() ? nullptr : &Writers)) {
282         // Remember that we are tracking this global, and the mod/ref fns
283         NonAddressTakenGlobals.insert(&GV);
284         Handles.emplace_front(*this, &GV);
285         Handles.front().I = Handles.begin();
286 
287         for (Function *Reader : Readers) {
288           if (TrackedFunctions.insert(Reader).second) {
289             Handles.emplace_front(*this, Reader);
290             Handles.front().I = Handles.begin();
291           }
292           FunctionInfos[Reader].addModRefInfoForGlobal(GV, ModRefInfo::Ref);
293         }
294 
295         if (!GV.isConstant()) // No need to keep track of writers to constants
296           for (Function *Writer : Writers) {
297             if (TrackedFunctions.insert(Writer).second) {
298               Handles.emplace_front(*this, Writer);
299               Handles.front().I = Handles.begin();
300             }
301             FunctionInfos[Writer].addModRefInfoForGlobal(GV, ModRefInfo::Mod);
302           }
303         ++NumNonAddrTakenGlobalVars;
304 
305         // If this global holds a pointer type, see if it is an indirect global.
306         if (GV.getValueType()->isPointerTy() &&
307             AnalyzeIndirectGlobalMemory(&GV))
308           ++NumIndirectGlobalVars;
309       }
310       Readers.clear();
311       Writers.clear();
312     }
313 }
314 
315 /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
316 /// If this is used by anything complex (i.e., the address escapes), return
317 /// true.  Also, while we are at it, keep track of those functions that read and
318 /// write to the value.
319 ///
320 /// If OkayStoreDest is non-null, stores into this global are allowed.
321 bool GlobalsAAResult::AnalyzeUsesOfPointer(Value *V,
322                                            SmallPtrSetImpl<Function *> *Readers,
323                                            SmallPtrSetImpl<Function *> *Writers,
324                                            GlobalValue *OkayStoreDest) {
325   if (!V->getType()->isPointerTy())
326     return true;
327 
328   for (Use &U : V->uses()) {
329     User *I = U.getUser();
330     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
331       if (Readers)
332         Readers->insert(LI->getParent()->getParent());
333     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
334       if (V == SI->getOperand(1)) {
335         if (Writers)
336           Writers->insert(SI->getParent()->getParent());
337       } else if (SI->getOperand(1) != OkayStoreDest) {
338         return true; // Storing the pointer
339       }
340     } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
341       if (AnalyzeUsesOfPointer(I, Readers, Writers))
342         return true;
343     } else if (Operator::getOpcode(I) == Instruction::BitCast ||
344                Operator::getOpcode(I) == Instruction::AddrSpaceCast) {
345       if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
346         return true;
347     } else if (auto *Call = dyn_cast<CallBase>(I)) {
348       // Make sure that this is just the function being called, not that it is
349       // passing into the function.
350       if (Call->isDataOperand(&U)) {
351         // Detect calls to free.
352         if (Call->isArgOperand(&U) &&
353             getFreedOperand(Call, &GetTLI(*Call->getFunction())) == U) {
354           if (Writers)
355             Writers->insert(Call->getParent()->getParent());
356         } else {
357           return true; // Argument of an unknown call.
358         }
359       }
360     } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
361       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
362         return true; // Allow comparison against null.
363     } else if (Constant *C = dyn_cast<Constant>(I)) {
364       // Ignore constants which don't have any live uses.
365       if (isa<GlobalValue>(C) || C->isConstantUsed())
366         return true;
367     } else {
368       return true;
369     }
370   }
371 
372   return false;
373 }
374 
375 /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
376 /// which holds a pointer type.  See if the global always points to non-aliased
377 /// heap memory: that is, all initializers of the globals store a value known
378 /// to be obtained via a noalias return function call which have no other use.
379 /// Further, all loads out of GV must directly use the memory, not store the
380 /// pointer somewhere.  If this is true, we consider the memory pointed to by
381 /// GV to be owned by GV and can disambiguate other pointers from it.
382 bool GlobalsAAResult::AnalyzeIndirectGlobalMemory(GlobalVariable *GV) {
383   // Keep track of values related to the allocation of the memory, f.e. the
384   // value produced by the noalias call and any casts.
385   std::vector<Value *> AllocRelatedValues;
386 
387   // If the initializer is a valid pointer, bail.
388   if (Constant *C = GV->getInitializer())
389     if (!C->isNullValue())
390       return false;
391 
392   // Walk the user list of the global.  If we find anything other than a direct
393   // load or store, bail out.
394   for (User *U : GV->users()) {
395     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
396       // The pointer loaded from the global can only be used in simple ways:
397       // we allow addressing of it and loading storing to it.  We do *not* allow
398       // storing the loaded pointer somewhere else or passing to a function.
399       if (AnalyzeUsesOfPointer(LI))
400         return false; // Loaded pointer escapes.
401       // TODO: Could try some IP mod/ref of the loaded pointer.
402     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
403       // Storing the global itself.
404       if (SI->getOperand(0) == GV)
405         return false;
406 
407       // If storing the null pointer, ignore it.
408       if (isa<ConstantPointerNull>(SI->getOperand(0)))
409         continue;
410 
411       // Check the value being stored.
412       Value *Ptr = getUnderlyingObject(SI->getOperand(0));
413 
414       if (!isNoAliasCall(Ptr))
415         return false; // Too hard to analyze.
416 
417       // Analyze all uses of the allocation.  If any of them are used in a
418       // non-simple way (e.g. stored to another global) bail out.
419       if (AnalyzeUsesOfPointer(Ptr, /*Readers*/ nullptr, /*Writers*/ nullptr,
420                                GV))
421         return false; // Loaded pointer escapes.
422 
423       // Remember that this allocation is related to the indirect global.
424       AllocRelatedValues.push_back(Ptr);
425     } else {
426       // Something complex, bail out.
427       return false;
428     }
429   }
430 
431   // Okay, this is an indirect global.  Remember all of the allocations for
432   // this global in AllocsForIndirectGlobals.
433   while (!AllocRelatedValues.empty()) {
434     AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
435     Handles.emplace_front(*this, AllocRelatedValues.back());
436     Handles.front().I = Handles.begin();
437     AllocRelatedValues.pop_back();
438   }
439   IndirectGlobals.insert(GV);
440   Handles.emplace_front(*this, GV);
441   Handles.front().I = Handles.begin();
442   return true;
443 }
444 
445 void GlobalsAAResult::CollectSCCMembership(CallGraph &CG) {
446   // We do a bottom-up SCC traversal of the call graph.  In other words, we
447   // visit all callees before callers (leaf-first).
448   unsigned SCCID = 0;
449   for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
450     const std::vector<CallGraphNode *> &SCC = *I;
451     assert(!SCC.empty() && "SCC with no functions?");
452 
453     for (auto *CGN : SCC)
454       if (Function *F = CGN->getFunction())
455         FunctionToSCCMap[F] = SCCID;
456     ++SCCID;
457   }
458 }
459 
460 /// AnalyzeCallGraph - At this point, we know the functions where globals are
461 /// immediately stored to and read from.  Propagate this information up the call
462 /// graph to all callers and compute the mod/ref info for all memory for each
463 /// function.
464 void GlobalsAAResult::AnalyzeCallGraph(CallGraph &CG, Module &M) {
465   // We do a bottom-up SCC traversal of the call graph.  In other words, we
466   // visit all callees before callers (leaf-first).
467   for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
468     const std::vector<CallGraphNode *> &SCC = *I;
469     assert(!SCC.empty() && "SCC with no functions?");
470 
471     Function *F = SCC[0]->getFunction();
472 
473     if (!F || !F->isDefinitionExact()) {
474       // Calls externally or not exact - can't say anything useful. Remove any
475       // existing function records (may have been created when scanning
476       // globals).
477       for (auto *Node : SCC)
478         FunctionInfos.erase(Node->getFunction());
479       continue;
480     }
481 
482     FunctionInfo &FI = FunctionInfos[F];
483     Handles.emplace_front(*this, F);
484     Handles.front().I = Handles.begin();
485     bool KnowNothing = false;
486 
487     // Intrinsics, like any other synchronizing function, can make effects
488     // of other threads visible. Without nosync we know nothing really.
489     // Similarly, if `nocallback` is missing the function, or intrinsic,
490     // can call into the module arbitrarily. If both are set the function
491     // has an effect but will not interact with accesses of internal
492     // globals inside the module. We are conservative here for optnone
493     // functions, might not be necessary.
494     auto MaySyncOrCallIntoModule = [](const Function &F) {
495       return !F.isDeclaration() || !F.hasNoSync() ||
496              !F.hasFnAttribute(Attribute::NoCallback);
497     };
498 
499     // Collect the mod/ref properties due to called functions.  We only compute
500     // one mod-ref set.
501     for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
502       if (!F) {
503         KnowNothing = true;
504         break;
505       }
506 
507       if (F->isDeclaration() || F->hasOptNone()) {
508         // Try to get mod/ref behaviour from function attributes.
509         if (F->doesNotAccessMemory()) {
510           // Can't do better than that!
511         } else if (F->onlyReadsMemory()) {
512           FI.addModRefInfo(ModRefInfo::Ref);
513           if (!F->onlyAccessesArgMemory() && MaySyncOrCallIntoModule(*F))
514             // This function might call back into the module and read a global -
515             // consider every global as possibly being read by this function.
516             FI.setMayReadAnyGlobal();
517         } else {
518           FI.addModRefInfo(ModRefInfo::ModRef);
519           if (!F->onlyAccessesArgMemory())
520             FI.setMayReadAnyGlobal();
521           if (MaySyncOrCallIntoModule(*F)) {
522             KnowNothing = true;
523             break;
524           }
525         }
526         continue;
527       }
528 
529       for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
530            CI != E && !KnowNothing; ++CI)
531         if (Function *Callee = CI->second->getFunction()) {
532           if (FunctionInfo *CalleeFI = getFunctionInfo(Callee)) {
533             // Propagate function effect up.
534             FI.addFunctionInfo(*CalleeFI);
535           } else {
536             // Can't say anything about it.  However, if it is inside our SCC,
537             // then nothing needs to be done.
538             CallGraphNode *CalleeNode = CG[Callee];
539             if (!is_contained(SCC, CalleeNode))
540               KnowNothing = true;
541           }
542         } else {
543           KnowNothing = true;
544         }
545     }
546 
547     // If we can't say anything useful about this SCC, remove all SCC functions
548     // from the FunctionInfos map.
549     if (KnowNothing) {
550       for (auto *Node : SCC)
551         FunctionInfos.erase(Node->getFunction());
552       continue;
553     }
554 
555     // Scan the function bodies for explicit loads or stores.
556     for (auto *Node : SCC) {
557       if (isModAndRefSet(FI.getModRefInfo()))
558         break; // The mod/ref lattice saturates here.
559 
560       // Don't prove any properties based on the implementation of an optnone
561       // function. Function attributes were already used as a best approximation
562       // above.
563       if (Node->getFunction()->hasOptNone())
564         continue;
565 
566       for (Instruction &I : instructions(Node->getFunction())) {
567         if (isModAndRefSet(FI.getModRefInfo()))
568           break; // The mod/ref lattice saturates here.
569 
570         // We handle calls specially because the graph-relevant aspects are
571         // handled above.
572         if (auto *Call = dyn_cast<CallBase>(&I)) {
573           if (Function *Callee = Call->getCalledFunction()) {
574             // The callgraph doesn't include intrinsic calls.
575             if (Callee->isIntrinsic()) {
576               if (isa<DbgInfoIntrinsic>(Call))
577                 // Don't let dbg intrinsics affect alias info.
578                 continue;
579 
580               MemoryEffects Behaviour = AAResultBase::getModRefBehavior(Callee);
581               FI.addModRefInfo(Behaviour.getModRef());
582             }
583           }
584           continue;
585         }
586 
587         // All non-call instructions we use the primary predicates for whether
588         // they read or write memory.
589         if (I.mayReadFromMemory())
590           FI.addModRefInfo(ModRefInfo::Ref);
591         if (I.mayWriteToMemory())
592           FI.addModRefInfo(ModRefInfo::Mod);
593       }
594     }
595 
596     if (!isModSet(FI.getModRefInfo()))
597       ++NumReadMemFunctions;
598     if (!isModOrRefSet(FI.getModRefInfo()))
599       ++NumNoMemFunctions;
600 
601     // Finally, now that we know the full effect on this SCC, clone the
602     // information to each function in the SCC.
603     // FI is a reference into FunctionInfos, so copy it now so that it doesn't
604     // get invalidated if DenseMap decides to re-hash.
605     FunctionInfo CachedFI = FI;
606     for (unsigned i = 1, e = SCC.size(); i != e; ++i)
607       FunctionInfos[SCC[i]->getFunction()] = CachedFI;
608   }
609 }
610 
611 // GV is a non-escaping global. V is a pointer address that has been loaded from.
612 // If we can prove that V must escape, we can conclude that a load from V cannot
613 // alias GV.
614 static bool isNonEscapingGlobalNoAliasWithLoad(const GlobalValue *GV,
615                                                const Value *V,
616                                                int &Depth,
617                                                const DataLayout &DL) {
618   SmallPtrSet<const Value *, 8> Visited;
619   SmallVector<const Value *, 8> Inputs;
620   Visited.insert(V);
621   Inputs.push_back(V);
622   do {
623     const Value *Input = Inputs.pop_back_val();
624 
625     if (isa<GlobalValue>(Input) || isa<Argument>(Input) || isa<CallInst>(Input) ||
626         isa<InvokeInst>(Input))
627       // Arguments to functions or returns from functions are inherently
628       // escaping, so we can immediately classify those as not aliasing any
629       // non-addr-taken globals.
630       //
631       // (Transitive) loads from a global are also safe - if this aliased
632       // another global, its address would escape, so no alias.
633       continue;
634 
635     // Recurse through a limited number of selects, loads and PHIs. This is an
636     // arbitrary depth of 4, lower numbers could be used to fix compile time
637     // issues if needed, but this is generally expected to be only be important
638     // for small depths.
639     if (++Depth > 4)
640       return false;
641 
642     if (auto *LI = dyn_cast<LoadInst>(Input)) {
643       Inputs.push_back(getUnderlyingObject(LI->getPointerOperand()));
644       continue;
645     }
646     if (auto *SI = dyn_cast<SelectInst>(Input)) {
647       const Value *LHS = getUnderlyingObject(SI->getTrueValue());
648       const Value *RHS = getUnderlyingObject(SI->getFalseValue());
649       if (Visited.insert(LHS).second)
650         Inputs.push_back(LHS);
651       if (Visited.insert(RHS).second)
652         Inputs.push_back(RHS);
653       continue;
654     }
655     if (auto *PN = dyn_cast<PHINode>(Input)) {
656       for (const Value *Op : PN->incoming_values()) {
657         Op = getUnderlyingObject(Op);
658         if (Visited.insert(Op).second)
659           Inputs.push_back(Op);
660       }
661       continue;
662     }
663 
664     return false;
665   } while (!Inputs.empty());
666 
667   // All inputs were known to be no-alias.
668   return true;
669 }
670 
671 // There are particular cases where we can conclude no-alias between
672 // a non-addr-taken global and some other underlying object. Specifically,
673 // a non-addr-taken global is known to not be escaped from any function. It is
674 // also incorrect for a transformation to introduce an escape of a global in
675 // a way that is observable when it was not there previously. One function
676 // being transformed to introduce an escape which could possibly be observed
677 // (via loading from a global or the return value for example) within another
678 // function is never safe. If the observation is made through non-atomic
679 // operations on different threads, it is a data-race and UB. If the
680 // observation is well defined, by being observed the transformation would have
681 // changed program behavior by introducing the observed escape, making it an
682 // invalid transform.
683 //
684 // This property does require that transformations which *temporarily* escape
685 // a global that was not previously escaped, prior to restoring it, cannot rely
686 // on the results of GMR::alias. This seems a reasonable restriction, although
687 // currently there is no way to enforce it. There is also no realistic
688 // optimization pass that would make this mistake. The closest example is
689 // a transformation pass which does reg2mem of SSA values but stores them into
690 // global variables temporarily before restoring the global variable's value.
691 // This could be useful to expose "benign" races for example. However, it seems
692 // reasonable to require that a pass which introduces escapes of global
693 // variables in this way to either not trust AA results while the escape is
694 // active, or to be forced to operate as a module pass that cannot co-exist
695 // with an alias analysis such as GMR.
696 bool GlobalsAAResult::isNonEscapingGlobalNoAlias(const GlobalValue *GV,
697                                                  const Value *V) {
698   // In order to know that the underlying object cannot alias the
699   // non-addr-taken global, we must know that it would have to be an escape.
700   // Thus if the underlying object is a function argument, a load from
701   // a global, or the return of a function, it cannot alias. We can also
702   // recurse through PHI nodes and select nodes provided all of their inputs
703   // resolve to one of these known-escaping roots.
704   SmallPtrSet<const Value *, 8> Visited;
705   SmallVector<const Value *, 8> Inputs;
706   Visited.insert(V);
707   Inputs.push_back(V);
708   int Depth = 0;
709   do {
710     const Value *Input = Inputs.pop_back_val();
711 
712     if (auto *InputGV = dyn_cast<GlobalValue>(Input)) {
713       // If one input is the very global we're querying against, then we can't
714       // conclude no-alias.
715       if (InputGV == GV)
716         return false;
717 
718       // Distinct GlobalVariables never alias, unless overriden or zero-sized.
719       // FIXME: The condition can be refined, but be conservative for now.
720       auto *GVar = dyn_cast<GlobalVariable>(GV);
721       auto *InputGVar = dyn_cast<GlobalVariable>(InputGV);
722       if (GVar && InputGVar &&
723           !GVar->isDeclaration() && !InputGVar->isDeclaration() &&
724           !GVar->isInterposable() && !InputGVar->isInterposable()) {
725         Type *GVType = GVar->getInitializer()->getType();
726         Type *InputGVType = InputGVar->getInitializer()->getType();
727         if (GVType->isSized() && InputGVType->isSized() &&
728             (DL.getTypeAllocSize(GVType) > 0) &&
729             (DL.getTypeAllocSize(InputGVType) > 0))
730           continue;
731       }
732 
733       // Conservatively return false, even though we could be smarter
734       // (e.g. look through GlobalAliases).
735       return false;
736     }
737 
738     if (isa<Argument>(Input) || isa<CallInst>(Input) ||
739         isa<InvokeInst>(Input)) {
740       // Arguments to functions or returns from functions are inherently
741       // escaping, so we can immediately classify those as not aliasing any
742       // non-addr-taken globals.
743       continue;
744     }
745 
746     // Recurse through a limited number of selects, loads and PHIs. This is an
747     // arbitrary depth of 4, lower numbers could be used to fix compile time
748     // issues if needed, but this is generally expected to be only be important
749     // for small depths.
750     if (++Depth > 4)
751       return false;
752 
753     if (auto *LI = dyn_cast<LoadInst>(Input)) {
754       // A pointer loaded from a global would have been captured, and we know
755       // that the global is non-escaping, so no alias.
756       const Value *Ptr = getUnderlyingObject(LI->getPointerOperand());
757       if (isNonEscapingGlobalNoAliasWithLoad(GV, Ptr, Depth, DL))
758         // The load does not alias with GV.
759         continue;
760       // Otherwise, a load could come from anywhere, so bail.
761       return false;
762     }
763     if (auto *SI = dyn_cast<SelectInst>(Input)) {
764       const Value *LHS = getUnderlyingObject(SI->getTrueValue());
765       const Value *RHS = getUnderlyingObject(SI->getFalseValue());
766       if (Visited.insert(LHS).second)
767         Inputs.push_back(LHS);
768       if (Visited.insert(RHS).second)
769         Inputs.push_back(RHS);
770       continue;
771     }
772     if (auto *PN = dyn_cast<PHINode>(Input)) {
773       for (const Value *Op : PN->incoming_values()) {
774         Op = getUnderlyingObject(Op);
775         if (Visited.insert(Op).second)
776           Inputs.push_back(Op);
777       }
778       continue;
779     }
780 
781     // FIXME: It would be good to handle other obvious no-alias cases here, but
782     // it isn't clear how to do so reasonably without building a small version
783     // of BasicAA into this code. We could recurse into AAResultBase::alias
784     // here but that seems likely to go poorly as we're inside the
785     // implementation of such a query. Until then, just conservatively return
786     // false.
787     return false;
788   } while (!Inputs.empty());
789 
790   // If all the inputs to V were definitively no-alias, then V is no-alias.
791   return true;
792 }
793 
794 bool GlobalsAAResult::invalidate(Module &, const PreservedAnalyses &PA,
795                                  ModuleAnalysisManager::Invalidator &) {
796   // Check whether the analysis has been explicitly invalidated. Otherwise, it's
797   // stateless and remains preserved.
798   auto PAC = PA.getChecker<GlobalsAA>();
799   return !PAC.preservedWhenStateless();
800 }
801 
802 /// alias - If one of the pointers is to a global that we are tracking, and the
803 /// other is some random pointer, we know there cannot be an alias, because the
804 /// address of the global isn't taken.
805 AliasResult GlobalsAAResult::alias(const MemoryLocation &LocA,
806                                    const MemoryLocation &LocB,
807                                    AAQueryInfo &AAQI) {
808   // Get the base object these pointers point to.
809   const Value *UV1 =
810       getUnderlyingObject(LocA.Ptr->stripPointerCastsForAliasAnalysis());
811   const Value *UV2 =
812       getUnderlyingObject(LocB.Ptr->stripPointerCastsForAliasAnalysis());
813 
814   // If either of the underlying values is a global, they may be non-addr-taken
815   // globals, which we can answer queries about.
816   const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
817   const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
818   if (GV1 || GV2) {
819     // If the global's address is taken, pretend we don't know it's a pointer to
820     // the global.
821     if (GV1 && !NonAddressTakenGlobals.count(GV1))
822       GV1 = nullptr;
823     if (GV2 && !NonAddressTakenGlobals.count(GV2))
824       GV2 = nullptr;
825 
826     // If the two pointers are derived from two different non-addr-taken
827     // globals we know these can't alias.
828     if (GV1 && GV2 && GV1 != GV2)
829       return AliasResult::NoAlias;
830 
831     // If one is and the other isn't, it isn't strictly safe but we can fake
832     // this result if necessary for performance. This does not appear to be
833     // a common problem in practice.
834     if (EnableUnsafeGlobalsModRefAliasResults)
835       if ((GV1 || GV2) && GV1 != GV2)
836         return AliasResult::NoAlias;
837 
838     // Check for a special case where a non-escaping global can be used to
839     // conclude no-alias.
840     if ((GV1 || GV2) && GV1 != GV2) {
841       const GlobalValue *GV = GV1 ? GV1 : GV2;
842       const Value *UV = GV1 ? UV2 : UV1;
843       if (isNonEscapingGlobalNoAlias(GV, UV))
844         return AliasResult::NoAlias;
845     }
846 
847     // Otherwise if they are both derived from the same addr-taken global, we
848     // can't know the two accesses don't overlap.
849   }
850 
851   // These pointers may be based on the memory owned by an indirect global.  If
852   // so, we may be able to handle this.  First check to see if the base pointer
853   // is a direct load from an indirect global.
854   GV1 = GV2 = nullptr;
855   if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
856     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
857       if (IndirectGlobals.count(GV))
858         GV1 = GV;
859   if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
860     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
861       if (IndirectGlobals.count(GV))
862         GV2 = GV;
863 
864   // These pointers may also be from an allocation for the indirect global.  If
865   // so, also handle them.
866   if (!GV1)
867     GV1 = AllocsForIndirectGlobals.lookup(UV1);
868   if (!GV2)
869     GV2 = AllocsForIndirectGlobals.lookup(UV2);
870 
871   // Now that we know whether the two pointers are related to indirect globals,
872   // use this to disambiguate the pointers. If the pointers are based on
873   // different indirect globals they cannot alias.
874   if (GV1 && GV2 && GV1 != GV2)
875     return AliasResult::NoAlias;
876 
877   // If one is based on an indirect global and the other isn't, it isn't
878   // strictly safe but we can fake this result if necessary for performance.
879   // This does not appear to be a common problem in practice.
880   if (EnableUnsafeGlobalsModRefAliasResults)
881     if ((GV1 || GV2) && GV1 != GV2)
882       return AliasResult::NoAlias;
883 
884   return AAResultBase::alias(LocA, LocB, AAQI);
885 }
886 
887 ModRefInfo GlobalsAAResult::getModRefInfoForArgument(const CallBase *Call,
888                                                      const GlobalValue *GV,
889                                                      AAQueryInfo &AAQI) {
890   if (Call->doesNotAccessMemory())
891     return ModRefInfo::NoModRef;
892   ModRefInfo ConservativeResult =
893       Call->onlyReadsMemory() ? ModRefInfo::Ref : ModRefInfo::ModRef;
894 
895   // Iterate through all the arguments to the called function. If any argument
896   // is based on GV, return the conservative result.
897   for (const auto &A : Call->args()) {
898     SmallVector<const Value*, 4> Objects;
899     getUnderlyingObjects(A, Objects);
900 
901     // All objects must be identified.
902     if (!all_of(Objects, isIdentifiedObject) &&
903         // Try ::alias to see if all objects are known not to alias GV.
904         !all_of(Objects, [&](const Value *V) {
905           return this->alias(MemoryLocation::getBeforeOrAfter(V),
906                              MemoryLocation::getBeforeOrAfter(GV),
907                              AAQI) == AliasResult::NoAlias;
908         }))
909       return ConservativeResult;
910 
911     if (is_contained(Objects, GV))
912       return ConservativeResult;
913   }
914 
915   // We identified all objects in the argument list, and none of them were GV.
916   return ModRefInfo::NoModRef;
917 }
918 
919 ModRefInfo GlobalsAAResult::getModRefInfo(const CallBase *Call,
920                                           const MemoryLocation &Loc,
921                                           AAQueryInfo &AAQI) {
922   ModRefInfo Known = ModRefInfo::ModRef;
923 
924   // If we are asking for mod/ref info of a direct call with a pointer to a
925   // global we are tracking, return information if we have it.
926   if (const GlobalValue *GV =
927           dyn_cast<GlobalValue>(getUnderlyingObject(Loc.Ptr)))
928     // If GV is internal to this IR and there is no function with local linkage
929     // that has had their address taken, keep looking for a tighter ModRefInfo.
930     if (GV->hasLocalLinkage() && !UnknownFunctionsWithLocalLinkage)
931       if (const Function *F = Call->getCalledFunction())
932         if (NonAddressTakenGlobals.count(GV))
933           if (const FunctionInfo *FI = getFunctionInfo(F))
934             Known = FI->getModRefInfoForGlobal(*GV) |
935                     getModRefInfoForArgument(Call, GV, AAQI);
936 
937   return Known;
938 }
939 
940 GlobalsAAResult::GlobalsAAResult(
941     const DataLayout &DL,
942     std::function<const TargetLibraryInfo &(Function &F)> GetTLI)
943     : DL(DL), GetTLI(std::move(GetTLI)) {}
944 
945 GlobalsAAResult::GlobalsAAResult(GlobalsAAResult &&Arg)
946     : AAResultBase(std::move(Arg)), DL(Arg.DL), GetTLI(std::move(Arg.GetTLI)),
947       NonAddressTakenGlobals(std::move(Arg.NonAddressTakenGlobals)),
948       IndirectGlobals(std::move(Arg.IndirectGlobals)),
949       AllocsForIndirectGlobals(std::move(Arg.AllocsForIndirectGlobals)),
950       FunctionInfos(std::move(Arg.FunctionInfos)),
951       Handles(std::move(Arg.Handles)) {
952   // Update the parent for each DeletionCallbackHandle.
953   for (auto &H : Handles) {
954     assert(H.GAR == &Arg);
955     H.GAR = this;
956   }
957 }
958 
959 GlobalsAAResult::~GlobalsAAResult() = default;
960 
961 /*static*/ GlobalsAAResult GlobalsAAResult::analyzeModule(
962     Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
963     CallGraph &CG) {
964   GlobalsAAResult Result(M.getDataLayout(), GetTLI);
965 
966   // Discover which functions aren't recursive, to feed into AnalyzeGlobals.
967   Result.CollectSCCMembership(CG);
968 
969   // Find non-addr taken globals.
970   Result.AnalyzeGlobals(M);
971 
972   // Propagate on CG.
973   Result.AnalyzeCallGraph(CG, M);
974 
975   return Result;
976 }
977 
978 AnalysisKey GlobalsAA::Key;
979 
980 GlobalsAAResult GlobalsAA::run(Module &M, ModuleAnalysisManager &AM) {
981   FunctionAnalysisManager &FAM =
982       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
983   auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
984     return FAM.getResult<TargetLibraryAnalysis>(F);
985   };
986   return GlobalsAAResult::analyzeModule(M, GetTLI,
987                                         AM.getResult<CallGraphAnalysis>(M));
988 }
989 
990 PreservedAnalyses RecomputeGlobalsAAPass::run(Module &M,
991                                               ModuleAnalysisManager &AM) {
992   if (auto *G = AM.getCachedResult<GlobalsAA>(M)) {
993     auto &CG = AM.getResult<CallGraphAnalysis>(M);
994     G->NonAddressTakenGlobals.clear();
995     G->UnknownFunctionsWithLocalLinkage = false;
996     G->IndirectGlobals.clear();
997     G->AllocsForIndirectGlobals.clear();
998     G->FunctionInfos.clear();
999     G->FunctionToSCCMap.clear();
1000     G->Handles.clear();
1001     G->CollectSCCMembership(CG);
1002     G->AnalyzeGlobals(M);
1003     G->AnalyzeCallGraph(CG, M);
1004   }
1005   return PreservedAnalyses::all();
1006 }
1007 
1008 char GlobalsAAWrapperPass::ID = 0;
1009 INITIALIZE_PASS_BEGIN(GlobalsAAWrapperPass, "globals-aa",
1010                       "Globals Alias Analysis", false, true)
1011 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1012 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1013 INITIALIZE_PASS_END(GlobalsAAWrapperPass, "globals-aa",
1014                     "Globals Alias Analysis", false, true)
1015 
1016 ModulePass *llvm::createGlobalsAAWrapperPass() {
1017   return new GlobalsAAWrapperPass();
1018 }
1019 
1020 GlobalsAAWrapperPass::GlobalsAAWrapperPass() : ModulePass(ID) {
1021   initializeGlobalsAAWrapperPassPass(*PassRegistry::getPassRegistry());
1022 }
1023 
1024 bool GlobalsAAWrapperPass::runOnModule(Module &M) {
1025   auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
1026     return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1027   };
1028   Result.reset(new GlobalsAAResult(GlobalsAAResult::analyzeModule(
1029       M, GetTLI, getAnalysis<CallGraphWrapperPass>().getCallGraph())));
1030   return false;
1031 }
1032 
1033 bool GlobalsAAWrapperPass::doFinalization(Module &M) {
1034   Result.reset();
1035   return false;
1036 }
1037 
1038 void GlobalsAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1039   AU.setPreservesAll();
1040   AU.addRequired<CallGraphWrapperPass>();
1041   AU.addRequired<TargetLibraryInfoWrapperPass>();
1042 }
1043