blob: 77fb41be8e2213eb668c5a7a723652661fee7492 [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
Chris Lattner26dff502004-06-28 06:33:13 +000017#include "llvm/Analysis/Passes.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"
Chris Lattner26dff502004-06-28 06:33:13 +000021#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/CallGraph.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000023#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DerivedTypes.h"
Chandler Carruth83948572014-03-04 10:30:26 +000027#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Instructions.h"
29#include "llvm/IR/IntrinsicInst.h"
30#include "llvm/IR/Module.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Pass.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/Support/CommandLine.h"
Chandler Carruthda7c1912015-07-22 09:27:58 +000033#include <list>
Chris Lattner26dff502004-06-28 06:33:13 +000034using namespace llvm;
35
Chandler Carruthf1221bd2014-04-22 02:48:03 +000036#define DEBUG_TYPE "globalsmodref-aa"
37
Chris Lattner57ef9422006-12-19 22:30:33 +000038STATISTIC(NumNonAddrTakenGlobalVars,
39 "Number of global vars without address taken");
40STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
41STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
42STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
43STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
44
Chandler Carruthf55803f2015-07-17 06:58:24 +000045// An option to enable unsafe alias results from the GlobalsModRef analysis.
46// When enabled, GlobalsModRef will provide no-alias results which in extremely
47// rare cases may not be conservatively correct. In particular, in the face of
48// transforms which cause assymetry between how effective GetUnderlyingObject
49// is for two pointers, it may produce incorrect results.
50//
51// These unsafe results have been returned by GMR for many years without
52// causing significant issues in the wild and so we provide a mechanism to
53// re-enable them for users of LLVM that have a particular performance
54// sensitivity and no known issues. The option also makes it easy to evaluate
55// the performance impact of these results.
56static cl::opt<bool> EnableUnsafeGlobalsModRefAliasResults(
57 "enable-unsafe-globalsmodref-alias-results", cl::init(false), cl::Hidden);
58
Chris Lattner26dff502004-06-28 06:33:13 +000059namespace {
Chandler Carruth5657b732015-07-22 23:56:31 +000060/// The mod/ref information collected for a particular function.
61///
62/// We collect information about mod/ref behavior of a function here, both in
63/// general and as pertains to specific globals. We only have this detailed
64/// information when we know *something* useful about the behavior. If we
65/// saturate to fully general mod/ref, we remove the info for the function.
66class FunctionInfo {
Chandler Carruth8e4357d2015-07-23 07:50:52 +000067 typedef SmallDenseMap<const GlobalValue *, ModRefInfo, 16> GlobalInfoMapType;
68
69 /// Build a wrapper struct that has 8-byte alignment. All heap allocations
70 /// should provide this much alignment at least, but this makes it clear we
71 /// specifically rely on this amount of alignment.
72 struct LLVM_ALIGNAS(8) AlignedMap {
73 AlignedMap() {}
74 AlignedMap(const AlignedMap &Arg) : Map(Arg.Map) {}
75 GlobalInfoMapType Map;
76 };
77
78 /// Pointer traits for our aligned map.
79 struct AlignedMapPointerTraits {
80 static inline void *getAsVoidPointer(AlignedMap *P) { return P; }
81 static inline AlignedMap *getFromVoidPointer(void *P) {
82 return (AlignedMap *)P;
83 }
84 enum { NumLowBitsAvailable = 3 };
85 static_assert(AlignOf<AlignedMap>::Alignment >= (1 << NumLowBitsAvailable),
86 "AlignedMap insufficiently aligned to have enough low bits.");
87 };
88
89 /// The bit that flags that this function may read any global. This is
90 /// chosen to mix together with ModRefInfo bits.
91 enum { MayReadAnyGlobal = 4 };
92
93 /// Checks to document the invariants of the bit packing here.
94 static_assert((MayReadAnyGlobal & MRI_ModRef) == 0,
95 "ModRef and the MayReadAnyGlobal flag bits overlap.");
96 static_assert(((MayReadAnyGlobal | MRI_ModRef) >>
97 AlignedMapPointerTraits::NumLowBitsAvailable) == 0,
98 "Insufficient low bits to store our flag and ModRef info.");
99
Chandler Carruth5657b732015-07-22 23:56:31 +0000100public:
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000101 FunctionInfo() : Info() {}
102 ~FunctionInfo() {
103 delete Info.getPointer();
104 }
105 // Spell out the copy ond move constructors and assignment operators to get
106 // deep copy semantics and correct move semantics in the face of the
107 // pointer-int pair.
108 FunctionInfo(const FunctionInfo &Arg)
109 : Info(nullptr, Arg.Info.getInt()) {
110 if (const auto *ArgPtr = Arg.Info.getPointer())
111 Info.setPointer(new AlignedMap(*ArgPtr));
112 }
113 FunctionInfo(FunctionInfo &&Arg)
114 : Info(Arg.Info.getPointer(), Arg.Info.getInt()) {
115 Arg.Info.setPointerAndInt(nullptr, 0);
116 }
117 FunctionInfo &operator=(const FunctionInfo &RHS) {
118 delete Info.getPointer();
119 Info.setPointerAndInt(nullptr, RHS.Info.getInt());
120 if (const auto *RHSPtr = RHS.Info.getPointer())
121 Info.setPointer(new AlignedMap(*RHSPtr));
122 return *this;
123 }
124 FunctionInfo &operator=(FunctionInfo &&RHS) {
125 delete Info.getPointer();
126 Info.setPointerAndInt(RHS.Info.getPointer(), RHS.Info.getInt());
127 RHS.Info.setPointerAndInt(nullptr, 0);
128 return *this;
129 }
Chris Lattner3a353e82004-07-27 06:40:37 +0000130
Chandler Carruth5657b732015-07-22 23:56:31 +0000131 /// Returns the \c ModRefInfo info for this function.
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000132 ModRefInfo getModRefInfo() const {
133 return ModRefInfo(Info.getInt() & MRI_ModRef);
134 }
Duncan Sands06dbb122008-09-12 07:29:58 +0000135
Chandler Carruth5657b732015-07-22 23:56:31 +0000136 /// Adds new \c ModRefInfo for this function to its state.
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000137 void addModRefInfo(ModRefInfo NewMRI) {
138 Info.setInt(Info.getInt() | NewMRI);
139 }
Chandler Carruth5657b732015-07-22 23:56:31 +0000140
141 /// Returns whether this function may read any global variable, and we don't
142 /// know which global.
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000143 bool mayReadAnyGlobal() const { return Info.getInt() & MayReadAnyGlobal; }
Chandler Carruth5657b732015-07-22 23:56:31 +0000144
145 /// Sets this function as potentially reading from any global.
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000146 void setMayReadAnyGlobal() { Info.setInt(Info.getInt() | MayReadAnyGlobal); }
Chandler Carruth5657b732015-07-22 23:56:31 +0000147
148 /// Returns the \c ModRefInfo info for this function w.r.t. a particular
149 /// global, which may be more precise than the general information above.
150 ModRefInfo getModRefInfoForGlobal(const GlobalValue &GV) const {
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000151 ModRefInfo GlobalMRI = mayReadAnyGlobal() ? MRI_Ref : MRI_NoModRef;
152 if (AlignedMap *P = Info.getPointer()) {
153 auto I = P->Map.find(&GV);
154 if (I != P->Map.end())
155 GlobalMRI = ModRefInfo(GlobalMRI | I->second);
156 }
Chandler Carruth5657b732015-07-22 23:56:31 +0000157 return GlobalMRI;
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000158 }
159
Chandler Carruthdbb46222015-07-23 00:12:32 +0000160 /// Add mod/ref info from another function into ours, saturating towards
161 /// MRI_ModRef.
162 void addFunctionInfo(const FunctionInfo &FI) {
163 addModRefInfo(FI.getModRefInfo());
164
165 if (FI.mayReadAnyGlobal())
166 setMayReadAnyGlobal();
167
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000168 if (AlignedMap *P = FI.Info.getPointer())
169 for (const auto &G : P->Map)
170 addModRefInfoForGlobal(*G.first, G.second);
Chandler Carruth5657b732015-07-22 23:56:31 +0000171 }
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000172
Chandler Carruth5657b732015-07-22 23:56:31 +0000173 void addModRefInfoForGlobal(const GlobalValue &GV, ModRefInfo NewMRI) {
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000174 AlignedMap *P = Info.getPointer();
175 if (!P) {
176 P = new AlignedMap();
177 Info.setPointer(P);
178 }
179 auto &GlobalMRI = P->Map[&GV];
Chandler Carruth5657b732015-07-22 23:56:31 +0000180 GlobalMRI = ModRefInfo(GlobalMRI | NewMRI);
181 }
182
Chandler Carruth786e6db2015-07-28 06:01:57 +0000183 /// Clear a global's ModRef info. Should be used when a global is being
184 /// deleted.
185 void eraseModRefInfoForGlobal(const GlobalValue &GV) {
186 if (AlignedMap *P = Info.getPointer())
187 P->Map.erase(&GV);
188 }
189
Chandler Carruth5657b732015-07-22 23:56:31 +0000190private:
Chandler Carruth8e4357d2015-07-23 07:50:52 +0000191 /// All of the information is encoded into a single pointer, with a three bit
192 /// integer in the low three bits. The high bit provides a flag for when this
193 /// function may read any global. The low two bits are the ModRefInfo. And
194 /// the pointer, when non-null, points to a map from GlobalValue to
195 /// ModRefInfo specific to that GlobalValue.
196 PointerIntPair<AlignedMap *, 3, unsigned, AlignedMapPointerTraits> Info;
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000197};
198
199/// GlobalsModRef - The actual analysis pass.
200class GlobalsModRef : public ModulePass, public AliasAnalysis {
Chandler Carruthda7c1912015-07-22 09:27:58 +0000201 /// The globals that do not have their addresses taken.
Chandler Carruthf3af4af2015-07-22 11:47:54 +0000202 SmallPtrSet<const GlobalValue *, 8> NonAddressTakenGlobals;
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000203
204 /// IndirectGlobals - The memory pointed to by this global is known to be
205 /// 'owned' by the global.
Chandler Carruthf3af4af2015-07-22 11:47:54 +0000206 SmallPtrSet<const GlobalValue *, 8> IndirectGlobals;
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000207
208 /// AllocsForIndirectGlobals - If an instruction allocates memory for an
209 /// indirect global, this map indicates which one.
Chandler Carruth69192672015-07-22 11:36:09 +0000210 DenseMap<const Value *, const GlobalValue *> AllocsForIndirectGlobals;
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000211
Chandler Carruth5657b732015-07-22 23:56:31 +0000212 /// For each function, keep track of what globals are modified or read.
213 DenseMap<const Function *, FunctionInfo> FunctionInfos;
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000214
Chandler Carruthda7c1912015-07-22 09:27:58 +0000215 /// Handle to clear this analysis on deletion of values.
Chandler Carruth8f1b63e2015-07-22 11:10:41 +0000216 struct DeletionCallbackHandle final : CallbackVH {
217 GlobalsModRef &GMR;
218 std::list<DeletionCallbackHandle>::iterator I;
219
220 DeletionCallbackHandle(GlobalsModRef &GMR, Value *V)
221 : CallbackVH(V), GMR(GMR) {}
222
223 void deleted() override {
224 Value *V = getValPtr();
Chandler Carruth786e6db2015-07-28 06:01:57 +0000225 if (auto *F = dyn_cast<Function>(V))
226 GMR.FunctionInfos.erase(F);
227
Chandler Carruth8f1b63e2015-07-22 11:10:41 +0000228 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
229 if (GMR.NonAddressTakenGlobals.erase(GV)) {
230 // This global might be an indirect global. If so, remove it and
Chandler Carruth786e6db2015-07-28 06:01:57 +0000231 // remove any AllocRelatedValues for it.
Chandler Carruth8f1b63e2015-07-22 11:10:41 +0000232 if (GMR.IndirectGlobals.erase(GV)) {
233 // Remove any entries in AllocsForIndirectGlobals for this global.
Chandler Carruth69192672015-07-22 11:36:09 +0000234 for (auto I = GMR.AllocsForIndirectGlobals.begin(),
235 E = GMR.AllocsForIndirectGlobals.end();
236 I != E; ++I)
237 if (I->second == GV)
238 GMR.AllocsForIndirectGlobals.erase(I);
Chandler Carruth8f1b63e2015-07-22 11:10:41 +0000239 }
Chandler Carruth786e6db2015-07-28 06:01:57 +0000240
241 // Scan the function info we have collected and remove this global
242 // from all of them.
243 for (auto &FIPair : GMR.FunctionInfos)
244 FIPair.second.eraseModRefInfoForGlobal(*GV);
Chandler Carruth8f1b63e2015-07-22 11:10:41 +0000245 }
246 }
247
248 // If this is an allocation related to an indirect global, remove it.
249 GMR.AllocsForIndirectGlobals.erase(V);
250
251 // And clear out the handle.
252 setValPtr(nullptr);
253 GMR.Handles.erase(I);
254 // This object is now destroyed!
255 }
256 };
Chandler Carruthda7c1912015-07-22 09:27:58 +0000257
258 /// List of callbacks for globals being tracked by this analysis. Note that
259 /// these objects are quite large, but we only anticipate having one per
260 /// global tracked by this analysis. There are numerous optimizations we
261 /// could perform to the memory utilization here if this becomes a problem.
262 std::list<DeletionCallbackHandle> Handles;
263
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000264public:
265 static char ID;
266 GlobalsModRef() : ModulePass(ID) {
267 initializeGlobalsModRefPass(*PassRegistry::getPassRegistry());
268 }
269
270 bool runOnModule(Module &M) override {
271 InitializeAliasAnalysis(this, &M.getDataLayout());
272
273 // Find non-addr taken globals.
274 AnalyzeGlobals(M);
275
276 // Propagate on CG.
277 AnalyzeCallGraph(getAnalysis<CallGraphWrapperPass>().getCallGraph(), M);
278 return false;
279 }
280
281 void getAnalysisUsage(AnalysisUsage &AU) const override {
282 AliasAnalysis::getAnalysisUsage(AU);
283 AU.addRequired<CallGraphWrapperPass>();
284 AU.setPreservesAll(); // Does not transform code
285 }
286
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000287 /// getAdjustedAnalysisPointer - This method is used when a pass implements
288 /// an analysis interface through multiple inheritance. If needed, it
289 /// should override this to adjust the this pointer as needed for the
290 /// specified pass info.
291 void *getAdjustedAnalysisPointer(AnalysisID PI) override {
292 if (PI == &AliasAnalysis::ID)
293 return (AliasAnalysis *)this;
294 return this;
295 }
Chris Lattner3a353e82004-07-27 06:40:37 +0000296
Chandler Carruth194f59c2015-07-22 23:15:57 +0000297 //------------------------------------------------
298 // Implement the AliasAnalysis API
299 //
300 AliasResult alias(const MemoryLocation &LocA,
301 const MemoryLocation &LocB) override;
302 ModRefInfo getModRefInfo(ImmutableCallSite CS,
303 const MemoryLocation &Loc) override;
304 ModRefInfo getModRefInfo(ImmutableCallSite CS1,
305 ImmutableCallSite CS2) override {
306 return AliasAnalysis::getModRefInfo(CS1, CS2);
307 }
308
309 /// getModRefBehavior - Return the behavior of the specified function if
310 /// called from the specified call site. The call site may be null in which
311 /// case the most generic behavior of this function should be returned.
312 FunctionModRefBehavior getModRefBehavior(const Function *F) override {
313 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
314
Chandler Carruth5657b732015-07-22 23:56:31 +0000315 if (FunctionInfo *FI = getFunctionInfo(F)) {
316 if (FI->getModRefInfo() == MRI_NoModRef)
Chandler Carruth194f59c2015-07-22 23:15:57 +0000317 Min = FMRB_DoesNotAccessMemory;
Chandler Carruth5657b732015-07-22 23:56:31 +0000318 else if ((FI->getModRefInfo() & MRI_Mod) == 0)
Chandler Carruth194f59c2015-07-22 23:15:57 +0000319 Min = FMRB_OnlyReadsMemory;
320 }
321
322 return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
323 }
324
325 /// getModRefBehavior - Return the behavior of the specified function if
326 /// called from the specified call site. The call site may be null in which
327 /// case the most generic behavior of this function should be returned.
328 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) override {
329 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
330
331 if (const Function *F = CS.getCalledFunction())
Chandler Carruth5657b732015-07-22 23:56:31 +0000332 if (FunctionInfo *FI = getFunctionInfo(F)) {
333 if (FI->getModRefInfo() == MRI_NoModRef)
Chandler Carruth194f59c2015-07-22 23:15:57 +0000334 Min = FMRB_DoesNotAccessMemory;
Chandler Carruth5657b732015-07-22 23:56:31 +0000335 else if ((FI->getModRefInfo() & MRI_Mod) == 0)
Chandler Carruth194f59c2015-07-22 23:15:57 +0000336 Min = FMRB_OnlyReadsMemory;
337 }
338
339 return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
340 }
341
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000342private:
Chandler Carruth5657b732015-07-22 23:56:31 +0000343 /// Returns the function info for the function, or null if we don't have
344 /// anything useful to say about it.
345 FunctionInfo *getFunctionInfo(const Function *F) {
346 auto I = FunctionInfos.find(F);
347 if (I != FunctionInfos.end())
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000348 return &I->second;
349 return nullptr;
350 }
Chris Lattner3a353e82004-07-27 06:40:37 +0000351
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000352 void AnalyzeGlobals(Module &M);
353 void AnalyzeCallGraph(CallGraph &CG, Module &M);
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000354 bool AnalyzeUsesOfPointer(Value *V,
355 SmallPtrSetImpl<Function *> *Readers = nullptr,
356 SmallPtrSetImpl<Function *> *Writers = nullptr,
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000357 GlobalValue *OkayStoreDest = nullptr);
358 bool AnalyzeIndirectGlobalMemory(GlobalValue *GV);
359};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000360}
Chris Lattner26dff502004-06-28 06:33:13 +0000361
Dan Gohmand78c4002008-05-13 00:00:25 +0000362char GlobalsModRef::ID = 0;
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000363INITIALIZE_AG_PASS_BEGIN(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
364 "Simple mod/ref analysis for globals", false, true,
365 false)
Chandler Carruth6378cf52013-11-26 04:19:30 +0000366INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000367INITIALIZE_AG_PASS_END(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
368 "Simple mod/ref analysis for globals", false, true,
369 false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000370
Chris Lattner26dff502004-06-28 06:33:13 +0000371Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
372
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000373/// AnalyzeGlobals - Scan through the users of all of the internal
Duncan Sands42c644e2008-09-03 12:55:42 +0000374/// GlobalValue's in the program. If none of them have their "address taken"
Chris Lattner26dff502004-06-28 06:33:13 +0000375/// (really, their address passed to something nontrivial), record this fact,
376/// and record the functions that they are used directly in.
377void GlobalsModRef::AnalyzeGlobals(Module &M) {
Chandler Carruth786e6db2015-07-28 06:01:57 +0000378 SmallPtrSet<Function *, 64> TrackedFunctions;
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000379 for (Function &F : M)
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000380 if (F.hasLocalLinkage())
381 if (!AnalyzeUsesOfPointer(&F)) {
Chris Lattner3a353e82004-07-27 06:40:37 +0000382 // Remember that we are tracking this global.
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000383 NonAddressTakenGlobals.insert(&F);
Chandler Carruth786e6db2015-07-28 06:01:57 +0000384 TrackedFunctions.insert(&F);
Chandler Carruthda7c1912015-07-22 09:27:58 +0000385 Handles.emplace_front(*this, &F);
386 Handles.front().I = Handles.begin();
Chris Lattner26dff502004-06-28 06:33:13 +0000387 ++NumNonAddrTakenFunctions;
388 }
Chris Lattner26dff502004-06-28 06:33:13 +0000389
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000390 SmallPtrSet<Function *, 64> Readers, Writers;
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000391 for (GlobalVariable &GV : M.globals())
392 if (GV.hasLocalLinkage()) {
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000393 if (!AnalyzeUsesOfPointer(&GV, &Readers,
394 GV.isConstant() ? nullptr : &Writers)) {
Chris Lattner26dff502004-06-28 06:33:13 +0000395 // Remember that we are tracking this global, and the mod/ref fns
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000396 NonAddressTakenGlobals.insert(&GV);
Chandler Carruthda7c1912015-07-22 09:27:58 +0000397 Handles.emplace_front(*this, &GV);
398 Handles.front().I = Handles.begin();
Duncan Sands42c644e2008-09-03 12:55:42 +0000399
Chandler Carruth786e6db2015-07-28 06:01:57 +0000400 for (Function *Reader : Readers) {
401 if (TrackedFunctions.insert(Reader).second) {
402 Handles.emplace_front(*this, Reader);
403 Handles.front().I = Handles.begin();
404 }
Chandler Carruth5657b732015-07-22 23:56:31 +0000405 FunctionInfos[Reader].addModRefInfoForGlobal(GV, MRI_Ref);
Chandler Carruth786e6db2015-07-28 06:01:57 +0000406 }
Chris Lattner3a353e82004-07-27 06:40:37 +0000407
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000408 if (!GV.isConstant()) // No need to keep track of writers to constants
Chandler Carruth786e6db2015-07-28 06:01:57 +0000409 for (Function *Writer : Writers) {
410 if (TrackedFunctions.insert(Writer).second) {
411 Handles.emplace_front(*this, Writer);
412 Handles.front().I = Handles.begin();
413 }
Chandler Carruth5657b732015-07-22 23:56:31 +0000414 FunctionInfos[Writer].addModRefInfoForGlobal(GV, MRI_Mod);
Chandler Carruth786e6db2015-07-28 06:01:57 +0000415 }
Chris Lattner26dff502004-06-28 06:33:13 +0000416 ++NumNonAddrTakenGlobalVars;
Duncan Sands42c644e2008-09-03 12:55:42 +0000417
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000418 // If this global holds a pointer type, see if it is an indirect global.
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000419 if (GV.getType()->getElementType()->isPointerTy() &&
420 AnalyzeIndirectGlobalMemory(&GV))
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000421 ++NumIndirectGlobalVars;
Chris Lattner26dff502004-06-28 06:33:13 +0000422 }
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000423 Readers.clear();
424 Writers.clear();
Chris Lattner26dff502004-06-28 06:33:13 +0000425 }
426}
427
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000428/// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
429/// If this is used by anything complex (i.e., the address escapes), return
430/// true. Also, while we are at it, keep track of those functions that read and
431/// write to the value.
432///
433/// If OkayStoreDest is non-null, stores into this global are allowed.
434bool GlobalsModRef::AnalyzeUsesOfPointer(Value *V,
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000435 SmallPtrSetImpl<Function *> *Readers,
436 SmallPtrSetImpl<Function *> *Writers,
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000437 GlobalValue *OkayStoreDest) {
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000438 if (!V->getType()->isPointerTy())
439 return true;
Chris Lattner26dff502004-06-28 06:33:13 +0000440
Chandler Carruthcdf47882014-03-09 03:16:01 +0000441 for (Use &U : V->uses()) {
442 User *I = U.getUser();
443 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000444 if (Readers)
445 Readers->insert(LI->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000446 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000447 if (V == SI->getOperand(1)) {
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000448 if (Writers)
449 Writers->insert(SI->getParent()->getParent());
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000450 } else if (SI->getOperand(1) != OkayStoreDest) {
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000451 return true; // Storing the pointer
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000452 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000453 } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
454 if (AnalyzeUsesOfPointer(I, Readers, Writers))
Victor Hernandez537d8d92009-09-18 21:34:51 +0000455 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000456 } else if (Operator::getOpcode(I) == Instruction::BitCast) {
457 if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
Benjamin Kramerb8266d22014-02-10 14:17:30 +0000458 return true;
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000459 } else if (auto CS = CallSite(I)) {
Chris Lattner26dff502004-06-28 06:33:13 +0000460 // Make sure that this is just the function being called, not that it is
461 // passing into the function.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000462 if (!CS.isCallee(&U)) {
Benjamin Kramerb8266d22014-02-10 14:17:30 +0000463 // Detect calls to free.
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000464 if (isFreeCall(I, TLI)) {
465 if (Writers)
466 Writers->insert(CS->getParent()->getParent());
467 } else {
Benjamin Kramerb8266d22014-02-10 14:17:30 +0000468 return true; // Argument of an unknown call.
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000469 }
Misha Brukman01808ca2005-04-21 21:13:18 +0000470 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000471 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000472 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000473 return true; // Allow comparison against null.
Chris Lattner26dff502004-06-28 06:33:13 +0000474 } else {
475 return true;
476 }
Gabor Greif070b9a22010-07-09 15:53:42 +0000477 }
478
Chris Lattner26dff502004-06-28 06:33:13 +0000479 return false;
480}
481
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000482/// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
483/// which holds a pointer type. See if the global always points to non-aliased
484/// heap memory: that is, all initializers of the globals are allocations, and
485/// those allocations have no use other than initialization of the global.
486/// Further, all loads out of GV must directly use the memory, not store the
487/// pointer somewhere. If this is true, we consider the memory pointed to by
488/// GV to be owned by GV and can disambiguate other pointers from it.
489bool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
490 // Keep track of values related to the allocation of the memory, f.e. the
491 // value produced by the malloc call and any casts.
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000492 std::vector<Value *> AllocRelatedValues;
Duncan Sands42c644e2008-09-03 12:55:42 +0000493
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000494 // Walk the user list of the global. If we find anything other than a direct
495 // load or store, bail out.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000496 for (User *U : GV->users()) {
Gabor Greifaa389f52010-07-09 16:22:36 +0000497 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000498 // The pointer loaded from the global can only be used in simple ways:
499 // we allow addressing of it and loading storing to it. We do *not* allow
500 // storing the loaded pointer somewhere else or passing to a function.
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000501 if (AnalyzeUsesOfPointer(LI))
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000502 return false; // Loaded pointer escapes.
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000503 // TODO: Could try some IP mod/ref of the loaded pointer.
Gabor Greifaa389f52010-07-09 16:22:36 +0000504 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000505 // Storing the global itself.
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000506 if (SI->getOperand(0) == GV)
507 return false;
Duncan Sands42c644e2008-09-03 12:55:42 +0000508
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000509 // If storing the null pointer, ignore it.
510 if (isa<ConstantPointerNull>(SI->getOperand(0)))
511 continue;
Duncan Sands42c644e2008-09-03 12:55:42 +0000512
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000513 // Check the value being stored.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000514 Value *Ptr = GetUnderlyingObject(SI->getOperand(0),
515 GV->getParent()->getDataLayout());
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000516
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000517 if (!isAllocLikeFn(Ptr, TLI))
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000518 return false; // Too hard to analyze.
Duncan Sands42c644e2008-09-03 12:55:42 +0000519
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000520 // Analyze all uses of the allocation. If any of them are used in a
521 // non-simple way (e.g. stored to another global) bail out.
Chandler Carruth4cef26e2015-07-22 22:10:05 +0000522 if (AnalyzeUsesOfPointer(Ptr, /*Readers*/ nullptr, /*Writers*/ nullptr,
523 GV))
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000524 return false; // Loaded pointer escapes.
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000525
526 // Remember that this allocation is related to the indirect global.
527 AllocRelatedValues.push_back(Ptr);
528 } else {
529 // Something complex, bail out.
530 return false;
531 }
532 }
Duncan Sands42c644e2008-09-03 12:55:42 +0000533
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000534 // Okay, this is an indirect global. Remember all of the allocations for
535 // this global in AllocsForIndirectGlobals.
536 while (!AllocRelatedValues.empty()) {
537 AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
Chandler Carruthda7c1912015-07-22 09:27:58 +0000538 Handles.emplace_front(*this, AllocRelatedValues.back());
539 Handles.front().I = Handles.begin();
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000540 AllocRelatedValues.pop_back();
541 }
542 IndirectGlobals.insert(GV);
Chandler Carruthda7c1912015-07-22 09:27:58 +0000543 Handles.emplace_front(*this, GV);
544 Handles.front().I = Handles.begin();
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000545 return true;
546}
547
Chris Lattner26dff502004-06-28 06:33:13 +0000548/// AnalyzeCallGraph - At this point, we know the functions where globals are
549/// immediately stored to and read from. Propagate this information up the call
Chris Lattner3a353e82004-07-27 06:40:37 +0000550/// graph to all callers and compute the mod/ref info for all memory for each
Misha Brukman01808ca2005-04-21 21:13:18 +0000551/// function.
Chris Lattner26dff502004-06-28 06:33:13 +0000552void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
Chris Lattner26dff502004-06-28 06:33:13 +0000553 // We do a bottom-up SCC traversal of the call graph. In other words, we
554 // visit all callees before callers (leaf-first).
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000555 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000556 const std::vector<CallGraphNode *> &SCC = *I;
Duncan Sands21a57992008-09-04 19:16:20 +0000557 assert(!SCC.empty() && "SCC with no functions?");
Duncan Sands42c644e2008-09-03 12:55:42 +0000558
Duncan Sands21a57992008-09-04 19:16:20 +0000559 if (!SCC[0]->getFunction()) {
560 // Calls externally - can't say anything useful. Remove any existing
561 // function records (may have been created when scanning globals).
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000562 for (auto *Node : SCC)
Chandler Carruth5657b732015-07-22 23:56:31 +0000563 FunctionInfos.erase(Node->getFunction());
Duncan Sands42c644e2008-09-03 12:55:42 +0000564 continue;
Duncan Sands21a57992008-09-04 19:16:20 +0000565 }
566
Chandler Carruth5657b732015-07-22 23:56:31 +0000567 FunctionInfo &FI = FunctionInfos[SCC[0]->getFunction()];
Duncan Sands42c644e2008-09-03 12:55:42 +0000568 bool KnowNothing = false;
Chris Lattner3a353e82004-07-27 06:40:37 +0000569
Duncan Sands42c644e2008-09-03 12:55:42 +0000570 // Collect the mod/ref properties due to called functions. We only compute
571 // one mod-ref set.
572 for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
573 Function *F = SCC[i]->getFunction();
574 if (!F) {
575 KnowNothing = true;
Chris Lattner3a353e82004-07-27 06:40:37 +0000576 break;
Chris Lattner26dff502004-06-28 06:33:13 +0000577 }
Chris Lattner3a353e82004-07-27 06:40:37 +0000578
Duncan Sands42c644e2008-09-03 12:55:42 +0000579 if (F->isDeclaration()) {
580 // Try to get mod/ref behaviour from function attributes.
Duncan Sands0eca0572008-09-03 15:31:24 +0000581 if (F->doesNotAccessMemory()) {
582 // Can't do better than that!
583 } else if (F->onlyReadsMemory()) {
Chandler Carruthdbb46222015-07-23 00:12:32 +0000584 FI.addModRefInfo(MRI_Ref);
Duncan Sands06dbb122008-09-12 07:29:58 +0000585 if (!F->isIntrinsic())
Duncan Sandse30b36f2008-09-11 15:43:12 +0000586 // This function might call back into the module and read a global -
Duncan Sands06dbb122008-09-12 07:29:58 +0000587 // consider every global as possibly being read by this function.
Chandler Carruth5657b732015-07-22 23:56:31 +0000588 FI.setMayReadAnyGlobal();
Duncan Sands0eca0572008-09-03 15:31:24 +0000589 } else {
Chandler Carruthdbb46222015-07-23 00:12:32 +0000590 FI.addModRefInfo(MRI_ModRef);
Duncan Sandsd4133ac2008-09-11 19:35:55 +0000591 // Can't say anything useful unless it's an intrinsic - they don't
592 // read or write global variables of the kind considered here.
593 KnowNothing = !F->isIntrinsic();
Duncan Sands42c644e2008-09-03 12:55:42 +0000594 }
595 continue;
596 }
Misha Brukman01808ca2005-04-21 21:13:18 +0000597
Duncan Sands42c644e2008-09-03 12:55:42 +0000598 for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
Duncan Sands21a57992008-09-04 19:16:20 +0000599 CI != E && !KnowNothing; ++CI)
Duncan Sands42c644e2008-09-03 12:55:42 +0000600 if (Function *Callee = CI->second->getFunction()) {
Chandler Carruth5657b732015-07-22 23:56:31 +0000601 if (FunctionInfo *CalleeFI = getFunctionInfo(Callee)) {
Duncan Sands42c644e2008-09-03 12:55:42 +0000602 // Propagate function effect up.
Chandler Carruthdbb46222015-07-23 00:12:32 +0000603 FI.addFunctionInfo(*CalleeFI);
Duncan Sands42c644e2008-09-03 12:55:42 +0000604 } else {
605 // Can't say anything about it. However, if it is inside our SCC,
606 // then nothing needs to be done.
607 CallGraphNode *CalleeNode = CG[Callee];
608 if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end())
609 KnowNothing = true;
610 }
611 } else {
612 KnowNothing = true;
613 }
614 }
615
616 // If we can't say anything useful about this SCC, remove all SCC functions
Chandler Carruth5657b732015-07-22 23:56:31 +0000617 // from the FunctionInfos map.
Duncan Sands42c644e2008-09-03 12:55:42 +0000618 if (KnowNothing) {
Chandler Carrutha033bbb2015-07-15 08:09:23 +0000619 for (auto *Node : SCC)
Chandler Carruth5657b732015-07-22 23:56:31 +0000620 FunctionInfos.erase(Node->getFunction());
Duncan Sandse74d7502008-09-03 16:10:55 +0000621 continue;
Duncan Sands42c644e2008-09-03 12:55:42 +0000622 }
623
624 // Scan the function bodies for explicit loads or stores.
Chandler Carruth6af95d02015-07-15 08:53:29 +0000625 for (auto *Node : SCC) {
Chandler Carruthdbb46222015-07-23 00:12:32 +0000626 if (FI.getModRefInfo() == MRI_ModRef)
Chandler Carruth6af95d02015-07-15 08:53:29 +0000627 break; // The mod/ref lattice saturates here.
628 for (Instruction &I : inst_range(Node->getFunction())) {
Chandler Carruthdbb46222015-07-23 00:12:32 +0000629 if (FI.getModRefInfo() == MRI_ModRef)
Chandler Carruth6af95d02015-07-15 08:53:29 +0000630 break; // The mod/ref lattice saturates here.
631
632 // We handle calls specially because the graph-relevant aspects are
633 // handled above.
634 if (auto CS = CallSite(&I)) {
635 if (isAllocationFn(&I, TLI) || isFreeCall(&I, TLI)) {
636 // FIXME: It is completely unclear why this is necessary and not
637 // handled by the above graph code.
Chandler Carruthdbb46222015-07-23 00:12:32 +0000638 FI.addModRefInfo(MRI_ModRef);
Chandler Carruth6af95d02015-07-15 08:53:29 +0000639 } else if (Function *Callee = CS.getCalledFunction()) {
640 // The callgraph doesn't include intrinsic calls.
641 if (Callee->isIntrinsic()) {
Chandler Carruth194f59c2015-07-22 23:15:57 +0000642 FunctionModRefBehavior Behaviour =
Chandler Carruth6af95d02015-07-15 08:53:29 +0000643 AliasAnalysis::getModRefBehavior(Callee);
Chandler Carruthdbb46222015-07-23 00:12:32 +0000644 FI.addModRefInfo(ModRefInfo(Behaviour & MRI_ModRef));
Chandler Carruth6af95d02015-07-15 08:53:29 +0000645 }
646 }
647 continue;
Duncan Sands9ddb3142008-09-13 12:45:50 +0000648 }
Duncan Sands42c644e2008-09-03 12:55:42 +0000649
Chandler Carruth6af95d02015-07-15 08:53:29 +0000650 // All non-call instructions we use the primary predicates for whether
651 // thay read or write memory.
652 if (I.mayReadFromMemory())
Chandler Carruthdbb46222015-07-23 00:12:32 +0000653 FI.addModRefInfo(MRI_Ref);
Chandler Carruth6af95d02015-07-15 08:53:29 +0000654 if (I.mayWriteToMemory())
Chandler Carruthdbb46222015-07-23 00:12:32 +0000655 FI.addModRefInfo(MRI_Mod);
Chandler Carruth6af95d02015-07-15 08:53:29 +0000656 }
657 }
658
Chandler Carruthdbb46222015-07-23 00:12:32 +0000659 if ((FI.getModRefInfo() & MRI_Mod) == 0)
Duncan Sands42c644e2008-09-03 12:55:42 +0000660 ++NumReadMemFunctions;
Chandler Carruthdbb46222015-07-23 00:12:32 +0000661 if (FI.getModRefInfo() == MRI_NoModRef)
Duncan Sands42c644e2008-09-03 12:55:42 +0000662 ++NumNoMemFunctions;
Duncan Sands42c644e2008-09-03 12:55:42 +0000663
664 // Finally, now that we know the full effect on this SCC, clone the
665 // information to each function in the SCC.
666 for (unsigned i = 1, e = SCC.size(); i != e; ++i)
Chandler Carruth5657b732015-07-22 23:56:31 +0000667 FunctionInfos[SCC[i]->getFunction()] = FI;
Chris Lattner3a353e82004-07-27 06:40:37 +0000668 }
Chris Lattner26dff502004-06-28 06:33:13 +0000669}
670
Chris Lattner26dff502004-06-28 06:33:13 +0000671/// alias - If one of the pointers is to a global that we are tracking, and the
672/// other is some random pointer, we know there cannot be an alias, because the
673/// address of the global isn't taken.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000674AliasResult GlobalsModRef::alias(const MemoryLocation &LocA,
675 const MemoryLocation &LocB) {
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000676 // Get the base object these pointers point to.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000677 const Value *UV1 = GetUnderlyingObject(LocA.Ptr, *DL);
678 const Value *UV2 = GetUnderlyingObject(LocB.Ptr, *DL);
Duncan Sands42c644e2008-09-03 12:55:42 +0000679
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000680 // If either of the underlying values is a global, they may be non-addr-taken
681 // globals, which we can answer queries about.
Dan Gohman5442c712010-08-03 21:48:53 +0000682 const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
683 const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000684 if (GV1 || GV2) {
685 // If the global's address is taken, pretend we don't know it's a pointer to
686 // the global.
Chandler Carruth466d7ad2015-07-14 08:42:39 +0000687 if (GV1 && !NonAddressTakenGlobals.count(GV1))
688 GV1 = nullptr;
689 if (GV2 && !NonAddressTakenGlobals.count(GV2))
690 GV2 = nullptr;
Chris Lattner26dff502004-06-28 06:33:13 +0000691
Dan Gohman4a618822010-02-10 16:03:48 +0000692 // If the two pointers are derived from two different non-addr-taken
Chandler Carruthf55803f2015-07-17 06:58:24 +0000693 // globals we know these can't alias.
694 if (GV1 && GV2 && GV1 != GV2)
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000695 return NoAlias;
Chris Lattner26dff502004-06-28 06:33:13 +0000696
Chandler Carruthf55803f2015-07-17 06:58:24 +0000697 // If one is and the other isn't, it isn't strictly safe but we can fake
698 // this result if necessary for performance. This does not appear to be
699 // a common problem in practice.
700 if (EnableUnsafeGlobalsModRefAliasResults)
701 if ((GV1 || GV2) && GV1 != GV2)
702 return NoAlias;
703
Chandler Carruth99ad7bb2015-07-28 11:11:11 +0000704 // There are particular cases where we can conclude no-alias between
705 // a non-addr-taken global and some other underlying object. Specifically,
706 // a non-addr-taken global is known to not be escaped from any function. It
707 // is also incorrect for a transformation to introduce an escape of
708 // a global in a way that is observable when it was not there previously.
709 // One function being transformed to introduce an escape which could
710 // possibly be observed (via loading from a global or the return value for
711 // example) within another function is never safe. If the observation is
712 // made through non-atomic operations on different threads, it is
713 // a data-race and UB. If the observation is well defined, by being
714 // observed the transformation would have changed program behavior by
715 // introducing the observed escape, making it an invalid transform.
716 //
717 // This property does require that transformations which *temporarily*
718 // escape a global that was not previously escaped, prior to restoring
719 // it, cannot rely on the results of GMR::alias. This seems a reasonable
720 // restriction, although currently there is no way to enforce it. There is
721 // also no realistic optimization pass that would make this mistake. The
722 // closest example is a transformation pass which does reg2mem of SSA
723 // values but stores them into global variables temporarily before
724 // restoring the global variable's value. This could be useful to expose
725 // "benign" races for example. However, it seems reasonable to require that
726 // a pass which introduces escapes of global variables in this way to
727 // either not trust AA results while the escape is active, or to be forced
728 // to operate as a module pass that cannot co-exist with an alias analysis
729 // such as GMR.
730 if ((GV1 || GV2) && GV1 != GV2) {
731 const Value *UV = GV1 ? UV2 : UV1;
732
733 // In order to know that the underlying object cannot alias the
734 // non-addr-taken global, we must know that it would have to be an
735 // escape. Thus if the underlying object is a function argument, a load
736 // from a global, or the return of a function, it cannot alias.
737 if (isa<Argument>(UV) || isa<CallInst>(UV) || isa<InvokeInst>(UV)) {
738 // Arguments to functions or returns from functions are inherently
739 // escaping, so we can immediately classify those as not aliasing any
740 // non-addr-taken globals.
741 return NoAlias;
742 } else if (auto *LI = dyn_cast<LoadInst>(UV)) {
743 // A pointer loaded from a global would have been captured, and we know
744 // that GV is non-addr-taken, so no alias.
745 if (isa<GlobalValue>(LI->getPointerOperand()))
746 return NoAlias;
747 }
748 }
749
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000750 // Otherwise if they are both derived from the same addr-taken global, we
751 // can't know the two accesses don't overlap.
752 }
Duncan Sands42c644e2008-09-03 12:55:42 +0000753
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000754 // These pointers may be based on the memory owned by an indirect global. If
755 // so, we may be able to handle this. First check to see if the base pointer
756 // is a direct load from an indirect global.
Craig Topper353eda42014-04-24 06:44:33 +0000757 GV1 = GV2 = nullptr;
Dan Gohman5442c712010-08-03 21:48:53 +0000758 if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000759 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
760 if (IndirectGlobals.count(GV))
761 GV1 = GV;
Dan Gohman5442c712010-08-03 21:48:53 +0000762 if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
763 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000764 if (IndirectGlobals.count(GV))
765 GV2 = GV;
Duncan Sands42c644e2008-09-03 12:55:42 +0000766
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000767 // These pointers may also be from an allocation for the indirect global. If
768 // so, also handle them.
Chandler Carruth56e2c622015-07-22 11:43:24 +0000769 if (!GV1)
770 GV1 = AllocsForIndirectGlobals.lookup(UV1);
771 if (!GV2)
772 GV2 = AllocsForIndirectGlobals.lookup(UV2);
Duncan Sands42c644e2008-09-03 12:55:42 +0000773
Chris Lattnerbfdd19b2006-10-01 22:36:45 +0000774 // Now that we know whether the two pointers are related to indirect globals,
Chandler Carruthf55803f2015-07-17 06:58:24 +0000775 // use this to disambiguate the pointers. If the pointers are based on
776 // different indirect globals they cannot alias.
777 if (GV1 && GV2 && GV1 != GV2)
Chris Lattner26dff502004-06-28 06:33:13 +0000778 return NoAlias;
Duncan Sands42c644e2008-09-03 12:55:42 +0000779
Chandler Carruthf55803f2015-07-17 06:58:24 +0000780 // If one is based on an indirect global and the other isn't, it isn't
781 // strictly safe but we can fake this result if necessary for performance.
782 // This does not appear to be a common problem in practice.
783 if (EnableUnsafeGlobalsModRefAliasResults)
784 if ((GV1 || GV2) && GV1 != GV2)
785 return NoAlias;
786
Dan Gohman41f14cf2010-09-14 21:25:10 +0000787 return AliasAnalysis::alias(LocA, LocB);
Chris Lattner26dff502004-06-28 06:33:13 +0000788}
789
Chandler Carruth194f59c2015-07-22 23:15:57 +0000790ModRefInfo GlobalsModRef::getModRefInfo(ImmutableCallSite CS,
791 const MemoryLocation &Loc) {
792 unsigned Known = MRI_ModRef;
Chris Lattner26dff502004-06-28 06:33:13 +0000793
794 // If we are asking for mod/ref info of a direct call with a pointer to a
Chris Lattner3a353e82004-07-27 06:40:37 +0000795 // global we are tracking, return information if we have it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000796 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
Dan Gohman41f14cf2010-09-14 21:25:10 +0000797 if (const GlobalValue *GV =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000798 dyn_cast<GlobalValue>(GetUnderlyingObject(Loc.Ptr, DL)))
Rafael Espindola6de96a12009-01-15 20:18:42 +0000799 if (GV->hasLocalLinkage())
Dan Gohman5442c712010-08-03 21:48:53 +0000800 if (const Function *F = CS.getCalledFunction())
Chris Lattner3a353e82004-07-27 06:40:37 +0000801 if (NonAddressTakenGlobals.count(GV))
Chandler Carruth5657b732015-07-22 23:56:31 +0000802 if (const FunctionInfo *FI = getFunctionInfo(F))
803 Known = FI->getModRefInfoForGlobal(*GV);
Chris Lattner26dff502004-06-28 06:33:13 +0000804
Chandler Carruth194f59c2015-07-22 23:15:57 +0000805 if (Known == MRI_NoModRef)
806 return MRI_NoModRef; // No need to query other mod/ref analyses
807 return ModRefInfo(Known & AliasAnalysis::getModRefInfo(CS, Loc));
Chris Lattner26dff502004-06-28 06:33:13 +0000808}