blob: 979e2de0fcf17178a4d6c5a171ceef2c2f9c81da [file] [log] [blame]
Chris Lattner26dff502004-06-28 06:33:13 +00001//===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
Chris Lattner26dff502004-06-28 06:33:13 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman01808ca2005-04-21 21:13:18 +00007//
Chris Lattner26dff502004-06-28 06:33:13 +00008//===----------------------------------------------------------------------===//
9//
10// This simple pass provides alias and mod/ref information for global values
Chris Lattner3a353e82004-07-27 06:40:37 +000011// 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.
Chris Lattner26dff502004-06-28 06:33:13 +000014//
15//===----------------------------------------------------------------------===//
16
Chandler Carruth21dcff72015-08-14 03:48:20 +000017#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SCCIterator.h"
Chandler Carruthf3af4af2015-07-22 11:47:54 +000019#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/Statistic.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000021#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DerivedTypes.h"
Chandler Carruth83948572014-03-04 10:30:26 +000025#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Instructions.h"
27#include "llvm/IR/IntrinsicInst.h"
28#include "llvm/IR/Module.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Pass.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000030#include "llvm/Support/CommandLine.h"
Chris Lattner26dff502004-06-28 06:33:13 +000031using namespace llvm;
32
Chandler Carruthf1221bd2014-04-22 02:48:03 +000033#define DEBUG_TYPE "globalsmodref-aa"
34
Chris Lattner57ef9422006-12-19 22:30:33 +000035STATISTIC(NumNonAddrTakenGlobalVars,
36 "Number of global vars without address taken");
37STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
38STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
39STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
40STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
41
Chandler Carruthf55803f2015-07-17 06:58:24 +000042// An option to enable unsafe alias results from the GlobalsModRef analysis.
43// When enabled, GlobalsModRef will provide no-alias results which in extremely
44// rare cases may not be conservatively correct. In particular, in the face of
45// transforms which cause assymetry between how effective GetUnderlyingObject
46// is for two pointers, it may produce incorrect results.
47//
48// These unsafe results have been returned by GMR for many years without
49// causing significant issues in the wild and so we provide a mechanism to
50// re-enable them for users of LLVM that have a particular performance
51// sensitivity and no known issues. The option also makes it easy to evaluate
52// the performance impact of these results.
53static cl::opt<bool> EnableUnsafeGlobalsModRefAliasResults(
54 "enable-unsafe-globalsmodref-alias-results", cl::init(false), cl::Hidden);
55
Chandler Carruth5657b732015-07-22 23:56:31 +000056/// The mod/ref information collected for a particular function.
57///
58/// We collect information about mod/ref behavior of a function here, both in
59/// general and as pertains to specific globals. We only have this detailed
60/// information when we know *something* useful about the behavior. If we
61/// saturate to fully general mod/ref, we remove the info for the function.
Chandler Carruth7b560d42015-09-09 17:55:00 +000062class GlobalsAAResult::FunctionInfo {
Chandler Carruth8e4357d2015-07-23 07:50:52 +000063 typedef SmallDenseMap<const GlobalValue *, ModRefInfo, 16> GlobalInfoMapType;
64
65 /// Build a wrapper struct that has 8-byte alignment. All heap allocations
66 /// should provide this much alignment at least, but this makes it clear we
67 /// specifically rely on this amount of alignment.
68 struct LLVM_ALIGNAS(8) AlignedMap {
69 AlignedMap() {}
70 AlignedMap(const AlignedMap &Arg) : Map(Arg.Map) {}
71 GlobalInfoMapType Map;
72 };
73
74 /// Pointer traits for our aligned map.
75 struct AlignedMapPointerTraits {
76 static inline void *getAsVoidPointer(AlignedMap *P) { return P; }
77 static inline AlignedMap *getFromVoidPointer(void *P) {
78 return (AlignedMap *)P;
79 }
80 enum { NumLowBitsAvailable = 3 };
81 static_assert(AlignOf<AlignedMap>::Alignment >= (1 << NumLowBitsAvailable),
82 "AlignedMap insufficiently aligned to have enough low bits.");
83 };
84
85 /// The bit that flags that this function may read any global. This is
86 /// chosen to mix together with ModRefInfo bits.
87 enum { MayReadAnyGlobal = 4 };
88
89 /// Checks to document the invariants of the bit packing here.
90 static_assert((MayReadAnyGlobal & MRI_ModRef) == 0,
91 "ModRef and the MayReadAnyGlobal flag bits overlap.");
92 static_assert(((MayReadAnyGlobal | MRI_ModRef) >>
93 AlignedMapPointerTraits::NumLowBitsAvailable) == 0,
94 "Insufficient low bits to store our flag and ModRef info.");
95
Chandler Carruth5657b732015-07-22 23:56:31 +000096public:
Chandler Carruth8e4357d2015-07-23 07:50:52 +000097 FunctionInfo() : Info() {}
98 ~FunctionInfo() {
99 delete Info.getPointer();
100 }
101 // Spell out the copy ond move constructors and assignment operators to get
102 // deep copy semantics and correct move semantics in the face of the
103 // pointer-int pair.
104 FunctionInfo(const FunctionInfo &Arg)
105 : Info(nullptr, Arg.Info.getInt()) {
106 if (const auto *ArgPtr = Arg.Info.getPointer())
107 Info.setPointer(new AlignedMap(*ArgPtr));
108 }
109 FunctionInfo(FunctionInfo &&Arg)
110 : Info(Arg.Info.getPointer(), Arg.Info.getInt()) {
111 Arg.Info.setPointerAndInt(nullptr, 0);
112 }
113 FunctionInfo &operator=(const FunctionInfo &RHS) {
114 delete Info.getPointer();
115 Info.setPointerAndInt(nullptr, RHS.Info.getInt());
116 if (const auto *RHSPtr = RHS.Info.getPointer())
117 Info.setPointer(new AlignedMap(*RHSPtr));
118 return *this;
119 }
120 FunctionInfo &operator=(FunctionInfo &&RHS) {
121 delete Info.getPointer();
122 Info.setPointerAndInt(RHS.Info.getPointer(), RHS.Info.getInt());
123 RHS.Info.setPointerAndInt(nullptr, 0);
124 return *this;
125 }
Chris Lattner3a353e82004-07-27 06:40:37 +0000126
Chandler Carruth5657b732015-07-22 23:56:31 +0000127 /// Returns the \c ModRefInfo info for this function.
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000128 ModRefInfo getModRefInfo() const {
129 return ModRefInfo(Info.getInt() & MRI_ModRef);
130 }
Duncan Sands06dbb122008-09-12 07:29:58 +0000131
Chandler Carruth5657b732015-07-22 23:56:31 +0000132 /// Adds new \c ModRefInfo for this function to its state.
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000133 void addModRefInfo(ModRefInfo NewMRI) {
134 Info.setInt(Info.getInt() | NewMRI);
135 }
Chandler Carruth5657b732015-07-22 23:56:31 +0000136
137 /// Returns whether this function may read any global variable, and we don't
138 /// know which global.
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000139 bool mayReadAnyGlobal() const { return Info.getInt() & MayReadAnyGlobal; }
Chandler Carruth5657b732015-07-22 23:56:31 +0000140
141 /// Sets this function as potentially reading from any global.
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000142 void setMayReadAnyGlobal() { Info.setInt(Info.getInt() | MayReadAnyGlobal); }
Chandler Carruth5657b732015-07-22 23:56:31 +0000143
144 /// Returns the \c ModRefInfo info for this function w.r.t. a particular
145 /// global, which may be more precise than the general information above.
146 ModRefInfo getModRefInfoForGlobal(const GlobalValue &GV) const {
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000147 ModRefInfo GlobalMRI = mayReadAnyGlobal() ? MRI_Ref : MRI_NoModRef;
148 if (AlignedMap *P = Info.getPointer()) {
149 auto I = P->Map.find(&GV);
150 if (I != P->Map.end())
151 GlobalMRI = ModRefInfo(GlobalMRI | I->second);
152 }
Chandler Carruth5657b732015-07-22 23:56:31 +0000153 return GlobalMRI;
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000154 }
155
Chandler Carruthdbb46222015-07-23 00:12:32 +0000156 /// Add mod/ref info from another function into ours, saturating towards
157 /// MRI_ModRef.
158 void addFunctionInfo(const FunctionInfo &FI) {
159 addModRefInfo(FI.getModRefInfo());
160
161 if (FI.mayReadAnyGlobal())
162 setMayReadAnyGlobal();
163
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000164 if (AlignedMap *P = FI.Info.getPointer())
165 for (const auto &G : P->Map)
166 addModRefInfoForGlobal(*G.first, G.second);
Chandler Carruth5657b732015-07-22 23:56:31 +0000167 }
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000168
Chandler Carruth5657b732015-07-22 23:56:31 +0000169 void addModRefInfoForGlobal(const GlobalValue &GV, ModRefInfo NewMRI) {
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000170 AlignedMap *P = Info.getPointer();
171 if (!P) {
172 P = new AlignedMap();
173 Info.setPointer(P);
174 }
175 auto &GlobalMRI = P->Map[&GV];
Chandler Carruth5657b732015-07-22 23:56:31 +0000176 GlobalMRI = ModRefInfo(GlobalMRI | NewMRI);
177 }
178
Chandler Carruth786e6db2015-07-28 06:01:57 +0000179 /// Clear a global's ModRef info. Should be used when a global is being
180 /// deleted.
181 void eraseModRefInfoForGlobal(const GlobalValue &GV) {
182 if (AlignedMap *P = Info.getPointer())
183 P->Map.erase(&GV);
184 }
185
Chandler Carruth5657b732015-07-22 23:56:31 +0000186private:
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000187 /// All of the information is encoded into a single pointer, with a three bit
188 /// integer in the low three bits. The high bit provides a flag for when this
189 /// function may read any global. The low two bits are the ModRefInfo. And
190 /// the pointer, when non-null, points to a map from GlobalValue to
191 /// ModRefInfo specific to that GlobalValue.
192 PointerIntPair<AlignedMap *, 3, unsigned, AlignedMapPointerTraits> Info;
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000193};
194
Chandler Carruth7b560d42015-09-09 17:55:00 +0000195void GlobalsAAResult::DeletionCallbackHandle::deleted() {
Chandler Carruth21dcff72015-08-14 03:48:20 +0000196 Value *V = getValPtr();
197 if (auto *F = dyn_cast<Function>(V))
NAKAMURA Takumi98800d92015-09-14 06:16:44 +0000198 GAR->FunctionInfos.erase(F);
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000199
Chandler Carruth21dcff72015-08-14 03:48:20 +0000200 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
NAKAMURA Takumi98800d92015-09-14 06:16:44 +0000201 if (GAR->NonAddressTakenGlobals.erase(GV)) {
Chandler Carruth21dcff72015-08-14 03:48:20 +0000202 // This global might be an indirect global. If so, remove it and
203 // remove any AllocRelatedValues for it.
NAKAMURA Takumi98800d92015-09-14 06:16:44 +0000204 if (GAR->IndirectGlobals.erase(GV)) {
Chandler Carruth21dcff72015-08-14 03:48:20 +0000205 // Remove any entries in AllocsForIndirectGlobals for this global.
NAKAMURA Takumi98800d92015-09-14 06:16:44 +0000206 for (auto I = GAR->AllocsForIndirectGlobals.begin(),
207 E = GAR->AllocsForIndirectGlobals.end();
Chandler Carruth21dcff72015-08-14 03:48:20 +0000208 I != E; ++I)
209 if (I->second == GV)
NAKAMURA Takumi98800d92015-09-14 06:16:44 +0000210 GAR->AllocsForIndirectGlobals.erase(I);
Chandler Carruth8f1b63e2015-07-22 11:10:41 +0000211 }
212
Chandler Carruth21dcff72015-08-14 03:48:20 +0000213 // Scan the function info we have collected and remove this global
214 // from all of them.
NAKAMURA Takumi98800d92015-09-14 06:16:44 +0000215 for (auto &FIPair : GAR->FunctionInfos)
Chandler Carruth21dcff72015-08-14 03:48:20 +0000216 FIPair.second.eraseModRefInfoForGlobal(*GV);
Chandler Carruth8f1b63e2015-07-22 11:10:41 +0000217 }
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000218 }
219
Chandler Carruth21dcff72015-08-14 03:48:20 +0000220 // If this is an allocation related to an indirect global, remove it.
NAKAMURA Takumi98800d92015-09-14 06:16:44 +0000221 GAR->AllocsForIndirectGlobals.erase(V);
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000222
Chandler Carruth21dcff72015-08-14 03:48:20 +0000223 // And clear out the handle.
224 setValPtr(nullptr);
NAKAMURA Takumi98800d92015-09-14 06:16:44 +0000225 GAR->Handles.erase(I);
Chandler Carruth21dcff72015-08-14 03:48:20 +0000226 // This object is now destroyed!
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000227}
Chris Lattner26dff502004-06-28 06:33:13 +0000228
Chandler Carruth7b560d42015-09-09 17:55:00 +0000229FunctionModRefBehavior GlobalsAAResult::getModRefBehavior(const Function *F) {
Chandler Carruth21dcff72015-08-14 03:48:20 +0000230 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
231
232 if (FunctionInfo *FI = getFunctionInfo(F)) {
233 if (FI->getModRefInfo() == MRI_NoModRef)
234 Min = FMRB_DoesNotAccessMemory;
235 else if ((FI->getModRefInfo() & MRI_Mod) == 0)
236 Min = FMRB_OnlyReadsMemory;
237 }
238
Chandler Carruth7b560d42015-09-09 17:55:00 +0000239 return FunctionModRefBehavior(AAResultBase::getModRefBehavior(F) & Min);
Chandler Carruth21dcff72015-08-14 03:48:20 +0000240}
241
Chandler Carruth7b560d42015-09-09 17:55:00 +0000242FunctionModRefBehavior
243GlobalsAAResult::getModRefBehavior(ImmutableCallSite CS) {
Chandler Carruth21dcff72015-08-14 03:48:20 +0000244 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
245
246 if (const Function *F = CS.getCalledFunction())
247 if (FunctionInfo *FI = getFunctionInfo(F)) {
248 if (FI->getModRefInfo() == MRI_NoModRef)
249 Min = FMRB_DoesNotAccessMemory;
250 else if ((FI->getModRefInfo() & MRI_Mod) == 0)
251 Min = FMRB_OnlyReadsMemory;
252 }
253
Chandler Carruth7b560d42015-09-09 17:55:00 +0000254 return FunctionModRefBehavior(AAResultBase::getModRefBehavior(CS) & Min);
Chandler Carruth21dcff72015-08-14 03:48:20 +0000255}
256
257/// Returns the function info for the function, or null if we don't have
258/// anything useful to say about it.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000259GlobalsAAResult::FunctionInfo *
260GlobalsAAResult::getFunctionInfo(const Function *F) {
Chandler Carruth21dcff72015-08-14 03:48:20 +0000261 auto I = FunctionInfos.find(F);
262 if (I != FunctionInfos.end())
263 return &I->second;
264 return nullptr;
265}
266
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000267/// AnalyzeGlobals - Scan through the users of all of the internal
Duncan Sands42c644e2008-09-03 12:55:42 +0000268/// GlobalValue's in the program. If none of them have their "address taken"
Chris Lattner26dff502004-06-28 06:33:13 +0000269/// (really, their address passed to something nontrivial), record this fact,
270/// and record the functions that they are used directly in.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000271void GlobalsAAResult::AnalyzeGlobals(Module &M) {
Chandler Carruth786e6db2015-07-28 06:01:57 +0000272 SmallPtrSet<Function *, 64> TrackedFunctions;
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000273 for (Function &F : M)
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000274 if (F.hasLocalLinkage())
275 if (!AnalyzeUsesOfPointer(&F)) {
Chris Lattner3a353e82004-07-27 06:40:37 +0000276 // Remember that we are tracking this global.
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000277 NonAddressTakenGlobals.insert(&F);
Chandler Carruth786e6db2015-07-28 06:01:57 +0000278 TrackedFunctions.insert(&F);
Chandler Carruthda7c1912015-07-22 09:27:58 +0000279 Handles.emplace_front(*this, &F);
280 Handles.front().I = Handles.begin();
Chris Lattner26dff502004-06-28 06:33:13 +0000281 ++NumNonAddrTakenFunctions;
282 }
Chris Lattner26dff502004-06-28 06:33:13 +0000283
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000284 SmallPtrSet<Function *, 64> Readers, Writers;
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000285 for (GlobalVariable &GV : M.globals())
286 if (GV.hasLocalLinkage()) {
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000287 if (!AnalyzeUsesOfPointer(&GV, &Readers,
288 GV.isConstant() ? nullptr : &Writers)) {
Chris Lattner26dff502004-06-28 06:33:13 +0000289 // Remember that we are tracking this global, and the mod/ref fns
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000290 NonAddressTakenGlobals.insert(&GV);
Chandler Carruthda7c1912015-07-22 09:27:58 +0000291 Handles.emplace_front(*this, &GV);
292 Handles.front().I = Handles.begin();
Duncan Sands42c644e2008-09-03 12:55:42 +0000293
Chandler Carruth786e6db2015-07-28 06:01:57 +0000294 for (Function *Reader : Readers) {
295 if (TrackedFunctions.insert(Reader).second) {
296 Handles.emplace_front(*this, Reader);
297 Handles.front().I = Handles.begin();
298 }
Chandler Carruth5657b732015-07-22 23:56:31 +0000299 FunctionInfos[Reader].addModRefInfoForGlobal(GV, MRI_Ref);
Chandler Carruth786e6db2015-07-28 06:01:57 +0000300 }
Chris Lattner3a353e82004-07-27 06:40:37 +0000301
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000302 if (!GV.isConstant()) // No need to keep track of writers to constants
Chandler Carruth786e6db2015-07-28 06:01:57 +0000303 for (Function *Writer : Writers) {
304 if (TrackedFunctions.insert(Writer).second) {
305 Handles.emplace_front(*this, Writer);
306 Handles.front().I = Handles.begin();
307 }
Chandler Carruth5657b732015-07-22 23:56:31 +0000308 FunctionInfos[Writer].addModRefInfoForGlobal(GV, MRI_Mod);
Chandler Carruth786e6db2015-07-28 06:01:57 +0000309 }
Chris Lattner26dff502004-06-28 06:33:13 +0000310 ++NumNonAddrTakenGlobalVars;
Duncan Sands42c644e2008-09-03 12:55:42 +0000311
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000312 // If this global holds a pointer type, see if it is an indirect global.
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000313 if (GV.getType()->getElementType()->isPointerTy() &&
314 AnalyzeIndirectGlobalMemory(&GV))
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000315 ++NumIndirectGlobalVars;
Chris Lattner26dff502004-06-28 06:33:13 +0000316 }
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000317 Readers.clear();
318 Writers.clear();
Chris Lattner26dff502004-06-28 06:33:13 +0000319 }
320}
321
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000322/// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
323/// If this is used by anything complex (i.e., the address escapes), return
324/// true. Also, while we are at it, keep track of those functions that read and
325/// write to the value.
326///
327/// If OkayStoreDest is non-null, stores into this global are allowed.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000328bool GlobalsAAResult::AnalyzeUsesOfPointer(Value *V,
329 SmallPtrSetImpl<Function *> *Readers,
330 SmallPtrSetImpl<Function *> *Writers,
331 GlobalValue *OkayStoreDest) {
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000332 if (!V->getType()->isPointerTy())
333 return true;
Chris Lattner26dff502004-06-28 06:33:13 +0000334
Chandler Carruthcdf47882014-03-09 03:16:01 +0000335 for (Use &U : V->uses()) {
336 User *I = U.getUser();
337 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000338 if (Readers)
339 Readers->insert(LI->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000340 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000341 if (V == SI->getOperand(1)) {
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000342 if (Writers)
343 Writers->insert(SI->getParent()->getParent());
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000344 } else if (SI->getOperand(1) != OkayStoreDest) {
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000345 return true; // Storing the pointer
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000346 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000347 } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
348 if (AnalyzeUsesOfPointer(I, Readers, Writers))
Victor Hernandez537d8d92009-09-18 21:34:51 +0000349 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000350 } else if (Operator::getOpcode(I) == Instruction::BitCast) {
351 if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
Benjamin Kramerb8266d22014-02-10 14:17:30 +0000352 return true;
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000353 } else if (auto CS = CallSite(I)) {
Chris Lattner26dff502004-06-28 06:33:13 +0000354 // Make sure that this is just the function being called, not that it is
355 // passing into the function.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000356 if (!CS.isCallee(&U)) {
Benjamin Kramerb8266d22014-02-10 14:17:30 +0000357 // Detect calls to free.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000358 if (isFreeCall(I, &TLI)) {
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000359 if (Writers)
360 Writers->insert(CS->getParent()->getParent());
James Molloyeb466412015-09-25 15:39:29 +0000361 } else if (CS.doesNotCapture(CS.getArgumentNo(&U))) {
362 Function *ParentF = CS->getParent()->getParent();
363 // A nocapture argument may be read from or written to, but does not
364 // escape unless the call can somehow recurse.
365 //
366 // nocapture "indicates that the callee does not make any copies of
367 // the pointer that outlive itself". Therefore if we directly or
368 // indirectly recurse, we must treat the pointer as escaping.
369 if (FunctionToSCCMap[ParentF] ==
370 FunctionToSCCMap[CS.getCalledFunction()])
371 return true;
372 if (Readers)
373 Readers->insert(ParentF);
374 if (Writers)
375 Writers->insert(ParentF);
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000376 } else {
Benjamin Kramerb8266d22014-02-10 14:17:30 +0000377 return true; // Argument of an unknown call.
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000378 }
Misha Brukman01808ca2005-04-21 21:13:18 +0000379 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000380 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000381 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000382 return true; // Allow comparison against null.
Chris Lattner26dff502004-06-28 06:33:13 +0000383 } else {
384 return true;
385 }
Gabor Greif070b9a22010-07-09 15:53:42 +0000386 }
387
Chris Lattner26dff502004-06-28 06:33:13 +0000388 return false;
389}
390
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000391/// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
392/// which holds a pointer type. See if the global always points to non-aliased
393/// heap memory: that is, all initializers of the globals are allocations, and
394/// those allocations have no use other than initialization of the global.
395/// Further, all loads out of GV must directly use the memory, not store the
396/// pointer somewhere. If this is true, we consider the memory pointed to by
397/// GV to be owned by GV and can disambiguate other pointers from it.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000398bool GlobalsAAResult::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000399 // Keep track of values related to the allocation of the memory, f.e. the
400 // value produced by the malloc call and any casts.
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000401 std::vector<Value *> AllocRelatedValues;
Duncan Sands42c644e2008-09-03 12:55:42 +0000402
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000403 // Walk the user list of the global. If we find anything other than a direct
404 // load or store, bail out.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000405 for (User *U : GV->users()) {
Gabor Greifaa389f52010-07-09 16:22:36 +0000406 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000407 // The pointer loaded from the global can only be used in simple ways:
408 // we allow addressing of it and loading storing to it. We do *not* allow
409 // storing the loaded pointer somewhere else or passing to a function.
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000410 if (AnalyzeUsesOfPointer(LI))
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000411 return false; // Loaded pointer escapes.
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000412 // TODO: Could try some IP mod/ref of the loaded pointer.
Gabor Greifaa389f52010-07-09 16:22:36 +0000413 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000414 // Storing the global itself.
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000415 if (SI->getOperand(0) == GV)
416 return false;
Duncan Sands42c644e2008-09-03 12:55:42 +0000417
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000418 // If storing the null pointer, ignore it.
419 if (isa<ConstantPointerNull>(SI->getOperand(0)))
420 continue;
Duncan Sands42c644e2008-09-03 12:55:42 +0000421
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000422 // Check the value being stored.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000423 Value *Ptr = GetUnderlyingObject(SI->getOperand(0),
424 GV->getParent()->getDataLayout());
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000425
Chandler Carruth7b560d42015-09-09 17:55:00 +0000426 if (!isAllocLikeFn(Ptr, &TLI))
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000427 return false; // Too hard to analyze.
Duncan Sands42c644e2008-09-03 12:55:42 +0000428
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000429 // Analyze all uses of the allocation. If any of them are used in a
430 // non-simple way (e.g. stored to another global) bail out.
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000431 if (AnalyzeUsesOfPointer(Ptr, /*Readers*/ nullptr, /*Writers*/ nullptr,
432 GV))
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000433 return false; // Loaded pointer escapes.
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000434
435 // Remember that this allocation is related to the indirect global.
436 AllocRelatedValues.push_back(Ptr);
437 } else {
438 // Something complex, bail out.
439 return false;
440 }
441 }
Duncan Sands42c644e2008-09-03 12:55:42 +0000442
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000443 // Okay, this is an indirect global. Remember all of the allocations for
444 // this global in AllocsForIndirectGlobals.
445 while (!AllocRelatedValues.empty()) {
446 AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
Chandler Carruthda7c1912015-07-22 09:27:58 +0000447 Handles.emplace_front(*this, AllocRelatedValues.back());
448 Handles.front().I = Handles.begin();
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000449 AllocRelatedValues.pop_back();
450 }
451 IndirectGlobals.insert(GV);
Chandler Carruthda7c1912015-07-22 09:27:58 +0000452 Handles.emplace_front(*this, GV);
453 Handles.front().I = Handles.begin();
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000454 return true;
455}
456
James Molloyeb466412015-09-25 15:39:29 +0000457void GlobalsAAResult::CollectSCCMembership(CallGraph &CG) {
458 // We do a bottom-up SCC traversal of the call graph. In other words, we
459 // visit all callees before callers (leaf-first).
460 unsigned SCCID = 0;
461 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
462 const std::vector<CallGraphNode *> &SCC = *I;
463 assert(!SCC.empty() && "SCC with no functions?");
464
465 for (auto *CGN : SCC)
466 if (Function *F = CGN->getFunction())
467 FunctionToSCCMap[F] = SCCID;
468 ++SCCID;
469 }
470}
471
Chris Lattner26dff502004-06-28 06:33:13 +0000472/// AnalyzeCallGraph - At this point, we know the functions where globals are
473/// immediately stored to and read from. Propagate this information up the call
Chris Lattner3a353e82004-07-27 06:40:37 +0000474/// graph to all callers and compute the mod/ref info for all memory for each
Misha Brukman01808ca2005-04-21 21:13:18 +0000475/// function.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000476void GlobalsAAResult::AnalyzeCallGraph(CallGraph &CG, Module &M) {
Chris Lattner26dff502004-06-28 06:33:13 +0000477 // We do a bottom-up SCC traversal of the call graph. In other words, we
478 // visit all callees before callers (leaf-first).
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000479 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000480 const std::vector<CallGraphNode *> &SCC = *I;
Duncan Sands21a57992008-09-04 19:16:20 +0000481 assert(!SCC.empty() && "SCC with no functions?");
Duncan Sands42c644e2008-09-03 12:55:42 +0000482
James Molloy860507f2015-10-13 10:43:33 +0000483 if (!SCC[0]->getFunction() || SCC[0]->getFunction()->mayBeOverridden()) {
484 // Calls externally or is weak - can't say anything useful. Remove any existing
Duncan Sands21a57992008-09-04 19:16:20 +0000485 // function records (may have been created when scanning globals).
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000486 for (auto *Node : SCC)
Chandler Carruth5657b732015-07-22 23:56:31 +0000487 FunctionInfos.erase(Node->getFunction());
Duncan Sands42c644e2008-09-03 12:55:42 +0000488 continue;
Duncan Sands21a57992008-09-04 19:16:20 +0000489 }
490
Chandler Carruth5657b732015-07-22 23:56:31 +0000491 FunctionInfo &FI = FunctionInfos[SCC[0]->getFunction()];
Duncan Sands42c644e2008-09-03 12:55:42 +0000492 bool KnowNothing = false;
Chris Lattner3a353e82004-07-27 06:40:37 +0000493
Duncan Sands42c644e2008-09-03 12:55:42 +0000494 // Collect the mod/ref properties due to called functions. We only compute
495 // one mod-ref set.
496 for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
497 Function *F = SCC[i]->getFunction();
498 if (!F) {
499 KnowNothing = true;
Chris Lattner3a353e82004-07-27 06:40:37 +0000500 break;
Chris Lattner26dff502004-06-28 06:33:13 +0000501 }
Chris Lattner3a353e82004-07-27 06:40:37 +0000502
Duncan Sands42c644e2008-09-03 12:55:42 +0000503 if (F->isDeclaration()) {
504 // Try to get mod/ref behaviour from function attributes.
Duncan Sands0eca0572008-09-03 15:31:24 +0000505 if (F->doesNotAccessMemory()) {
506 // Can't do better than that!
507 } else if (F->onlyReadsMemory()) {
Chandler Carruthdbb46222015-07-23 00:12:32 +0000508 FI.addModRefInfo(MRI_Ref);
Duncan Sands06dbb122008-09-12 07:29:58 +0000509 if (!F->isIntrinsic())
Duncan Sandse30b36f2008-09-11 15:43:12 +0000510 // This function might call back into the module and read a global -
Duncan Sands06dbb122008-09-12 07:29:58 +0000511 // consider every global as possibly being read by this function.
Chandler Carruth5657b732015-07-22 23:56:31 +0000512 FI.setMayReadAnyGlobal();
Duncan Sands0eca0572008-09-03 15:31:24 +0000513 } else {
Chandler Carruthdbb46222015-07-23 00:12:32 +0000514 FI.addModRefInfo(MRI_ModRef);
Duncan Sandsd4133ac2008-09-11 19:35:55 +0000515 // Can't say anything useful unless it's an intrinsic - they don't
516 // read or write global variables of the kind considered here.
517 KnowNothing = !F->isIntrinsic();
Duncan Sands42c644e2008-09-03 12:55:42 +0000518 }
519 continue;
520 }
Misha Brukman01808ca2005-04-21 21:13:18 +0000521
Duncan Sands42c644e2008-09-03 12:55:42 +0000522 for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
Duncan Sands21a57992008-09-04 19:16:20 +0000523 CI != E && !KnowNothing; ++CI)
Duncan Sands42c644e2008-09-03 12:55:42 +0000524 if (Function *Callee = CI->second->getFunction()) {
Chandler Carruth5657b732015-07-22 23:56:31 +0000525 if (FunctionInfo *CalleeFI = getFunctionInfo(Callee)) {
Duncan Sands42c644e2008-09-03 12:55:42 +0000526 // Propagate function effect up.
Chandler Carruthdbb46222015-07-23 00:12:32 +0000527 FI.addFunctionInfo(*CalleeFI);
Duncan Sands42c644e2008-09-03 12:55:42 +0000528 } else {
529 // Can't say anything about it. However, if it is inside our SCC,
530 // then nothing needs to be done.
531 CallGraphNode *CalleeNode = CG[Callee];
532 if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end())
533 KnowNothing = true;
534 }
535 } else {
536 KnowNothing = true;
537 }
538 }
539
540 // If we can't say anything useful about this SCC, remove all SCC functions
Chandler Carruth5657b732015-07-22 23:56:31 +0000541 // from the FunctionInfos map.
Duncan Sands42c644e2008-09-03 12:55:42 +0000542 if (KnowNothing) {
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000543 for (auto *Node : SCC)
Chandler Carruth5657b732015-07-22 23:56:31 +0000544 FunctionInfos.erase(Node->getFunction());
Duncan Sandse74d7502008-09-03 16:10:55 +0000545 continue;
Duncan Sands42c644e2008-09-03 12:55:42 +0000546 }
547
548 // Scan the function bodies for explicit loads or stores.
Chandler Carruth6af95d02015-07-15 08:53:29 +0000549 for (auto *Node : SCC) {
Chandler Carruthdbb46222015-07-23 00:12:32 +0000550 if (FI.getModRefInfo() == MRI_ModRef)
Chandler Carruth6af95d02015-07-15 08:53:29 +0000551 break; // The mod/ref lattice saturates here.
Nico Rieck78199512015-08-06 19:10:45 +0000552 for (Instruction &I : instructions(Node->getFunction())) {
Chandler Carruthdbb46222015-07-23 00:12:32 +0000553 if (FI.getModRefInfo() == MRI_ModRef)
Chandler Carruth6af95d02015-07-15 08:53:29 +0000554 break; // The mod/ref lattice saturates here.
555
556 // We handle calls specially because the graph-relevant aspects are
557 // handled above.
558 if (auto CS = CallSite(&I)) {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000559 if (isAllocationFn(&I, &TLI) || isFreeCall(&I, &TLI)) {
Chandler Carruth6af95d02015-07-15 08:53:29 +0000560 // FIXME: It is completely unclear why this is necessary and not
561 // handled by the above graph code.
Chandler Carruthdbb46222015-07-23 00:12:32 +0000562 FI.addModRefInfo(MRI_ModRef);
Chandler Carruth6af95d02015-07-15 08:53:29 +0000563 } else if (Function *Callee = CS.getCalledFunction()) {
564 // The callgraph doesn't include intrinsic calls.
565 if (Callee->isIntrinsic()) {
Chandler Carruth194f59c2015-07-22 23:15:57 +0000566 FunctionModRefBehavior Behaviour =
Chandler Carruth7b560d42015-09-09 17:55:00 +0000567 AAResultBase::getModRefBehavior(Callee);
Chandler Carruthdbb46222015-07-23 00:12:32 +0000568 FI.addModRefInfo(ModRefInfo(Behaviour & MRI_ModRef));
Chandler Carruth6af95d02015-07-15 08:53:29 +0000569 }
570 }
571 continue;
Duncan Sands9ddb3142008-09-13 12:45:50 +0000572 }
Duncan Sands42c644e2008-09-03 12:55:42 +0000573
Chandler Carruth6af95d02015-07-15 08:53:29 +0000574 // All non-call instructions we use the primary predicates for whether
575 // thay read or write memory.
576 if (I.mayReadFromMemory())
Chandler Carruthdbb46222015-07-23 00:12:32 +0000577 FI.addModRefInfo(MRI_Ref);
Chandler Carruth6af95d02015-07-15 08:53:29 +0000578 if (I.mayWriteToMemory())
Chandler Carruthdbb46222015-07-23 00:12:32 +0000579 FI.addModRefInfo(MRI_Mod);
Chandler Carruth6af95d02015-07-15 08:53:29 +0000580 }
581 }
582
Chandler Carruthdbb46222015-07-23 00:12:32 +0000583 if ((FI.getModRefInfo() & MRI_Mod) == 0)
Duncan Sands42c644e2008-09-03 12:55:42 +0000584 ++NumReadMemFunctions;
Chandler Carruthdbb46222015-07-23 00:12:32 +0000585 if (FI.getModRefInfo() == MRI_NoModRef)
Duncan Sands42c644e2008-09-03 12:55:42 +0000586 ++NumNoMemFunctions;
Duncan Sands42c644e2008-09-03 12:55:42 +0000587
588 // Finally, now that we know the full effect on this SCC, clone the
589 // information to each function in the SCC.
James Molloy17379c42015-10-19 08:54:59 +0000590 // FI is a reference into FunctionInfos, so copy it now so that it doesn't
591 // get invalidated if DenseMap decides to re-hash.
592 FunctionInfo CachedFI = FI;
Duncan Sands42c644e2008-09-03 12:55:42 +0000593 for (unsigned i = 1, e = SCC.size(); i != e; ++i)
James Molloy17379c42015-10-19 08:54:59 +0000594 FunctionInfos[SCC[i]->getFunction()] = CachedFI;
Chris Lattner3a353e82004-07-27 06:40:37 +0000595 }
Chris Lattner26dff502004-06-28 06:33:13 +0000596}
597
Chandler Carruth405e4f92015-08-05 17:58:30 +0000598// There are particular cases where we can conclude no-alias between
599// a non-addr-taken global and some other underlying object. Specifically,
600// a non-addr-taken global is known to not be escaped from any function. It is
601// also incorrect for a transformation to introduce an escape of a global in
602// a way that is observable when it was not there previously. One function
603// being transformed to introduce an escape which could possibly be observed
604// (via loading from a global or the return value for example) within another
605// function is never safe. If the observation is made through non-atomic
606// operations on different threads, it is a data-race and UB. If the
607// observation is well defined, by being observed the transformation would have
608// changed program behavior by introducing the observed escape, making it an
609// invalid transform.
610//
611// This property does require that transformations which *temporarily* escape
612// a global that was not previously escaped, prior to restoring it, cannot rely
613// on the results of GMR::alias. This seems a reasonable restriction, although
614// currently there is no way to enforce it. There is also no realistic
615// optimization pass that would make this mistake. The closest example is
616// a transformation pass which does reg2mem of SSA values but stores them into
617// global variables temporarily before restoring the global variable's value.
618// This could be useful to expose "benign" races for example. However, it seems
619// reasonable to require that a pass which introduces escapes of global
620// variables in this way to either not trust AA results while the escape is
621// active, or to be forced to operate as a module pass that cannot co-exist
622// with an alias analysis such as GMR.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000623bool GlobalsAAResult::isNonEscapingGlobalNoAlias(const GlobalValue *GV,
624 const Value *V) {
Chandler Carruth405e4f92015-08-05 17:58:30 +0000625 // In order to know that the underlying object cannot alias the
626 // non-addr-taken global, we must know that it would have to be an escape.
627 // Thus if the underlying object is a function argument, a load from
628 // a global, or the return of a function, it cannot alias. We can also
629 // recurse through PHI nodes and select nodes provided all of their inputs
630 // resolve to one of these known-escaping roots.
631 SmallPtrSet<const Value *, 8> Visited;
632 SmallVector<const Value *, 8> Inputs;
633 Visited.insert(V);
634 Inputs.push_back(V);
635 int Depth = 0;
636 do {
637 const Value *Input = Inputs.pop_back_val();
638
639 if (auto *InputGV = dyn_cast<GlobalValue>(Input)) {
640 // If one input is the very global we're querying against, then we can't
641 // conclude no-alias.
642 if (InputGV == GV)
643 return false;
644
Michael Kuperstein07f31d92015-08-11 08:06:44 +0000645 // Distinct GlobalVariables never alias, unless overriden or zero-sized.
646 // FIXME: The condition can be refined, but be conservative for now.
647 auto *GVar = dyn_cast<GlobalVariable>(GV);
648 auto *InputGVar = dyn_cast<GlobalVariable>(InputGV);
649 if (GVar && InputGVar &&
650 !GVar->isDeclaration() && !InputGVar->isDeclaration() &&
651 !GVar->mayBeOverridden() && !InputGVar->mayBeOverridden()) {
652 Type *GVType = GVar->getInitializer()->getType();
653 Type *InputGVType = InputGVar->getInitializer()->getType();
654 if (GVType->isSized() && InputGVType->isSized() &&
Chandler Carruth7b560d42015-09-09 17:55:00 +0000655 (DL.getTypeAllocSize(GVType) > 0) &&
656 (DL.getTypeAllocSize(InputGVType) > 0))
Michael Kuperstein07f31d92015-08-11 08:06:44 +0000657 continue;
658 }
659
660 // Conservatively return false, even though we could be smarter
661 // (e.g. look through GlobalAliases).
Chandler Carruth405e4f92015-08-05 17:58:30 +0000662 return false;
663 }
664
665 if (isa<Argument>(Input) || isa<CallInst>(Input) ||
666 isa<InvokeInst>(Input)) {
667 // Arguments to functions or returns from functions are inherently
668 // escaping, so we can immediately classify those as not aliasing any
669 // non-addr-taken globals.
670 continue;
671 }
672 if (auto *LI = dyn_cast<LoadInst>(Input)) {
673 // A pointer loaded from a global would have been captured, and we know
674 // that the global is non-escaping, so no alias.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000675 if (isa<GlobalValue>(GetUnderlyingObject(LI->getPointerOperand(), DL)))
Chandler Carruth405e4f92015-08-05 17:58:30 +0000676 continue;
677
678 // Otherwise, a load could come from anywhere, so bail.
679 return false;
680 }
681
682 // Recurse through a limited number of selects and PHIs. This is an
683 // arbitrary depth of 4, lower numbers could be used to fix compile time
684 // issues if needed, but this is generally expected to be only be important
685 // for small depths.
686 if (++Depth > 4)
687 return false;
688 if (auto *SI = dyn_cast<SelectInst>(Input)) {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000689 const Value *LHS = GetUnderlyingObject(SI->getTrueValue(), DL);
690 const Value *RHS = GetUnderlyingObject(SI->getFalseValue(), DL);
Chandler Carruth405e4f92015-08-05 17:58:30 +0000691 if (Visited.insert(LHS).second)
692 Inputs.push_back(LHS);
693 if (Visited.insert(RHS).second)
694 Inputs.push_back(RHS);
695 continue;
696 }
697 if (auto *PN = dyn_cast<PHINode>(Input)) {
698 for (const Value *Op : PN->incoming_values()) {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000699 Op = GetUnderlyingObject(Op, DL);
Chandler Carruth405e4f92015-08-05 17:58:30 +0000700 if (Visited.insert(Op).second)
701 Inputs.push_back(Op);
702 }
703 continue;
704 }
705
Michael Kuperstein07f31d92015-08-11 08:06:44 +0000706 // FIXME: It would be good to handle other obvious no-alias cases here, but
707 // it isn't clear how to do so reasonbly without building a small version
Chandler Carruth7b560d42015-09-09 17:55:00 +0000708 // of BasicAA into this code. We could recurse into AAResultBase::alias
Michael Kuperstein07f31d92015-08-11 08:06:44 +0000709 // here but that seems likely to go poorly as we're inside the
710 // implementation of such a query. Until then, just conservatievly retun
711 // false.
Chandler Carruth405e4f92015-08-05 17:58:30 +0000712 return false;
713 } while (!Inputs.empty());
714
715 // If all the inputs to V were definitively no-alias, then V is no-alias.
716 return true;
717}
718
Chris Lattner26dff502004-06-28 06:33:13 +0000719/// alias - If one of the pointers is to a global that we are tracking, and the
720/// other is some random pointer, we know there cannot be an alias, because the
721/// address of the global isn't taken.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000722AliasResult GlobalsAAResult::alias(const MemoryLocation &LocA,
723 const MemoryLocation &LocB) {
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000724 // Get the base object these pointers point to.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000725 const Value *UV1 = GetUnderlyingObject(LocA.Ptr, DL);
726 const Value *UV2 = GetUnderlyingObject(LocB.Ptr, DL);
Duncan Sands42c644e2008-09-03 12:55:42 +0000727
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000728 // If either of the underlying values is a global, they may be non-addr-taken
729 // globals, which we can answer queries about.
Dan Gohman5442c712010-08-03 21:48:53 +0000730 const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
731 const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000732 if (GV1 || GV2) {
733 // If the global's address is taken, pretend we don't know it's a pointer to
734 // the global.
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000735 if (GV1 && !NonAddressTakenGlobals.count(GV1))
736 GV1 = nullptr;
737 if (GV2 && !NonAddressTakenGlobals.count(GV2))
738 GV2 = nullptr;
Chris Lattner26dff502004-06-28 06:33:13 +0000739
Dan Gohman4a618822010-02-10 16:03:48 +0000740 // If the two pointers are derived from two different non-addr-taken
Chandler Carruthf55803f2015-07-17 06:58:24 +0000741 // globals we know these can't alias.
742 if (GV1 && GV2 && GV1 != GV2)
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000743 return NoAlias;
Chris Lattner26dff502004-06-28 06:33:13 +0000744
Chandler Carruthf55803f2015-07-17 06:58:24 +0000745 // If one is and the other isn't, it isn't strictly safe but we can fake
746 // this result if necessary for performance. This does not appear to be
747 // a common problem in practice.
748 if (EnableUnsafeGlobalsModRefAliasResults)
749 if ((GV1 || GV2) && GV1 != GV2)
750 return NoAlias;
751
Chandler Carruth405e4f92015-08-05 17:58:30 +0000752 // Check for a special case where a non-escaping global can be used to
753 // conclude no-alias.
Chandler Carruth99ad7bb2015-07-28 11:11:11 +0000754 if ((GV1 || GV2) && GV1 != GV2) {
Chandler Carruth405e4f92015-08-05 17:58:30 +0000755 const GlobalValue *GV = GV1 ? GV1 : GV2;
Chandler Carruth99ad7bb2015-07-28 11:11:11 +0000756 const Value *UV = GV1 ? UV2 : UV1;
Chandler Carruth405e4f92015-08-05 17:58:30 +0000757 if (isNonEscapingGlobalNoAlias(GV, UV))
Chandler Carruth99ad7bb2015-07-28 11:11:11 +0000758 return NoAlias;
Chandler Carruth99ad7bb2015-07-28 11:11:11 +0000759 }
760
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000761 // Otherwise if they are both derived from the same addr-taken global, we
762 // can't know the two accesses don't overlap.
763 }
Duncan Sands42c644e2008-09-03 12:55:42 +0000764
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000765 // These pointers may be based on the memory owned by an indirect global. If
766 // so, we may be able to handle this. First check to see if the base pointer
767 // is a direct load from an indirect global.
Craig Topper353eda42014-04-24 06:44:33 +0000768 GV1 = GV2 = nullptr;
Dan Gohman5442c712010-08-03 21:48:53 +0000769 if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000770 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
771 if (IndirectGlobals.count(GV))
772 GV1 = GV;
Dan Gohman5442c712010-08-03 21:48:53 +0000773 if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
774 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000775 if (IndirectGlobals.count(GV))
776 GV2 = GV;
Duncan Sands42c644e2008-09-03 12:55:42 +0000777
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000778 // These pointers may also be from an allocation for the indirect global. If
779 // so, also handle them.
Chandler Carruth56e2c622015-07-22 11:43:24 +0000780 if (!GV1)
781 GV1 = AllocsForIndirectGlobals.lookup(UV1);
782 if (!GV2)
783 GV2 = AllocsForIndirectGlobals.lookup(UV2);
Duncan Sands42c644e2008-09-03 12:55:42 +0000784
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000785 // Now that we know whether the two pointers are related to indirect globals,
Chandler Carruthf55803f2015-07-17 06:58:24 +0000786 // use this to disambiguate the pointers. If the pointers are based on
787 // different indirect globals they cannot alias.
788 if (GV1 && GV2 && GV1 != GV2)
Chris Lattner26dff502004-06-28 06:33:13 +0000789 return NoAlias;
Duncan Sands42c644e2008-09-03 12:55:42 +0000790
Chandler Carruthf55803f2015-07-17 06:58:24 +0000791 // If one is based on an indirect global and the other isn't, it isn't
792 // strictly safe but we can fake this result if necessary for performance.
793 // This does not appear to be a common problem in practice.
794 if (EnableUnsafeGlobalsModRefAliasResults)
795 if ((GV1 || GV2) && GV1 != GV2)
796 return NoAlias;
797
Chandler Carruth7b560d42015-09-09 17:55:00 +0000798 return AAResultBase::alias(LocA, LocB);
Chris Lattner26dff502004-06-28 06:33:13 +0000799}
800
James Molloyeb466412015-09-25 15:39:29 +0000801ModRefInfo GlobalsAAResult::getModRefInfoForArgument(ImmutableCallSite CS,
802 const GlobalValue *GV) {
803 if (CS.doesNotAccessMemory())
804 return MRI_NoModRef;
805 ModRefInfo ConservativeResult = CS.onlyReadsMemory() ? MRI_Ref : MRI_ModRef;
806
807 // Iterate through all the arguments to the called function. If any argument
808 // is based on GV, return the conservative result.
809 for (auto &A : CS.args()) {
810 SmallVector<Value*, 4> Objects;
811 GetUnderlyingObjects(A, Objects, DL);
812
813 // All objects must be identified.
814 if (!std::all_of(Objects.begin(), Objects.end(), [&GV](const Value *V) {
815 return isIdentifiedObject(V);
816 }))
817 return ConservativeResult;
818
819 if (std::find(Objects.begin(), Objects.end(), GV) != Objects.end())
820 return ConservativeResult;
821 }
822
823 // We identified all objects in the argument list, and none of them were GV.
824 return MRI_NoModRef;
825}
826
Chandler Carruth7b560d42015-09-09 17:55:00 +0000827ModRefInfo GlobalsAAResult::getModRefInfo(ImmutableCallSite CS,
828 const MemoryLocation &Loc) {
Chandler Carruth194f59c2015-07-22 23:15:57 +0000829 unsigned Known = MRI_ModRef;
Chris Lattner26dff502004-06-28 06:33:13 +0000830
831 // If we are asking for mod/ref info of a direct call with a pointer to a
Chris Lattner3a353e82004-07-27 06:40:37 +0000832 // global we are tracking, return information if we have it.
Dan Gohman41f14cf2010-09-14 21:25:10 +0000833 if (const GlobalValue *GV =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000834 dyn_cast<GlobalValue>(GetUnderlyingObject(Loc.Ptr, DL)))
Rafael Espindola6de96a12009-01-15 20:18:42 +0000835 if (GV->hasLocalLinkage())
Dan Gohman5442c712010-08-03 21:48:53 +0000836 if (const Function *F = CS.getCalledFunction())
Chris Lattner3a353e82004-07-27 06:40:37 +0000837 if (NonAddressTakenGlobals.count(GV))
Chandler Carruth5657b732015-07-22 23:56:31 +0000838 if (const FunctionInfo *FI = getFunctionInfo(F))
James Molloyeb466412015-09-25 15:39:29 +0000839 Known = FI->getModRefInfoForGlobal(*GV) |
840 getModRefInfoForArgument(CS, GV);
Chris Lattner26dff502004-06-28 06:33:13 +0000841
Chandler Carruth194f59c2015-07-22 23:15:57 +0000842 if (Known == MRI_NoModRef)
843 return MRI_NoModRef; // No need to query other mod/ref analyses
Chandler Carruth7b560d42015-09-09 17:55:00 +0000844 return ModRefInfo(Known & AAResultBase::getModRefInfo(CS, Loc));
845}
846
847GlobalsAAResult::GlobalsAAResult(const DataLayout &DL,
848 const TargetLibraryInfo &TLI)
849 : AAResultBase(TLI), DL(DL) {}
850
851GlobalsAAResult::GlobalsAAResult(GlobalsAAResult &&Arg)
NAKAMURA Takumi1a296ec2015-09-10 07:16:42 +0000852 : AAResultBase(std::move(Arg)), DL(Arg.DL),
853 NonAddressTakenGlobals(std::move(Arg.NonAddressTakenGlobals)),
854 IndirectGlobals(std::move(Arg.IndirectGlobals)),
855 AllocsForIndirectGlobals(std::move(Arg.AllocsForIndirectGlobals)),
856 FunctionInfos(std::move(Arg.FunctionInfos)),
NAKAMURA Takumi98800d92015-09-14 06:16:44 +0000857 Handles(std::move(Arg.Handles)) {
858 // Update the parent for each DeletionCallbackHandle.
859 for (auto &H : Handles) {
860 assert(H.GAR == &Arg);
861 H.GAR = this;
862 }
863}
Chandler Carruth7b560d42015-09-09 17:55:00 +0000864
865/*static*/ GlobalsAAResult
866GlobalsAAResult::analyzeModule(Module &M, const TargetLibraryInfo &TLI,
867 CallGraph &CG) {
868 GlobalsAAResult Result(M.getDataLayout(), TLI);
869
James Molloyeb466412015-09-25 15:39:29 +0000870 // Discover which functions aren't recursive, to feed into AnalyzeGlobals.
871 Result.CollectSCCMembership(CG);
872
Chandler Carruth7b560d42015-09-09 17:55:00 +0000873 // Find non-addr taken globals.
874 Result.AnalyzeGlobals(M);
875
876 // Propagate on CG.
877 Result.AnalyzeCallGraph(CG, M);
878
879 return Result;
880}
881
882GlobalsAAResult GlobalsAA::run(Module &M, AnalysisManager<Module> *AM) {
883 return GlobalsAAResult::analyzeModule(M,
884 AM->getResult<TargetLibraryAnalysis>(M),
885 AM->getResult<CallGraphAnalysis>(M));
886}
887
888char GlobalsAA::PassID;
889
890char GlobalsAAWrapperPass::ID = 0;
891INITIALIZE_PASS_BEGIN(GlobalsAAWrapperPass, "globals-aa",
892 "Globals Alias Analysis", false, true)
893INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
894INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
895INITIALIZE_PASS_END(GlobalsAAWrapperPass, "globals-aa",
896 "Globals Alias Analysis", false, true)
897
898ModulePass *llvm::createGlobalsAAWrapperPass() {
899 return new GlobalsAAWrapperPass();
900}
901
902GlobalsAAWrapperPass::GlobalsAAWrapperPass() : ModulePass(ID) {
903 initializeGlobalsAAWrapperPassPass(*PassRegistry::getPassRegistry());
904}
905
906bool GlobalsAAWrapperPass::runOnModule(Module &M) {
907 Result.reset(new GlobalsAAResult(GlobalsAAResult::analyzeModule(
908 M, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
909 getAnalysis<CallGraphWrapperPass>().getCallGraph())));
910 return false;
911}
912
913bool GlobalsAAWrapperPass::doFinalization(Module &M) {
914 Result.reset();
915 return false;
916}
917
918void GlobalsAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
919 AU.setPreservesAll();
920 AU.addRequired<CallGraphWrapperPass>();
921 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chris Lattner26dff502004-06-28 06:33:13 +0000922}