10b57cec5SDimitry Andric //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This simple pass provides alias and mod/ref information for global values
100b57cec5SDimitry Andric // that do not have their address taken, and keeps track of whether functions
110b57cec5SDimitry Andric // read or write memory (are "pure"). For this simple (but very common) case,
120b57cec5SDimitry Andric // we can provide pretty accurate and useful information.
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
150b57cec5SDimitry Andric
160b57cec5SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SCCIterator.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
190b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
205ffd83dbSDimitry Andric #include "llvm/Analysis/CallGraph.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
240b57cec5SDimitry Andric #include "llvm/IR/InstIterator.h"
250b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
260b57cec5SDimitry Andric #include "llvm/IR/Module.h"
2781ad6265SDimitry Andric #include "llvm/IR/PassManager.h"
28480093f4SDimitry Andric #include "llvm/InitializePasses.h"
290b57cec5SDimitry Andric #include "llvm/Pass.h"
300b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
315ffd83dbSDimitry Andric
320b57cec5SDimitry Andric using namespace llvm;
330b57cec5SDimitry Andric
340b57cec5SDimitry Andric #define DEBUG_TYPE "globalsmodref-aa"
350b57cec5SDimitry Andric
360b57cec5SDimitry Andric STATISTIC(NumNonAddrTakenGlobalVars,
370b57cec5SDimitry Andric "Number of global vars without address taken");
380b57cec5SDimitry Andric STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
390b57cec5SDimitry Andric STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
400b57cec5SDimitry Andric STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
410b57cec5SDimitry Andric STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
420b57cec5SDimitry Andric
430b57cec5SDimitry Andric // An option to enable unsafe alias results from the GlobalsModRef analysis.
440b57cec5SDimitry Andric // When enabled, GlobalsModRef will provide no-alias results which in extremely
450b57cec5SDimitry Andric // rare cases may not be conservatively correct. In particular, in the face of
46e8d8bef9SDimitry Andric // transforms which cause asymmetry between how effective getUnderlyingObject
470b57cec5SDimitry Andric // is for two pointers, it may produce incorrect results.
480b57cec5SDimitry Andric //
490b57cec5SDimitry Andric // These unsafe results have been returned by GMR for many years without
500b57cec5SDimitry Andric // causing significant issues in the wild and so we provide a mechanism to
510b57cec5SDimitry Andric // re-enable them for users of LLVM that have a particular performance
520b57cec5SDimitry Andric // sensitivity and no known issues. The option also makes it easy to evaluate
530b57cec5SDimitry Andric // the performance impact of these results.
540b57cec5SDimitry Andric static cl::opt<bool> EnableUnsafeGlobalsModRefAliasResults(
550b57cec5SDimitry Andric "enable-unsafe-globalsmodref-alias-results", cl::init(false), cl::Hidden);
560b57cec5SDimitry Andric
570b57cec5SDimitry Andric /// The mod/ref information collected for a particular function.
580b57cec5SDimitry Andric ///
590b57cec5SDimitry Andric /// We collect information about mod/ref behavior of a function here, both in
600b57cec5SDimitry Andric /// general and as pertains to specific globals. We only have this detailed
610b57cec5SDimitry Andric /// information when we know *something* useful about the behavior. If we
620b57cec5SDimitry Andric /// saturate to fully general mod/ref, we remove the info for the function.
630b57cec5SDimitry Andric class GlobalsAAResult::FunctionInfo {
640b57cec5SDimitry Andric typedef SmallDenseMap<const GlobalValue *, ModRefInfo, 16> GlobalInfoMapType;
650b57cec5SDimitry Andric
660b57cec5SDimitry Andric /// Build a wrapper struct that has 8-byte alignment. All heap allocations
670b57cec5SDimitry Andric /// should provide this much alignment at least, but this makes it clear we
680b57cec5SDimitry Andric /// specifically rely on this amount of alignment.
690b57cec5SDimitry Andric struct alignas(8) AlignedMap {
7081ad6265SDimitry Andric AlignedMap() = default;
7181ad6265SDimitry Andric AlignedMap(const AlignedMap &Arg) = default;
720b57cec5SDimitry Andric GlobalInfoMapType Map;
730b57cec5SDimitry Andric };
740b57cec5SDimitry Andric
750b57cec5SDimitry Andric /// Pointer traits for our aligned map.
760b57cec5SDimitry Andric struct AlignedMapPointerTraits {
getAsVoidPointerGlobalsAAResult::FunctionInfo::AlignedMapPointerTraits770b57cec5SDimitry Andric static inline void *getAsVoidPointer(AlignedMap *P) { return P; }
getFromVoidPointerGlobalsAAResult::FunctionInfo::AlignedMapPointerTraits780b57cec5SDimitry Andric static inline AlignedMap *getFromVoidPointer(void *P) {
790b57cec5SDimitry Andric return (AlignedMap *)P;
800b57cec5SDimitry Andric }
815ffd83dbSDimitry Andric static constexpr int NumLowBitsAvailable = 3;
820b57cec5SDimitry Andric static_assert(alignof(AlignedMap) >= (1 << NumLowBitsAvailable),
830b57cec5SDimitry Andric "AlignedMap insufficiently aligned to have enough low bits.");
840b57cec5SDimitry Andric };
850b57cec5SDimitry Andric
860b57cec5SDimitry Andric /// The bit that flags that this function may read any global. This is
870b57cec5SDimitry Andric /// chosen to mix together with ModRefInfo bits.
880b57cec5SDimitry Andric /// FIXME: This assumes ModRefInfo lattice will remain 4 bits!
890b57cec5SDimitry Andric /// FunctionInfo.getModRefInfo() masks out everything except ModRef so
90bdd1243dSDimitry Andric /// this remains correct.
910b57cec5SDimitry Andric enum { MayReadAnyGlobal = 4 };
920b57cec5SDimitry Andric
930b57cec5SDimitry Andric /// Checks to document the invariants of the bit packing here.
94bdd1243dSDimitry Andric static_assert((MayReadAnyGlobal & static_cast<int>(ModRefInfo::ModRef)) == 0,
950b57cec5SDimitry Andric "ModRef and the MayReadAnyGlobal flag bits overlap.");
96bdd1243dSDimitry Andric static_assert(((MayReadAnyGlobal | static_cast<int>(ModRefInfo::ModRef)) >>
970b57cec5SDimitry Andric AlignedMapPointerTraits::NumLowBitsAvailable) == 0,
980b57cec5SDimitry Andric "Insufficient low bits to store our flag and ModRef info.");
990b57cec5SDimitry Andric
1000b57cec5SDimitry Andric public:
10181ad6265SDimitry Andric FunctionInfo() = default;
~FunctionInfo()1020b57cec5SDimitry Andric ~FunctionInfo() {
1030b57cec5SDimitry Andric delete Info.getPointer();
1040b57cec5SDimitry Andric }
1050b57cec5SDimitry Andric // Spell out the copy ond move constructors and assignment operators to get
1060b57cec5SDimitry Andric // deep copy semantics and correct move semantics in the face of the
1070b57cec5SDimitry Andric // pointer-int pair.
FunctionInfo(const FunctionInfo & Arg)1080b57cec5SDimitry Andric FunctionInfo(const FunctionInfo &Arg)
1090b57cec5SDimitry Andric : Info(nullptr, Arg.Info.getInt()) {
1100b57cec5SDimitry Andric if (const auto *ArgPtr = Arg.Info.getPointer())
1110b57cec5SDimitry Andric Info.setPointer(new AlignedMap(*ArgPtr));
1120b57cec5SDimitry Andric }
FunctionInfo(FunctionInfo && Arg)1130b57cec5SDimitry Andric FunctionInfo(FunctionInfo &&Arg)
1140b57cec5SDimitry Andric : Info(Arg.Info.getPointer(), Arg.Info.getInt()) {
1150b57cec5SDimitry Andric Arg.Info.setPointerAndInt(nullptr, 0);
1160b57cec5SDimitry Andric }
operator =(const FunctionInfo & RHS)1170b57cec5SDimitry Andric FunctionInfo &operator=(const FunctionInfo &RHS) {
1180b57cec5SDimitry Andric delete Info.getPointer();
1190b57cec5SDimitry Andric Info.setPointerAndInt(nullptr, RHS.Info.getInt());
1200b57cec5SDimitry Andric if (const auto *RHSPtr = RHS.Info.getPointer())
1210b57cec5SDimitry Andric Info.setPointer(new AlignedMap(*RHSPtr));
1220b57cec5SDimitry Andric return *this;
1230b57cec5SDimitry Andric }
operator =(FunctionInfo && RHS)1240b57cec5SDimitry Andric FunctionInfo &operator=(FunctionInfo &&RHS) {
1250b57cec5SDimitry Andric delete Info.getPointer();
1260b57cec5SDimitry Andric Info.setPointerAndInt(RHS.Info.getPointer(), RHS.Info.getInt());
1270b57cec5SDimitry Andric RHS.Info.setPointerAndInt(nullptr, 0);
1280b57cec5SDimitry Andric return *this;
1290b57cec5SDimitry Andric }
1300b57cec5SDimitry Andric
1310b57cec5SDimitry Andric /// This method clears MayReadAnyGlobal bit added by GlobalsAAResult to return
132bdd1243dSDimitry Andric /// the corresponding ModRefInfo.
globalClearMayReadAnyGlobal(int I) const1330b57cec5SDimitry Andric ModRefInfo globalClearMayReadAnyGlobal(int I) const {
134bdd1243dSDimitry Andric return ModRefInfo(I & static_cast<int>(ModRefInfo::ModRef));
1350b57cec5SDimitry Andric }
1360b57cec5SDimitry Andric
1370b57cec5SDimitry Andric /// Returns the \c ModRefInfo info for this function.
getModRefInfo() const1380b57cec5SDimitry Andric ModRefInfo getModRefInfo() const {
1390b57cec5SDimitry Andric return globalClearMayReadAnyGlobal(Info.getInt());
1400b57cec5SDimitry Andric }
1410b57cec5SDimitry Andric
1420b57cec5SDimitry Andric /// Adds new \c ModRefInfo for this function to its state.
addModRefInfo(ModRefInfo NewMRI)1430b57cec5SDimitry Andric void addModRefInfo(ModRefInfo NewMRI) {
144bdd1243dSDimitry Andric Info.setInt(Info.getInt() | static_cast<int>(NewMRI));
1450b57cec5SDimitry Andric }
1460b57cec5SDimitry Andric
1470b57cec5SDimitry Andric /// Returns whether this function may read any global variable, and we don't
1480b57cec5SDimitry Andric /// know which global.
mayReadAnyGlobal() const1490b57cec5SDimitry Andric bool mayReadAnyGlobal() const { return Info.getInt() & MayReadAnyGlobal; }
1500b57cec5SDimitry Andric
1510b57cec5SDimitry Andric /// Sets this function as potentially reading from any global.
setMayReadAnyGlobal()1520b57cec5SDimitry Andric void setMayReadAnyGlobal() { Info.setInt(Info.getInt() | MayReadAnyGlobal); }
1530b57cec5SDimitry Andric
1540b57cec5SDimitry Andric /// Returns the \c ModRefInfo info for this function w.r.t. a particular
1550b57cec5SDimitry Andric /// global, which may be more precise than the general information above.
getModRefInfoForGlobal(const GlobalValue & GV) const1560b57cec5SDimitry Andric ModRefInfo getModRefInfoForGlobal(const GlobalValue &GV) const {
1570b57cec5SDimitry Andric ModRefInfo GlobalMRI =
1580b57cec5SDimitry Andric mayReadAnyGlobal() ? ModRefInfo::Ref : ModRefInfo::NoModRef;
1590b57cec5SDimitry Andric if (AlignedMap *P = Info.getPointer()) {
1600b57cec5SDimitry Andric auto I = P->Map.find(&GV);
1610b57cec5SDimitry Andric if (I != P->Map.end())
162bdd1243dSDimitry Andric GlobalMRI |= I->second;
1630b57cec5SDimitry Andric }
1640b57cec5SDimitry Andric return GlobalMRI;
1650b57cec5SDimitry Andric }
1660b57cec5SDimitry Andric
1670b57cec5SDimitry Andric /// Add mod/ref info from another function into ours, saturating towards
1680b57cec5SDimitry Andric /// ModRef.
addFunctionInfo(const FunctionInfo & FI)1690b57cec5SDimitry Andric void addFunctionInfo(const FunctionInfo &FI) {
1700b57cec5SDimitry Andric addModRefInfo(FI.getModRefInfo());
1710b57cec5SDimitry Andric
1720b57cec5SDimitry Andric if (FI.mayReadAnyGlobal())
1730b57cec5SDimitry Andric setMayReadAnyGlobal();
1740b57cec5SDimitry Andric
1750b57cec5SDimitry Andric if (AlignedMap *P = FI.Info.getPointer())
1760b57cec5SDimitry Andric for (const auto &G : P->Map)
1770b57cec5SDimitry Andric addModRefInfoForGlobal(*G.first, G.second);
1780b57cec5SDimitry Andric }
1790b57cec5SDimitry Andric
addModRefInfoForGlobal(const GlobalValue & GV,ModRefInfo NewMRI)1800b57cec5SDimitry Andric void addModRefInfoForGlobal(const GlobalValue &GV, ModRefInfo NewMRI) {
1810b57cec5SDimitry Andric AlignedMap *P = Info.getPointer();
1820b57cec5SDimitry Andric if (!P) {
1830b57cec5SDimitry Andric P = new AlignedMap();
1840b57cec5SDimitry Andric Info.setPointer(P);
1850b57cec5SDimitry Andric }
1860b57cec5SDimitry Andric auto &GlobalMRI = P->Map[&GV];
187bdd1243dSDimitry Andric GlobalMRI |= NewMRI;
1880b57cec5SDimitry Andric }
1890b57cec5SDimitry Andric
1900b57cec5SDimitry Andric /// Clear a global's ModRef info. Should be used when a global is being
1910b57cec5SDimitry Andric /// deleted.
eraseModRefInfoForGlobal(const GlobalValue & GV)1920b57cec5SDimitry Andric void eraseModRefInfoForGlobal(const GlobalValue &GV) {
1930b57cec5SDimitry Andric if (AlignedMap *P = Info.getPointer())
1940b57cec5SDimitry Andric P->Map.erase(&GV);
1950b57cec5SDimitry Andric }
1960b57cec5SDimitry Andric
1970b57cec5SDimitry Andric private:
1980b57cec5SDimitry Andric /// All of the information is encoded into a single pointer, with a three bit
1990b57cec5SDimitry Andric /// integer in the low three bits. The high bit provides a flag for when this
2000b57cec5SDimitry Andric /// function may read any global. The low two bits are the ModRefInfo. And
2010b57cec5SDimitry Andric /// the pointer, when non-null, points to a map from GlobalValue to
2020b57cec5SDimitry Andric /// ModRefInfo specific to that GlobalValue.
2030b57cec5SDimitry Andric PointerIntPair<AlignedMap *, 3, unsigned, AlignedMapPointerTraits> Info;
2040b57cec5SDimitry Andric };
2050b57cec5SDimitry Andric
deleted()2060b57cec5SDimitry Andric void GlobalsAAResult::DeletionCallbackHandle::deleted() {
2070b57cec5SDimitry Andric Value *V = getValPtr();
2080b57cec5SDimitry Andric if (auto *F = dyn_cast<Function>(V))
2090b57cec5SDimitry Andric GAR->FunctionInfos.erase(F);
2100b57cec5SDimitry Andric
2110b57cec5SDimitry Andric if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2120b57cec5SDimitry Andric if (GAR->NonAddressTakenGlobals.erase(GV)) {
2130b57cec5SDimitry Andric // This global might be an indirect global. If so, remove it and
2140b57cec5SDimitry Andric // remove any AllocRelatedValues for it.
2150b57cec5SDimitry Andric if (GAR->IndirectGlobals.erase(GV)) {
2160b57cec5SDimitry Andric // Remove any entries in AllocsForIndirectGlobals for this global.
2170b57cec5SDimitry Andric for (auto I = GAR->AllocsForIndirectGlobals.begin(),
2180b57cec5SDimitry Andric E = GAR->AllocsForIndirectGlobals.end();
2190b57cec5SDimitry Andric I != E; ++I)
2200b57cec5SDimitry Andric if (I->second == GV)
2210b57cec5SDimitry Andric GAR->AllocsForIndirectGlobals.erase(I);
2220b57cec5SDimitry Andric }
2230b57cec5SDimitry Andric
2240b57cec5SDimitry Andric // Scan the function info we have collected and remove this global
2250b57cec5SDimitry Andric // from all of them.
2260b57cec5SDimitry Andric for (auto &FIPair : GAR->FunctionInfos)
2270b57cec5SDimitry Andric FIPair.second.eraseModRefInfoForGlobal(*GV);
2280b57cec5SDimitry Andric }
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric
2310b57cec5SDimitry Andric // If this is an allocation related to an indirect global, remove it.
2320b57cec5SDimitry Andric GAR->AllocsForIndirectGlobals.erase(V);
2330b57cec5SDimitry Andric
2340b57cec5SDimitry Andric // And clear out the handle.
2350b57cec5SDimitry Andric setValPtr(nullptr);
2360b57cec5SDimitry Andric GAR->Handles.erase(I);
2370b57cec5SDimitry Andric // This object is now destroyed!
2380b57cec5SDimitry Andric }
2390b57cec5SDimitry Andric
getMemoryEffects(const Function * F)240bdd1243dSDimitry Andric MemoryEffects GlobalsAAResult::getMemoryEffects(const Function *F) {
241bdd1243dSDimitry Andric if (FunctionInfo *FI = getFunctionInfo(F))
242bdd1243dSDimitry Andric return MemoryEffects(FI->getModRefInfo());
2430b57cec5SDimitry Andric
2445f757f3fSDimitry Andric return MemoryEffects::unknown();
2450b57cec5SDimitry Andric }
2460b57cec5SDimitry Andric
2470b57cec5SDimitry Andric /// Returns the function info for the function, or null if we don't have
2480b57cec5SDimitry Andric /// anything useful to say about it.
2490b57cec5SDimitry Andric GlobalsAAResult::FunctionInfo *
getFunctionInfo(const Function * F)2500b57cec5SDimitry Andric GlobalsAAResult::getFunctionInfo(const Function *F) {
2510b57cec5SDimitry Andric auto I = FunctionInfos.find(F);
2520b57cec5SDimitry Andric if (I != FunctionInfos.end())
2530b57cec5SDimitry Andric return &I->second;
2540b57cec5SDimitry Andric return nullptr;
2550b57cec5SDimitry Andric }
2560b57cec5SDimitry Andric
2570b57cec5SDimitry Andric /// AnalyzeGlobals - Scan through the users of all of the internal
2580b57cec5SDimitry Andric /// GlobalValue's in the program. If none of them have their "address taken"
2590b57cec5SDimitry Andric /// (really, their address passed to something nontrivial), record this fact,
2600b57cec5SDimitry Andric /// and record the functions that they are used directly in.
AnalyzeGlobals(Module & M)2610b57cec5SDimitry Andric void GlobalsAAResult::AnalyzeGlobals(Module &M) {
2620b57cec5SDimitry Andric SmallPtrSet<Function *, 32> TrackedFunctions;
2630b57cec5SDimitry Andric for (Function &F : M)
264480093f4SDimitry Andric if (F.hasLocalLinkage()) {
2650b57cec5SDimitry Andric if (!AnalyzeUsesOfPointer(&F)) {
2660b57cec5SDimitry Andric // Remember that we are tracking this global.
2670b57cec5SDimitry Andric NonAddressTakenGlobals.insert(&F);
2680b57cec5SDimitry Andric TrackedFunctions.insert(&F);
2690b57cec5SDimitry Andric Handles.emplace_front(*this, &F);
2700b57cec5SDimitry Andric Handles.front().I = Handles.begin();
2710b57cec5SDimitry Andric ++NumNonAddrTakenFunctions;
272480093f4SDimitry Andric } else
273480093f4SDimitry Andric UnknownFunctionsWithLocalLinkage = true;
2740b57cec5SDimitry Andric }
2750b57cec5SDimitry Andric
2760b57cec5SDimitry Andric SmallPtrSet<Function *, 16> Readers, Writers;
2770b57cec5SDimitry Andric for (GlobalVariable &GV : M.globals())
2780b57cec5SDimitry Andric if (GV.hasLocalLinkage()) {
2790b57cec5SDimitry Andric if (!AnalyzeUsesOfPointer(&GV, &Readers,
2800b57cec5SDimitry Andric GV.isConstant() ? nullptr : &Writers)) {
2810b57cec5SDimitry Andric // Remember that we are tracking this global, and the mod/ref fns
2820b57cec5SDimitry Andric NonAddressTakenGlobals.insert(&GV);
2830b57cec5SDimitry Andric Handles.emplace_front(*this, &GV);
2840b57cec5SDimitry Andric Handles.front().I = Handles.begin();
2850b57cec5SDimitry Andric
2860b57cec5SDimitry Andric for (Function *Reader : Readers) {
2870b57cec5SDimitry Andric if (TrackedFunctions.insert(Reader).second) {
2880b57cec5SDimitry Andric Handles.emplace_front(*this, Reader);
2890b57cec5SDimitry Andric Handles.front().I = Handles.begin();
2900b57cec5SDimitry Andric }
2910b57cec5SDimitry Andric FunctionInfos[Reader].addModRefInfoForGlobal(GV, ModRefInfo::Ref);
2920b57cec5SDimitry Andric }
2930b57cec5SDimitry Andric
2940b57cec5SDimitry Andric if (!GV.isConstant()) // No need to keep track of writers to constants
2950b57cec5SDimitry Andric for (Function *Writer : Writers) {
2960b57cec5SDimitry Andric if (TrackedFunctions.insert(Writer).second) {
2970b57cec5SDimitry Andric Handles.emplace_front(*this, Writer);
2980b57cec5SDimitry Andric Handles.front().I = Handles.begin();
2990b57cec5SDimitry Andric }
3000b57cec5SDimitry Andric FunctionInfos[Writer].addModRefInfoForGlobal(GV, ModRefInfo::Mod);
3010b57cec5SDimitry Andric }
3020b57cec5SDimitry Andric ++NumNonAddrTakenGlobalVars;
3030b57cec5SDimitry Andric
3040b57cec5SDimitry Andric // If this global holds a pointer type, see if it is an indirect global.
3050b57cec5SDimitry Andric if (GV.getValueType()->isPointerTy() &&
3060b57cec5SDimitry Andric AnalyzeIndirectGlobalMemory(&GV))
3070b57cec5SDimitry Andric ++NumIndirectGlobalVars;
3080b57cec5SDimitry Andric }
3090b57cec5SDimitry Andric Readers.clear();
3100b57cec5SDimitry Andric Writers.clear();
3110b57cec5SDimitry Andric }
3120b57cec5SDimitry Andric }
3130b57cec5SDimitry Andric
3140b57cec5SDimitry Andric /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
3150b57cec5SDimitry Andric /// If this is used by anything complex (i.e., the address escapes), return
3160b57cec5SDimitry Andric /// true. Also, while we are at it, keep track of those functions that read and
3170b57cec5SDimitry Andric /// write to the value.
3180b57cec5SDimitry Andric ///
3190b57cec5SDimitry Andric /// If OkayStoreDest is non-null, stores into this global are allowed.
AnalyzeUsesOfPointer(Value * V,SmallPtrSetImpl<Function * > * Readers,SmallPtrSetImpl<Function * > * Writers,GlobalValue * OkayStoreDest)3200b57cec5SDimitry Andric bool GlobalsAAResult::AnalyzeUsesOfPointer(Value *V,
3210b57cec5SDimitry Andric SmallPtrSetImpl<Function *> *Readers,
3220b57cec5SDimitry Andric SmallPtrSetImpl<Function *> *Writers,
3230b57cec5SDimitry Andric GlobalValue *OkayStoreDest) {
3240b57cec5SDimitry Andric if (!V->getType()->isPointerTy())
3250b57cec5SDimitry Andric return true;
3260b57cec5SDimitry Andric
3270b57cec5SDimitry Andric for (Use &U : V->uses()) {
3280b57cec5SDimitry Andric User *I = U.getUser();
3290b57cec5SDimitry Andric if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3300b57cec5SDimitry Andric if (Readers)
3310b57cec5SDimitry Andric Readers->insert(LI->getParent()->getParent());
3320b57cec5SDimitry Andric } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3330b57cec5SDimitry Andric if (V == SI->getOperand(1)) {
3340b57cec5SDimitry Andric if (Writers)
3350b57cec5SDimitry Andric Writers->insert(SI->getParent()->getParent());
3360b57cec5SDimitry Andric } else if (SI->getOperand(1) != OkayStoreDest) {
3370b57cec5SDimitry Andric return true; // Storing the pointer
3380b57cec5SDimitry Andric }
3390b57cec5SDimitry Andric } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
3400b57cec5SDimitry Andric if (AnalyzeUsesOfPointer(I, Readers, Writers))
3410b57cec5SDimitry Andric return true;
342e8d8bef9SDimitry Andric } else if (Operator::getOpcode(I) == Instruction::BitCast ||
343e8d8bef9SDimitry Andric Operator::getOpcode(I) == Instruction::AddrSpaceCast) {
3440b57cec5SDimitry Andric if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
3450b57cec5SDimitry Andric return true;
3460b57cec5SDimitry Andric } else if (auto *Call = dyn_cast<CallBase>(I)) {
347*0fca6ea1SDimitry Andric if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
348*0fca6ea1SDimitry Andric if (II->getIntrinsicID() == Intrinsic::threadlocal_address &&
349*0fca6ea1SDimitry Andric V == II->getArgOperand(0)) {
350*0fca6ea1SDimitry Andric if (AnalyzeUsesOfPointer(II, Readers, Writers))
351*0fca6ea1SDimitry Andric return true;
352*0fca6ea1SDimitry Andric continue;
353*0fca6ea1SDimitry Andric }
354*0fca6ea1SDimitry Andric }
3550b57cec5SDimitry Andric // Make sure that this is just the function being called, not that it is
3560b57cec5SDimitry Andric // passing into the function.
3570b57cec5SDimitry Andric if (Call->isDataOperand(&U)) {
3580b57cec5SDimitry Andric // Detect calls to free.
3598bcb0991SDimitry Andric if (Call->isArgOperand(&U) &&
360fcaf7f86SDimitry Andric getFreedOperand(Call, &GetTLI(*Call->getFunction())) == U) {
3610b57cec5SDimitry Andric if (Writers)
3620b57cec5SDimitry Andric Writers->insert(Call->getParent()->getParent());
3630b57cec5SDimitry Andric } else {
364bdd1243dSDimitry Andric // In general, we return true for unknown calls, but there are
365bdd1243dSDimitry Andric // some simple checks that we can do for functions that
366bdd1243dSDimitry Andric // will never call back into the module.
367bdd1243dSDimitry Andric auto *F = Call->getCalledFunction();
368bdd1243dSDimitry Andric // TODO: we should be able to remove isDeclaration() check
369bdd1243dSDimitry Andric // and let the function body analysis check for captures,
370bdd1243dSDimitry Andric // and collect the mod-ref effects. This information will
371bdd1243dSDimitry Andric // be later propagated via the call graph.
372bdd1243dSDimitry Andric if (!F || !F->isDeclaration())
373bdd1243dSDimitry Andric return true;
374bdd1243dSDimitry Andric // Note that the NoCallback check here is a little bit too
375bdd1243dSDimitry Andric // conservative. If there are no captures of the global
376bdd1243dSDimitry Andric // in the module, then this call may not be a capture even
377bdd1243dSDimitry Andric // if it does not have NoCallback.
378bdd1243dSDimitry Andric if (!Call->hasFnAttr(Attribute::NoCallback) ||
379bdd1243dSDimitry Andric !Call->isArgOperand(&U) ||
380bdd1243dSDimitry Andric !Call->doesNotCapture(Call->getArgOperandNo(&U)))
381bdd1243dSDimitry Andric return true;
382bdd1243dSDimitry Andric
383bdd1243dSDimitry Andric // Conservatively, assume the call reads and writes the global.
384bdd1243dSDimitry Andric // We could use memory attributes to make it more precise.
385bdd1243dSDimitry Andric if (Readers)
386bdd1243dSDimitry Andric Readers->insert(Call->getParent()->getParent());
387bdd1243dSDimitry Andric if (Writers)
388bdd1243dSDimitry Andric Writers->insert(Call->getParent()->getParent());
3890b57cec5SDimitry Andric }
3900b57cec5SDimitry Andric }
3910b57cec5SDimitry Andric } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
3920b57cec5SDimitry Andric if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
3930b57cec5SDimitry Andric return true; // Allow comparison against null.
3940b57cec5SDimitry Andric } else if (Constant *C = dyn_cast<Constant>(I)) {
3950b57cec5SDimitry Andric // Ignore constants which don't have any live uses.
3960b57cec5SDimitry Andric if (isa<GlobalValue>(C) || C->isConstantUsed())
3970b57cec5SDimitry Andric return true;
3980b57cec5SDimitry Andric } else {
3990b57cec5SDimitry Andric return true;
4000b57cec5SDimitry Andric }
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric
4030b57cec5SDimitry Andric return false;
4040b57cec5SDimitry Andric }
4050b57cec5SDimitry Andric
4060b57cec5SDimitry Andric /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
4070b57cec5SDimitry Andric /// which holds a pointer type. See if the global always points to non-aliased
40804eeddc0SDimitry Andric /// heap memory: that is, all initializers of the globals store a value known
40904eeddc0SDimitry Andric /// to be obtained via a noalias return function call which have no other use.
4100b57cec5SDimitry Andric /// Further, all loads out of GV must directly use the memory, not store the
4110b57cec5SDimitry Andric /// pointer somewhere. If this is true, we consider the memory pointed to by
4120b57cec5SDimitry Andric /// GV to be owned by GV and can disambiguate other pointers from it.
AnalyzeIndirectGlobalMemory(GlobalVariable * GV)4130b57cec5SDimitry Andric bool GlobalsAAResult::AnalyzeIndirectGlobalMemory(GlobalVariable *GV) {
4140b57cec5SDimitry Andric // Keep track of values related to the allocation of the memory, f.e. the
41504eeddc0SDimitry Andric // value produced by the noalias call and any casts.
4160b57cec5SDimitry Andric std::vector<Value *> AllocRelatedValues;
4170b57cec5SDimitry Andric
4180b57cec5SDimitry Andric // If the initializer is a valid pointer, bail.
4190b57cec5SDimitry Andric if (Constant *C = GV->getInitializer())
4200b57cec5SDimitry Andric if (!C->isNullValue())
4210b57cec5SDimitry Andric return false;
4220b57cec5SDimitry Andric
4230b57cec5SDimitry Andric // Walk the user list of the global. If we find anything other than a direct
4240b57cec5SDimitry Andric // load or store, bail out.
4250b57cec5SDimitry Andric for (User *U : GV->users()) {
4260b57cec5SDimitry Andric if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
4270b57cec5SDimitry Andric // The pointer loaded from the global can only be used in simple ways:
4280b57cec5SDimitry Andric // we allow addressing of it and loading storing to it. We do *not* allow
4290b57cec5SDimitry Andric // storing the loaded pointer somewhere else or passing to a function.
4300b57cec5SDimitry Andric if (AnalyzeUsesOfPointer(LI))
4310b57cec5SDimitry Andric return false; // Loaded pointer escapes.
4320b57cec5SDimitry Andric // TODO: Could try some IP mod/ref of the loaded pointer.
4330b57cec5SDimitry Andric } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
4340b57cec5SDimitry Andric // Storing the global itself.
4350b57cec5SDimitry Andric if (SI->getOperand(0) == GV)
4360b57cec5SDimitry Andric return false;
4370b57cec5SDimitry Andric
4380b57cec5SDimitry Andric // If storing the null pointer, ignore it.
4390b57cec5SDimitry Andric if (isa<ConstantPointerNull>(SI->getOperand(0)))
4400b57cec5SDimitry Andric continue;
4410b57cec5SDimitry Andric
4420b57cec5SDimitry Andric // Check the value being stored.
443e8d8bef9SDimitry Andric Value *Ptr = getUnderlyingObject(SI->getOperand(0));
4440b57cec5SDimitry Andric
44504eeddc0SDimitry Andric if (!isNoAliasCall(Ptr))
4460b57cec5SDimitry Andric return false; // Too hard to analyze.
4470b57cec5SDimitry Andric
4480b57cec5SDimitry Andric // Analyze all uses of the allocation. If any of them are used in a
4490b57cec5SDimitry Andric // non-simple way (e.g. stored to another global) bail out.
4500b57cec5SDimitry Andric if (AnalyzeUsesOfPointer(Ptr, /*Readers*/ nullptr, /*Writers*/ nullptr,
4510b57cec5SDimitry Andric GV))
4520b57cec5SDimitry Andric return false; // Loaded pointer escapes.
4530b57cec5SDimitry Andric
4540b57cec5SDimitry Andric // Remember that this allocation is related to the indirect global.
4550b57cec5SDimitry Andric AllocRelatedValues.push_back(Ptr);
4560b57cec5SDimitry Andric } else {
4570b57cec5SDimitry Andric // Something complex, bail out.
4580b57cec5SDimitry Andric return false;
4590b57cec5SDimitry Andric }
4600b57cec5SDimitry Andric }
4610b57cec5SDimitry Andric
4620b57cec5SDimitry Andric // Okay, this is an indirect global. Remember all of the allocations for
4630b57cec5SDimitry Andric // this global in AllocsForIndirectGlobals.
4640b57cec5SDimitry Andric while (!AllocRelatedValues.empty()) {
4650b57cec5SDimitry Andric AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
4660b57cec5SDimitry Andric Handles.emplace_front(*this, AllocRelatedValues.back());
4670b57cec5SDimitry Andric Handles.front().I = Handles.begin();
4680b57cec5SDimitry Andric AllocRelatedValues.pop_back();
4690b57cec5SDimitry Andric }
4700b57cec5SDimitry Andric IndirectGlobals.insert(GV);
4710b57cec5SDimitry Andric Handles.emplace_front(*this, GV);
4720b57cec5SDimitry Andric Handles.front().I = Handles.begin();
4730b57cec5SDimitry Andric return true;
4740b57cec5SDimitry Andric }
4750b57cec5SDimitry Andric
CollectSCCMembership(CallGraph & CG)4760b57cec5SDimitry Andric void GlobalsAAResult::CollectSCCMembership(CallGraph &CG) {
4770b57cec5SDimitry Andric // We do a bottom-up SCC traversal of the call graph. In other words, we
4780b57cec5SDimitry Andric // visit all callees before callers (leaf-first).
4790b57cec5SDimitry Andric unsigned SCCID = 0;
4800b57cec5SDimitry Andric for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
4810b57cec5SDimitry Andric const std::vector<CallGraphNode *> &SCC = *I;
4820b57cec5SDimitry Andric assert(!SCC.empty() && "SCC with no functions?");
4830b57cec5SDimitry Andric
4840b57cec5SDimitry Andric for (auto *CGN : SCC)
4850b57cec5SDimitry Andric if (Function *F = CGN->getFunction())
4860b57cec5SDimitry Andric FunctionToSCCMap[F] = SCCID;
4870b57cec5SDimitry Andric ++SCCID;
4880b57cec5SDimitry Andric }
4890b57cec5SDimitry Andric }
4900b57cec5SDimitry Andric
4910b57cec5SDimitry Andric /// AnalyzeCallGraph - At this point, we know the functions where globals are
4920b57cec5SDimitry Andric /// immediately stored to and read from. Propagate this information up the call
4930b57cec5SDimitry Andric /// graph to all callers and compute the mod/ref info for all memory for each
4940b57cec5SDimitry Andric /// function.
AnalyzeCallGraph(CallGraph & CG,Module & M)4950b57cec5SDimitry Andric void GlobalsAAResult::AnalyzeCallGraph(CallGraph &CG, Module &M) {
4960b57cec5SDimitry Andric // We do a bottom-up SCC traversal of the call graph. In other words, we
4970b57cec5SDimitry Andric // visit all callees before callers (leaf-first).
4980b57cec5SDimitry Andric for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
4990b57cec5SDimitry Andric const std::vector<CallGraphNode *> &SCC = *I;
5000b57cec5SDimitry Andric assert(!SCC.empty() && "SCC with no functions?");
5010b57cec5SDimitry Andric
5020b57cec5SDimitry Andric Function *F = SCC[0]->getFunction();
5030b57cec5SDimitry Andric
5040b57cec5SDimitry Andric if (!F || !F->isDefinitionExact()) {
5050b57cec5SDimitry Andric // Calls externally or not exact - can't say anything useful. Remove any
5060b57cec5SDimitry Andric // existing function records (may have been created when scanning
5070b57cec5SDimitry Andric // globals).
5080b57cec5SDimitry Andric for (auto *Node : SCC)
5090b57cec5SDimitry Andric FunctionInfos.erase(Node->getFunction());
5100b57cec5SDimitry Andric continue;
5110b57cec5SDimitry Andric }
5120b57cec5SDimitry Andric
5130b57cec5SDimitry Andric FunctionInfo &FI = FunctionInfos[F];
5140b57cec5SDimitry Andric Handles.emplace_front(*this, F);
5150b57cec5SDimitry Andric Handles.front().I = Handles.begin();
5160b57cec5SDimitry Andric bool KnowNothing = false;
5170b57cec5SDimitry Andric
51881ad6265SDimitry Andric // Intrinsics, like any other synchronizing function, can make effects
51981ad6265SDimitry Andric // of other threads visible. Without nosync we know nothing really.
52081ad6265SDimitry Andric // Similarly, if `nocallback` is missing the function, or intrinsic,
52181ad6265SDimitry Andric // can call into the module arbitrarily. If both are set the function
52281ad6265SDimitry Andric // has an effect but will not interact with accesses of internal
52381ad6265SDimitry Andric // globals inside the module. We are conservative here for optnone
52481ad6265SDimitry Andric // functions, might not be necessary.
52581ad6265SDimitry Andric auto MaySyncOrCallIntoModule = [](const Function &F) {
52681ad6265SDimitry Andric return !F.isDeclaration() || !F.hasNoSync() ||
52781ad6265SDimitry Andric !F.hasFnAttribute(Attribute::NoCallback);
52881ad6265SDimitry Andric };
52981ad6265SDimitry Andric
5300b57cec5SDimitry Andric // Collect the mod/ref properties due to called functions. We only compute
5310b57cec5SDimitry Andric // one mod-ref set.
5320b57cec5SDimitry Andric for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
5330b57cec5SDimitry Andric if (!F) {
5340b57cec5SDimitry Andric KnowNothing = true;
5350b57cec5SDimitry Andric break;
5360b57cec5SDimitry Andric }
5370b57cec5SDimitry Andric
5380b57cec5SDimitry Andric if (F->isDeclaration() || F->hasOptNone()) {
5390b57cec5SDimitry Andric // Try to get mod/ref behaviour from function attributes.
5400b57cec5SDimitry Andric if (F->doesNotAccessMemory()) {
5410b57cec5SDimitry Andric // Can't do better than that!
5420b57cec5SDimitry Andric } else if (F->onlyReadsMemory()) {
5430b57cec5SDimitry Andric FI.addModRefInfo(ModRefInfo::Ref);
54481ad6265SDimitry Andric if (!F->onlyAccessesArgMemory() && MaySyncOrCallIntoModule(*F))
5450b57cec5SDimitry Andric // This function might call back into the module and read a global -
5460b57cec5SDimitry Andric // consider every global as possibly being read by this function.
5470b57cec5SDimitry Andric FI.setMayReadAnyGlobal();
5480b57cec5SDimitry Andric } else {
5490b57cec5SDimitry Andric FI.addModRefInfo(ModRefInfo::ModRef);
550480093f4SDimitry Andric if (!F->onlyAccessesArgMemory())
551480093f4SDimitry Andric FI.setMayReadAnyGlobal();
55281ad6265SDimitry Andric if (MaySyncOrCallIntoModule(*F)) {
553480093f4SDimitry Andric KnowNothing = true;
554480093f4SDimitry Andric break;
555480093f4SDimitry Andric }
5560b57cec5SDimitry Andric }
5570b57cec5SDimitry Andric continue;
5580b57cec5SDimitry Andric }
5590b57cec5SDimitry Andric
5600b57cec5SDimitry Andric for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
5610b57cec5SDimitry Andric CI != E && !KnowNothing; ++CI)
5620b57cec5SDimitry Andric if (Function *Callee = CI->second->getFunction()) {
5630b57cec5SDimitry Andric if (FunctionInfo *CalleeFI = getFunctionInfo(Callee)) {
5640b57cec5SDimitry Andric // Propagate function effect up.
5650b57cec5SDimitry Andric FI.addFunctionInfo(*CalleeFI);
5660b57cec5SDimitry Andric } else {
5670b57cec5SDimitry Andric // Can't say anything about it. However, if it is inside our SCC,
5680b57cec5SDimitry Andric // then nothing needs to be done.
5690b57cec5SDimitry Andric CallGraphNode *CalleeNode = CG[Callee];
5700b57cec5SDimitry Andric if (!is_contained(SCC, CalleeNode))
5710b57cec5SDimitry Andric KnowNothing = true;
5720b57cec5SDimitry Andric }
5730b57cec5SDimitry Andric } else {
5740b57cec5SDimitry Andric KnowNothing = true;
5750b57cec5SDimitry Andric }
5760b57cec5SDimitry Andric }
5770b57cec5SDimitry Andric
5780b57cec5SDimitry Andric // If we can't say anything useful about this SCC, remove all SCC functions
5790b57cec5SDimitry Andric // from the FunctionInfos map.
5800b57cec5SDimitry Andric if (KnowNothing) {
5810b57cec5SDimitry Andric for (auto *Node : SCC)
5820b57cec5SDimitry Andric FunctionInfos.erase(Node->getFunction());
5830b57cec5SDimitry Andric continue;
5840b57cec5SDimitry Andric }
5850b57cec5SDimitry Andric
5860b57cec5SDimitry Andric // Scan the function bodies for explicit loads or stores.
5870b57cec5SDimitry Andric for (auto *Node : SCC) {
5880b57cec5SDimitry Andric if (isModAndRefSet(FI.getModRefInfo()))
5890b57cec5SDimitry Andric break; // The mod/ref lattice saturates here.
5900b57cec5SDimitry Andric
5910b57cec5SDimitry Andric // Don't prove any properties based on the implementation of an optnone
5920b57cec5SDimitry Andric // function. Function attributes were already used as a best approximation
5930b57cec5SDimitry Andric // above.
5940b57cec5SDimitry Andric if (Node->getFunction()->hasOptNone())
5950b57cec5SDimitry Andric continue;
5960b57cec5SDimitry Andric
5970b57cec5SDimitry Andric for (Instruction &I : instructions(Node->getFunction())) {
5980b57cec5SDimitry Andric if (isModAndRefSet(FI.getModRefInfo()))
5990b57cec5SDimitry Andric break; // The mod/ref lattice saturates here.
6000b57cec5SDimitry Andric
6010b57cec5SDimitry Andric // We handle calls specially because the graph-relevant aspects are
6020b57cec5SDimitry Andric // handled above.
603bdd1243dSDimitry Andric if (isa<CallBase>(&I))
6040b57cec5SDimitry Andric continue;
6050b57cec5SDimitry Andric
6060b57cec5SDimitry Andric // All non-call instructions we use the primary predicates for whether
6070b57cec5SDimitry Andric // they read or write memory.
6080b57cec5SDimitry Andric if (I.mayReadFromMemory())
6090b57cec5SDimitry Andric FI.addModRefInfo(ModRefInfo::Ref);
6100b57cec5SDimitry Andric if (I.mayWriteToMemory())
6110b57cec5SDimitry Andric FI.addModRefInfo(ModRefInfo::Mod);
6120b57cec5SDimitry Andric }
6130b57cec5SDimitry Andric }
6140b57cec5SDimitry Andric
6150b57cec5SDimitry Andric if (!isModSet(FI.getModRefInfo()))
6160b57cec5SDimitry Andric ++NumReadMemFunctions;
6170b57cec5SDimitry Andric if (!isModOrRefSet(FI.getModRefInfo()))
6180b57cec5SDimitry Andric ++NumNoMemFunctions;
6190b57cec5SDimitry Andric
6200b57cec5SDimitry Andric // Finally, now that we know the full effect on this SCC, clone the
6210b57cec5SDimitry Andric // information to each function in the SCC.
6220b57cec5SDimitry Andric // FI is a reference into FunctionInfos, so copy it now so that it doesn't
6230b57cec5SDimitry Andric // get invalidated if DenseMap decides to re-hash.
6240b57cec5SDimitry Andric FunctionInfo CachedFI = FI;
6250b57cec5SDimitry Andric for (unsigned i = 1, e = SCC.size(); i != e; ++i)
6260b57cec5SDimitry Andric FunctionInfos[SCC[i]->getFunction()] = CachedFI;
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric }
6290b57cec5SDimitry Andric
6300b57cec5SDimitry Andric // GV is a non-escaping global. V is a pointer address that has been loaded from.
6310b57cec5SDimitry Andric // If we can prove that V must escape, we can conclude that a load from V cannot
6320b57cec5SDimitry Andric // alias GV.
isNonEscapingGlobalNoAliasWithLoad(const GlobalValue * GV,const Value * V,int & Depth,const DataLayout & DL)6330b57cec5SDimitry Andric static bool isNonEscapingGlobalNoAliasWithLoad(const GlobalValue *GV,
6340b57cec5SDimitry Andric const Value *V,
6350b57cec5SDimitry Andric int &Depth,
6360b57cec5SDimitry Andric const DataLayout &DL) {
6370b57cec5SDimitry Andric SmallPtrSet<const Value *, 8> Visited;
6380b57cec5SDimitry Andric SmallVector<const Value *, 8> Inputs;
6390b57cec5SDimitry Andric Visited.insert(V);
6400b57cec5SDimitry Andric Inputs.push_back(V);
6410b57cec5SDimitry Andric do {
6420b57cec5SDimitry Andric const Value *Input = Inputs.pop_back_val();
6430b57cec5SDimitry Andric
6440b57cec5SDimitry Andric if (isa<GlobalValue>(Input) || isa<Argument>(Input) || isa<CallInst>(Input) ||
6450b57cec5SDimitry Andric isa<InvokeInst>(Input))
6460b57cec5SDimitry Andric // Arguments to functions or returns from functions are inherently
6470b57cec5SDimitry Andric // escaping, so we can immediately classify those as not aliasing any
6480b57cec5SDimitry Andric // non-addr-taken globals.
6490b57cec5SDimitry Andric //
6500b57cec5SDimitry Andric // (Transitive) loads from a global are also safe - if this aliased
6510b57cec5SDimitry Andric // another global, its address would escape, so no alias.
6520b57cec5SDimitry Andric continue;
6530b57cec5SDimitry Andric
6540b57cec5SDimitry Andric // Recurse through a limited number of selects, loads and PHIs. This is an
6550b57cec5SDimitry Andric // arbitrary depth of 4, lower numbers could be used to fix compile time
6560b57cec5SDimitry Andric // issues if needed, but this is generally expected to be only be important
6570b57cec5SDimitry Andric // for small depths.
6580b57cec5SDimitry Andric if (++Depth > 4)
6590b57cec5SDimitry Andric return false;
6600b57cec5SDimitry Andric
6610b57cec5SDimitry Andric if (auto *LI = dyn_cast<LoadInst>(Input)) {
662e8d8bef9SDimitry Andric Inputs.push_back(getUnderlyingObject(LI->getPointerOperand()));
6630b57cec5SDimitry Andric continue;
6640b57cec5SDimitry Andric }
6650b57cec5SDimitry Andric if (auto *SI = dyn_cast<SelectInst>(Input)) {
666e8d8bef9SDimitry Andric const Value *LHS = getUnderlyingObject(SI->getTrueValue());
667e8d8bef9SDimitry Andric const Value *RHS = getUnderlyingObject(SI->getFalseValue());
6680b57cec5SDimitry Andric if (Visited.insert(LHS).second)
6690b57cec5SDimitry Andric Inputs.push_back(LHS);
6700b57cec5SDimitry Andric if (Visited.insert(RHS).second)
6710b57cec5SDimitry Andric Inputs.push_back(RHS);
6720b57cec5SDimitry Andric continue;
6730b57cec5SDimitry Andric }
6740b57cec5SDimitry Andric if (auto *PN = dyn_cast<PHINode>(Input)) {
6750b57cec5SDimitry Andric for (const Value *Op : PN->incoming_values()) {
676e8d8bef9SDimitry Andric Op = getUnderlyingObject(Op);
6770b57cec5SDimitry Andric if (Visited.insert(Op).second)
6780b57cec5SDimitry Andric Inputs.push_back(Op);
6790b57cec5SDimitry Andric }
6800b57cec5SDimitry Andric continue;
6810b57cec5SDimitry Andric }
6820b57cec5SDimitry Andric
6830b57cec5SDimitry Andric return false;
6840b57cec5SDimitry Andric } while (!Inputs.empty());
6850b57cec5SDimitry Andric
6860b57cec5SDimitry Andric // All inputs were known to be no-alias.
6870b57cec5SDimitry Andric return true;
6880b57cec5SDimitry Andric }
6890b57cec5SDimitry Andric
6900b57cec5SDimitry Andric // There are particular cases where we can conclude no-alias between
6910b57cec5SDimitry Andric // a non-addr-taken global and some other underlying object. Specifically,
6920b57cec5SDimitry Andric // a non-addr-taken global is known to not be escaped from any function. It is
6930b57cec5SDimitry Andric // also incorrect for a transformation to introduce an escape of a global in
6940b57cec5SDimitry Andric // a way that is observable when it was not there previously. One function
6950b57cec5SDimitry Andric // being transformed to introduce an escape which could possibly be observed
6960b57cec5SDimitry Andric // (via loading from a global or the return value for example) within another
6970b57cec5SDimitry Andric // function is never safe. If the observation is made through non-atomic
6980b57cec5SDimitry Andric // operations on different threads, it is a data-race and UB. If the
6990b57cec5SDimitry Andric // observation is well defined, by being observed the transformation would have
7000b57cec5SDimitry Andric // changed program behavior by introducing the observed escape, making it an
7010b57cec5SDimitry Andric // invalid transform.
7020b57cec5SDimitry Andric //
7030b57cec5SDimitry Andric // This property does require that transformations which *temporarily* escape
7040b57cec5SDimitry Andric // a global that was not previously escaped, prior to restoring it, cannot rely
7050b57cec5SDimitry Andric // on the results of GMR::alias. This seems a reasonable restriction, although
7060b57cec5SDimitry Andric // currently there is no way to enforce it. There is also no realistic
7070b57cec5SDimitry Andric // optimization pass that would make this mistake. The closest example is
7080b57cec5SDimitry Andric // a transformation pass which does reg2mem of SSA values but stores them into
7090b57cec5SDimitry Andric // global variables temporarily before restoring the global variable's value.
7100b57cec5SDimitry Andric // This could be useful to expose "benign" races for example. However, it seems
7110b57cec5SDimitry Andric // reasonable to require that a pass which introduces escapes of global
7120b57cec5SDimitry Andric // variables in this way to either not trust AA results while the escape is
7130b57cec5SDimitry Andric // active, or to be forced to operate as a module pass that cannot co-exist
7140b57cec5SDimitry Andric // with an alias analysis such as GMR.
isNonEscapingGlobalNoAlias(const GlobalValue * GV,const Value * V)7150b57cec5SDimitry Andric bool GlobalsAAResult::isNonEscapingGlobalNoAlias(const GlobalValue *GV,
7160b57cec5SDimitry Andric const Value *V) {
7170b57cec5SDimitry Andric // In order to know that the underlying object cannot alias the
7180b57cec5SDimitry Andric // non-addr-taken global, we must know that it would have to be an escape.
7190b57cec5SDimitry Andric // Thus if the underlying object is a function argument, a load from
7200b57cec5SDimitry Andric // a global, or the return of a function, it cannot alias. We can also
7210b57cec5SDimitry Andric // recurse through PHI nodes and select nodes provided all of their inputs
7220b57cec5SDimitry Andric // resolve to one of these known-escaping roots.
7230b57cec5SDimitry Andric SmallPtrSet<const Value *, 8> Visited;
7240b57cec5SDimitry Andric SmallVector<const Value *, 8> Inputs;
7250b57cec5SDimitry Andric Visited.insert(V);
7260b57cec5SDimitry Andric Inputs.push_back(V);
7270b57cec5SDimitry Andric int Depth = 0;
7280b57cec5SDimitry Andric do {
7290b57cec5SDimitry Andric const Value *Input = Inputs.pop_back_val();
7300b57cec5SDimitry Andric
7310b57cec5SDimitry Andric if (auto *InputGV = dyn_cast<GlobalValue>(Input)) {
7320b57cec5SDimitry Andric // If one input is the very global we're querying against, then we can't
7330b57cec5SDimitry Andric // conclude no-alias.
7340b57cec5SDimitry Andric if (InputGV == GV)
7350b57cec5SDimitry Andric return false;
7360b57cec5SDimitry Andric
7370b57cec5SDimitry Andric // Distinct GlobalVariables never alias, unless overriden or zero-sized.
7380b57cec5SDimitry Andric // FIXME: The condition can be refined, but be conservative for now.
7390b57cec5SDimitry Andric auto *GVar = dyn_cast<GlobalVariable>(GV);
7400b57cec5SDimitry Andric auto *InputGVar = dyn_cast<GlobalVariable>(InputGV);
7410b57cec5SDimitry Andric if (GVar && InputGVar &&
7420b57cec5SDimitry Andric !GVar->isDeclaration() && !InputGVar->isDeclaration() &&
7430b57cec5SDimitry Andric !GVar->isInterposable() && !InputGVar->isInterposable()) {
7440b57cec5SDimitry Andric Type *GVType = GVar->getInitializer()->getType();
7450b57cec5SDimitry Andric Type *InputGVType = InputGVar->getInitializer()->getType();
7460b57cec5SDimitry Andric if (GVType->isSized() && InputGVType->isSized() &&
7470b57cec5SDimitry Andric (DL.getTypeAllocSize(GVType) > 0) &&
7480b57cec5SDimitry Andric (DL.getTypeAllocSize(InputGVType) > 0))
7490b57cec5SDimitry Andric continue;
7500b57cec5SDimitry Andric }
7510b57cec5SDimitry Andric
7520b57cec5SDimitry Andric // Conservatively return false, even though we could be smarter
7530b57cec5SDimitry Andric // (e.g. look through GlobalAliases).
7540b57cec5SDimitry Andric return false;
7550b57cec5SDimitry Andric }
7560b57cec5SDimitry Andric
7570b57cec5SDimitry Andric if (isa<Argument>(Input) || isa<CallInst>(Input) ||
7580b57cec5SDimitry Andric isa<InvokeInst>(Input)) {
7590b57cec5SDimitry Andric // Arguments to functions or returns from functions are inherently
7600b57cec5SDimitry Andric // escaping, so we can immediately classify those as not aliasing any
7610b57cec5SDimitry Andric // non-addr-taken globals.
7620b57cec5SDimitry Andric continue;
7630b57cec5SDimitry Andric }
7640b57cec5SDimitry Andric
7650b57cec5SDimitry Andric // Recurse through a limited number of selects, loads and PHIs. This is an
7660b57cec5SDimitry Andric // arbitrary depth of 4, lower numbers could be used to fix compile time
7670b57cec5SDimitry Andric // issues if needed, but this is generally expected to be only be important
7680b57cec5SDimitry Andric // for small depths.
7690b57cec5SDimitry Andric if (++Depth > 4)
7700b57cec5SDimitry Andric return false;
7710b57cec5SDimitry Andric
7720b57cec5SDimitry Andric if (auto *LI = dyn_cast<LoadInst>(Input)) {
7730b57cec5SDimitry Andric // A pointer loaded from a global would have been captured, and we know
7740b57cec5SDimitry Andric // that the global is non-escaping, so no alias.
775e8d8bef9SDimitry Andric const Value *Ptr = getUnderlyingObject(LI->getPointerOperand());
7760b57cec5SDimitry Andric if (isNonEscapingGlobalNoAliasWithLoad(GV, Ptr, Depth, DL))
7770b57cec5SDimitry Andric // The load does not alias with GV.
7780b57cec5SDimitry Andric continue;
7790b57cec5SDimitry Andric // Otherwise, a load could come from anywhere, so bail.
7800b57cec5SDimitry Andric return false;
7810b57cec5SDimitry Andric }
7820b57cec5SDimitry Andric if (auto *SI = dyn_cast<SelectInst>(Input)) {
783e8d8bef9SDimitry Andric const Value *LHS = getUnderlyingObject(SI->getTrueValue());
784e8d8bef9SDimitry Andric const Value *RHS = getUnderlyingObject(SI->getFalseValue());
7850b57cec5SDimitry Andric if (Visited.insert(LHS).second)
7860b57cec5SDimitry Andric Inputs.push_back(LHS);
7870b57cec5SDimitry Andric if (Visited.insert(RHS).second)
7880b57cec5SDimitry Andric Inputs.push_back(RHS);
7890b57cec5SDimitry Andric continue;
7900b57cec5SDimitry Andric }
7910b57cec5SDimitry Andric if (auto *PN = dyn_cast<PHINode>(Input)) {
7920b57cec5SDimitry Andric for (const Value *Op : PN->incoming_values()) {
793e8d8bef9SDimitry Andric Op = getUnderlyingObject(Op);
7940b57cec5SDimitry Andric if (Visited.insert(Op).second)
7950b57cec5SDimitry Andric Inputs.push_back(Op);
7960b57cec5SDimitry Andric }
7970b57cec5SDimitry Andric continue;
7980b57cec5SDimitry Andric }
7990b57cec5SDimitry Andric
8000b57cec5SDimitry Andric // FIXME: It would be good to handle other obvious no-alias cases here, but
8010b57cec5SDimitry Andric // it isn't clear how to do so reasonably without building a small version
8025f757f3fSDimitry Andric // of BasicAA into this code.
8030b57cec5SDimitry Andric return false;
8040b57cec5SDimitry Andric } while (!Inputs.empty());
8050b57cec5SDimitry Andric
8060b57cec5SDimitry Andric // If all the inputs to V were definitively no-alias, then V is no-alias.
8070b57cec5SDimitry Andric return true;
8080b57cec5SDimitry Andric }
8090b57cec5SDimitry Andric
invalidate(Module &,const PreservedAnalyses & PA,ModuleAnalysisManager::Invalidator &)8105ffd83dbSDimitry Andric bool GlobalsAAResult::invalidate(Module &, const PreservedAnalyses &PA,
8115ffd83dbSDimitry Andric ModuleAnalysisManager::Invalidator &) {
8125ffd83dbSDimitry Andric // Check whether the analysis has been explicitly invalidated. Otherwise, it's
8135ffd83dbSDimitry Andric // stateless and remains preserved.
8145ffd83dbSDimitry Andric auto PAC = PA.getChecker<GlobalsAA>();
8155ffd83dbSDimitry Andric return !PAC.preservedWhenStateless();
8165ffd83dbSDimitry Andric }
8175ffd83dbSDimitry Andric
8180b57cec5SDimitry Andric /// alias - If one of the pointers is to a global that we are tracking, and the
8190b57cec5SDimitry Andric /// other is some random pointer, we know there cannot be an alias, because the
8200b57cec5SDimitry Andric /// address of the global isn't taken.
alias(const MemoryLocation & LocA,const MemoryLocation & LocB,AAQueryInfo & AAQI,const Instruction *)8210b57cec5SDimitry Andric AliasResult GlobalsAAResult::alias(const MemoryLocation &LocA,
8220b57cec5SDimitry Andric const MemoryLocation &LocB,
823bdd1243dSDimitry Andric AAQueryInfo &AAQI, const Instruction *) {
8240b57cec5SDimitry Andric // Get the base object these pointers point to.
825e8d8bef9SDimitry Andric const Value *UV1 =
826fe6060f1SDimitry Andric getUnderlyingObject(LocA.Ptr->stripPointerCastsForAliasAnalysis());
827e8d8bef9SDimitry Andric const Value *UV2 =
828fe6060f1SDimitry Andric getUnderlyingObject(LocB.Ptr->stripPointerCastsForAliasAnalysis());
8290b57cec5SDimitry Andric
8300b57cec5SDimitry Andric // If either of the underlying values is a global, they may be non-addr-taken
8310b57cec5SDimitry Andric // globals, which we can answer queries about.
8320b57cec5SDimitry Andric const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
8330b57cec5SDimitry Andric const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
8340b57cec5SDimitry Andric if (GV1 || GV2) {
8350b57cec5SDimitry Andric // If the global's address is taken, pretend we don't know it's a pointer to
8360b57cec5SDimitry Andric // the global.
8370b57cec5SDimitry Andric if (GV1 && !NonAddressTakenGlobals.count(GV1))
8380b57cec5SDimitry Andric GV1 = nullptr;
8390b57cec5SDimitry Andric if (GV2 && !NonAddressTakenGlobals.count(GV2))
8400b57cec5SDimitry Andric GV2 = nullptr;
8410b57cec5SDimitry Andric
8420b57cec5SDimitry Andric // If the two pointers are derived from two different non-addr-taken
8430b57cec5SDimitry Andric // globals we know these can't alias.
8440b57cec5SDimitry Andric if (GV1 && GV2 && GV1 != GV2)
845fe6060f1SDimitry Andric return AliasResult::NoAlias;
8460b57cec5SDimitry Andric
8470b57cec5SDimitry Andric // If one is and the other isn't, it isn't strictly safe but we can fake
8480b57cec5SDimitry Andric // this result if necessary for performance. This does not appear to be
8490b57cec5SDimitry Andric // a common problem in practice.
8500b57cec5SDimitry Andric if (EnableUnsafeGlobalsModRefAliasResults)
8510b57cec5SDimitry Andric if ((GV1 || GV2) && GV1 != GV2)
852fe6060f1SDimitry Andric return AliasResult::NoAlias;
8530b57cec5SDimitry Andric
8540b57cec5SDimitry Andric // Check for a special case where a non-escaping global can be used to
8550b57cec5SDimitry Andric // conclude no-alias.
8560b57cec5SDimitry Andric if ((GV1 || GV2) && GV1 != GV2) {
8570b57cec5SDimitry Andric const GlobalValue *GV = GV1 ? GV1 : GV2;
8580b57cec5SDimitry Andric const Value *UV = GV1 ? UV2 : UV1;
8590b57cec5SDimitry Andric if (isNonEscapingGlobalNoAlias(GV, UV))
860fe6060f1SDimitry Andric return AliasResult::NoAlias;
8610b57cec5SDimitry Andric }
8620b57cec5SDimitry Andric
8630b57cec5SDimitry Andric // Otherwise if they are both derived from the same addr-taken global, we
8640b57cec5SDimitry Andric // can't know the two accesses don't overlap.
8650b57cec5SDimitry Andric }
8660b57cec5SDimitry Andric
8670b57cec5SDimitry Andric // These pointers may be based on the memory owned by an indirect global. If
8680b57cec5SDimitry Andric // so, we may be able to handle this. First check to see if the base pointer
8690b57cec5SDimitry Andric // is a direct load from an indirect global.
8700b57cec5SDimitry Andric GV1 = GV2 = nullptr;
8710b57cec5SDimitry Andric if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
8720b57cec5SDimitry Andric if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
8730b57cec5SDimitry Andric if (IndirectGlobals.count(GV))
8740b57cec5SDimitry Andric GV1 = GV;
8750b57cec5SDimitry Andric if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
8760b57cec5SDimitry Andric if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
8770b57cec5SDimitry Andric if (IndirectGlobals.count(GV))
8780b57cec5SDimitry Andric GV2 = GV;
8790b57cec5SDimitry Andric
8800b57cec5SDimitry Andric // These pointers may also be from an allocation for the indirect global. If
8810b57cec5SDimitry Andric // so, also handle them.
8820b57cec5SDimitry Andric if (!GV1)
8830b57cec5SDimitry Andric GV1 = AllocsForIndirectGlobals.lookup(UV1);
8840b57cec5SDimitry Andric if (!GV2)
8850b57cec5SDimitry Andric GV2 = AllocsForIndirectGlobals.lookup(UV2);
8860b57cec5SDimitry Andric
8870b57cec5SDimitry Andric // Now that we know whether the two pointers are related to indirect globals,
8880b57cec5SDimitry Andric // use this to disambiguate the pointers. If the pointers are based on
8890b57cec5SDimitry Andric // different indirect globals they cannot alias.
8900b57cec5SDimitry Andric if (GV1 && GV2 && GV1 != GV2)
891fe6060f1SDimitry Andric return AliasResult::NoAlias;
8920b57cec5SDimitry Andric
8930b57cec5SDimitry Andric // If one is based on an indirect global and the other isn't, it isn't
8940b57cec5SDimitry Andric // strictly safe but we can fake this result if necessary for performance.
8950b57cec5SDimitry Andric // This does not appear to be a common problem in practice.
8960b57cec5SDimitry Andric if (EnableUnsafeGlobalsModRefAliasResults)
8970b57cec5SDimitry Andric if ((GV1 || GV2) && GV1 != GV2)
898fe6060f1SDimitry Andric return AliasResult::NoAlias;
8990b57cec5SDimitry Andric
9005f757f3fSDimitry Andric return AliasResult::MayAlias;
9010b57cec5SDimitry Andric }
9020b57cec5SDimitry Andric
getModRefInfoForArgument(const CallBase * Call,const GlobalValue * GV,AAQueryInfo & AAQI)9030b57cec5SDimitry Andric ModRefInfo GlobalsAAResult::getModRefInfoForArgument(const CallBase *Call,
9040b57cec5SDimitry Andric const GlobalValue *GV,
9050b57cec5SDimitry Andric AAQueryInfo &AAQI) {
9060b57cec5SDimitry Andric if (Call->doesNotAccessMemory())
9070b57cec5SDimitry Andric return ModRefInfo::NoModRef;
9080b57cec5SDimitry Andric ModRefInfo ConservativeResult =
9090b57cec5SDimitry Andric Call->onlyReadsMemory() ? ModRefInfo::Ref : ModRefInfo::ModRef;
9100b57cec5SDimitry Andric
9110b57cec5SDimitry Andric // Iterate through all the arguments to the called function. If any argument
9120b57cec5SDimitry Andric // is based on GV, return the conservative result.
913fcaf7f86SDimitry Andric for (const auto &A : Call->args()) {
9140b57cec5SDimitry Andric SmallVector<const Value*, 4> Objects;
915e8d8bef9SDimitry Andric getUnderlyingObjects(A, Objects);
9160b57cec5SDimitry Andric
9170b57cec5SDimitry Andric // All objects must be identified.
9180b57cec5SDimitry Andric if (!all_of(Objects, isIdentifiedObject) &&
9190b57cec5SDimitry Andric // Try ::alias to see if all objects are known not to alias GV.
9200b57cec5SDimitry Andric !all_of(Objects, [&](const Value *V) {
921e8d8bef9SDimitry Andric return this->alias(MemoryLocation::getBeforeOrAfter(V),
922bdd1243dSDimitry Andric MemoryLocation::getBeforeOrAfter(GV), AAQI,
923bdd1243dSDimitry Andric nullptr) == AliasResult::NoAlias;
9240b57cec5SDimitry Andric }))
9250b57cec5SDimitry Andric return ConservativeResult;
9260b57cec5SDimitry Andric
9270b57cec5SDimitry Andric if (is_contained(Objects, GV))
9280b57cec5SDimitry Andric return ConservativeResult;
9290b57cec5SDimitry Andric }
9300b57cec5SDimitry Andric
9310b57cec5SDimitry Andric // We identified all objects in the argument list, and none of them were GV.
9320b57cec5SDimitry Andric return ModRefInfo::NoModRef;
9330b57cec5SDimitry Andric }
9340b57cec5SDimitry Andric
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc,AAQueryInfo & AAQI)9350b57cec5SDimitry Andric ModRefInfo GlobalsAAResult::getModRefInfo(const CallBase *Call,
9360b57cec5SDimitry Andric const MemoryLocation &Loc,
9370b57cec5SDimitry Andric AAQueryInfo &AAQI) {
9380b57cec5SDimitry Andric ModRefInfo Known = ModRefInfo::ModRef;
9390b57cec5SDimitry Andric
9400b57cec5SDimitry Andric // If we are asking for mod/ref info of a direct call with a pointer to a
9410b57cec5SDimitry Andric // global we are tracking, return information if we have it.
9420b57cec5SDimitry Andric if (const GlobalValue *GV =
943e8d8bef9SDimitry Andric dyn_cast<GlobalValue>(getUnderlyingObject(Loc.Ptr)))
944480093f4SDimitry Andric // If GV is internal to this IR and there is no function with local linkage
945480093f4SDimitry Andric // that has had their address taken, keep looking for a tighter ModRefInfo.
946480093f4SDimitry Andric if (GV->hasLocalLinkage() && !UnknownFunctionsWithLocalLinkage)
9470b57cec5SDimitry Andric if (const Function *F = Call->getCalledFunction())
9480b57cec5SDimitry Andric if (NonAddressTakenGlobals.count(GV))
9490b57cec5SDimitry Andric if (const FunctionInfo *FI = getFunctionInfo(F))
950bdd1243dSDimitry Andric Known = FI->getModRefInfoForGlobal(*GV) |
951bdd1243dSDimitry Andric getModRefInfoForArgument(Call, GV, AAQI);
9520b57cec5SDimitry Andric
953bdd1243dSDimitry Andric return Known;
9540b57cec5SDimitry Andric }
9550b57cec5SDimitry Andric
GlobalsAAResult(const DataLayout & DL,std::function<const TargetLibraryInfo & (Function & F)> GetTLI)9568bcb0991SDimitry Andric GlobalsAAResult::GlobalsAAResult(
9578bcb0991SDimitry Andric const DataLayout &DL,
9588bcb0991SDimitry Andric std::function<const TargetLibraryInfo &(Function &F)> GetTLI)
95904eeddc0SDimitry Andric : DL(DL), GetTLI(std::move(GetTLI)) {}
9600b57cec5SDimitry Andric
GlobalsAAResult(GlobalsAAResult && Arg)9610b57cec5SDimitry Andric GlobalsAAResult::GlobalsAAResult(GlobalsAAResult &&Arg)
9628bcb0991SDimitry Andric : AAResultBase(std::move(Arg)), DL(Arg.DL), GetTLI(std::move(Arg.GetTLI)),
9630b57cec5SDimitry Andric NonAddressTakenGlobals(std::move(Arg.NonAddressTakenGlobals)),
9640b57cec5SDimitry Andric IndirectGlobals(std::move(Arg.IndirectGlobals)),
9650b57cec5SDimitry Andric AllocsForIndirectGlobals(std::move(Arg.AllocsForIndirectGlobals)),
9660b57cec5SDimitry Andric FunctionInfos(std::move(Arg.FunctionInfos)),
9670b57cec5SDimitry Andric Handles(std::move(Arg.Handles)) {
9680b57cec5SDimitry Andric // Update the parent for each DeletionCallbackHandle.
9690b57cec5SDimitry Andric for (auto &H : Handles) {
9700b57cec5SDimitry Andric assert(H.GAR == &Arg);
9710b57cec5SDimitry Andric H.GAR = this;
9720b57cec5SDimitry Andric }
9730b57cec5SDimitry Andric }
9740b57cec5SDimitry Andric
97581ad6265SDimitry Andric GlobalsAAResult::~GlobalsAAResult() = default;
9760b57cec5SDimitry Andric
analyzeModule(Module & M,std::function<const TargetLibraryInfo & (Function & F)> GetTLI,CallGraph & CG)9778bcb0991SDimitry Andric /*static*/ GlobalsAAResult GlobalsAAResult::analyzeModule(
9788bcb0991SDimitry Andric Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
9790b57cec5SDimitry Andric CallGraph &CG) {
9808bcb0991SDimitry Andric GlobalsAAResult Result(M.getDataLayout(), GetTLI);
9810b57cec5SDimitry Andric
9820b57cec5SDimitry Andric // Discover which functions aren't recursive, to feed into AnalyzeGlobals.
9830b57cec5SDimitry Andric Result.CollectSCCMembership(CG);
9840b57cec5SDimitry Andric
9850b57cec5SDimitry Andric // Find non-addr taken globals.
9860b57cec5SDimitry Andric Result.AnalyzeGlobals(M);
9870b57cec5SDimitry Andric
9880b57cec5SDimitry Andric // Propagate on CG.
9890b57cec5SDimitry Andric Result.AnalyzeCallGraph(CG, M);
9900b57cec5SDimitry Andric
9910b57cec5SDimitry Andric return Result;
9920b57cec5SDimitry Andric }
9930b57cec5SDimitry Andric
9940b57cec5SDimitry Andric AnalysisKey GlobalsAA::Key;
9950b57cec5SDimitry Andric
run(Module & M,ModuleAnalysisManager & AM)9960b57cec5SDimitry Andric GlobalsAAResult GlobalsAA::run(Module &M, ModuleAnalysisManager &AM) {
9978bcb0991SDimitry Andric FunctionAnalysisManager &FAM =
9988bcb0991SDimitry Andric AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
9998bcb0991SDimitry Andric auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
10008bcb0991SDimitry Andric return FAM.getResult<TargetLibraryAnalysis>(F);
10018bcb0991SDimitry Andric };
10028bcb0991SDimitry Andric return GlobalsAAResult::analyzeModule(M, GetTLI,
10030b57cec5SDimitry Andric AM.getResult<CallGraphAnalysis>(M));
10040b57cec5SDimitry Andric }
10050b57cec5SDimitry Andric
run(Module & M,ModuleAnalysisManager & AM)100681ad6265SDimitry Andric PreservedAnalyses RecomputeGlobalsAAPass::run(Module &M,
100781ad6265SDimitry Andric ModuleAnalysisManager &AM) {
100881ad6265SDimitry Andric if (auto *G = AM.getCachedResult<GlobalsAA>(M)) {
100981ad6265SDimitry Andric auto &CG = AM.getResult<CallGraphAnalysis>(M);
101081ad6265SDimitry Andric G->NonAddressTakenGlobals.clear();
101181ad6265SDimitry Andric G->UnknownFunctionsWithLocalLinkage = false;
101281ad6265SDimitry Andric G->IndirectGlobals.clear();
101381ad6265SDimitry Andric G->AllocsForIndirectGlobals.clear();
101481ad6265SDimitry Andric G->FunctionInfos.clear();
101581ad6265SDimitry Andric G->FunctionToSCCMap.clear();
101681ad6265SDimitry Andric G->Handles.clear();
101781ad6265SDimitry Andric G->CollectSCCMembership(CG);
101881ad6265SDimitry Andric G->AnalyzeGlobals(M);
101981ad6265SDimitry Andric G->AnalyzeCallGraph(CG, M);
102081ad6265SDimitry Andric }
102181ad6265SDimitry Andric return PreservedAnalyses::all();
102281ad6265SDimitry Andric }
102381ad6265SDimitry Andric
10240b57cec5SDimitry Andric char GlobalsAAWrapperPass::ID = 0;
10250b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(GlobalsAAWrapperPass, "globals-aa",
10260b57cec5SDimitry Andric "Globals Alias Analysis", false, true)
INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)10270b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
10280b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10290b57cec5SDimitry Andric INITIALIZE_PASS_END(GlobalsAAWrapperPass, "globals-aa",
10300b57cec5SDimitry Andric "Globals Alias Analysis", false, true)
10310b57cec5SDimitry Andric
10320b57cec5SDimitry Andric ModulePass *llvm::createGlobalsAAWrapperPass() {
10330b57cec5SDimitry Andric return new GlobalsAAWrapperPass();
10340b57cec5SDimitry Andric }
10350b57cec5SDimitry Andric
GlobalsAAWrapperPass()10360b57cec5SDimitry Andric GlobalsAAWrapperPass::GlobalsAAWrapperPass() : ModulePass(ID) {
10370b57cec5SDimitry Andric initializeGlobalsAAWrapperPassPass(*PassRegistry::getPassRegistry());
10380b57cec5SDimitry Andric }
10390b57cec5SDimitry Andric
runOnModule(Module & M)10400b57cec5SDimitry Andric bool GlobalsAAWrapperPass::runOnModule(Module &M) {
10418bcb0991SDimitry Andric auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
10428bcb0991SDimitry Andric return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
10438bcb0991SDimitry Andric };
10440b57cec5SDimitry Andric Result.reset(new GlobalsAAResult(GlobalsAAResult::analyzeModule(
10458bcb0991SDimitry Andric M, GetTLI, getAnalysis<CallGraphWrapperPass>().getCallGraph())));
10460b57cec5SDimitry Andric return false;
10470b57cec5SDimitry Andric }
10480b57cec5SDimitry Andric
doFinalization(Module & M)10490b57cec5SDimitry Andric bool GlobalsAAWrapperPass::doFinalization(Module &M) {
10500b57cec5SDimitry Andric Result.reset();
10510b57cec5SDimitry Andric return false;
10520b57cec5SDimitry Andric }
10530b57cec5SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const10540b57cec5SDimitry Andric void GlobalsAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10550b57cec5SDimitry Andric AU.setPreservesAll();
10560b57cec5SDimitry Andric AU.addRequired<CallGraphWrapperPass>();
10570b57cec5SDimitry Andric AU.addRequired<TargetLibraryInfoWrapperPass>();
10580b57cec5SDimitry Andric }
1059