GlobalsModRef.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This simple pass provides alias and mod/ref information for global values
  11. // that do not have their address taken, and keeps track of whether functions
  12. // read or write memory (are "pure"). For this simple (but very common) case,
  13. // we can provide pretty accurate and useful information.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Analysis/Passes.h"
  17. #include "llvm/ADT/SCCIterator.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/CallGraph.h"
  21. #include "llvm/Analysis/MemoryBuiltins.h"
  22. #include "llvm/Analysis/ValueTracking.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DerivedTypes.h"
  25. #include "llvm/IR/InstIterator.h"
  26. #include "llvm/IR/Instructions.h"
  27. #include "llvm/IR/IntrinsicInst.h"
  28. #include "llvm/IR/Module.h"
  29. #include "llvm/Pass.h"
  30. #include "llvm/Support/CommandLine.h"
  31. #include <set>
  32. using namespace llvm;
  33. #define DEBUG_TYPE "globalsmodref-aa"
  34. STATISTIC(NumNonAddrTakenGlobalVars,
  35. "Number of global vars without address taken");
  36. STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
  37. STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
  38. STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
  39. STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
  40. namespace {
  41. /// FunctionRecord - One instance of this structure is stored for every
  42. /// function in the program. Later, the entries for these functions are
  43. /// removed if the function is found to call an external function (in which
  44. /// case we know nothing about it.
  45. struct FunctionRecord {
  46. /// GlobalInfo - Maintain mod/ref info for all of the globals without
  47. /// addresses taken that are read or written (transitively) by this
  48. /// function.
  49. std::map<const GlobalValue *, unsigned> GlobalInfo;
  50. /// MayReadAnyGlobal - May read global variables, but it is not known which.
  51. bool MayReadAnyGlobal;
  52. unsigned getInfoForGlobal(const GlobalValue *GV) const {
  53. unsigned Effect = MayReadAnyGlobal ? AliasAnalysis::Ref : 0;
  54. std::map<const GlobalValue *, unsigned>::const_iterator I =
  55. GlobalInfo.find(GV);
  56. if (I != GlobalInfo.end())
  57. Effect |= I->second;
  58. return Effect;
  59. }
  60. /// FunctionEffect - Capture whether or not this function reads or writes to
  61. /// ANY memory. If not, we can do a lot of aggressive analysis on it.
  62. unsigned FunctionEffect;
  63. FunctionRecord() : MayReadAnyGlobal(false), FunctionEffect(0) {}
  64. };
  65. /// GlobalsModRef - The actual analysis pass.
  66. class GlobalsModRef : public ModulePass, public AliasAnalysis {
  67. /// NonAddressTakenGlobals - The globals that do not have their addresses
  68. /// taken.
  69. std::set<const GlobalValue *> NonAddressTakenGlobals;
  70. /// IndirectGlobals - The memory pointed to by this global is known to be
  71. /// 'owned' by the global.
  72. std::set<const GlobalValue *> IndirectGlobals;
  73. /// AllocsForIndirectGlobals - If an instruction allocates memory for an
  74. /// indirect global, this map indicates which one.
  75. std::map<const Value *, const GlobalValue *> AllocsForIndirectGlobals;
  76. /// FunctionInfo - For each function, keep track of what globals are
  77. /// modified or read.
  78. std::map<const Function *, FunctionRecord> FunctionInfo;
  79. public:
  80. static char ID;
  81. GlobalsModRef() : ModulePass(ID) {
  82. initializeGlobalsModRefPass(*PassRegistry::getPassRegistry());
  83. }
  84. bool runOnModule(Module &M) override {
  85. InitializeAliasAnalysis(this, &M.getDataLayout());
  86. // Find non-addr taken globals.
  87. AnalyzeGlobals(M);
  88. // Propagate on CG.
  89. AnalyzeCallGraph(getAnalysis<CallGraphWrapperPass>().getCallGraph(), M);
  90. return false;
  91. }
  92. void getAnalysisUsage(AnalysisUsage &AU) const override {
  93. AliasAnalysis::getAnalysisUsage(AU);
  94. AU.addRequired<CallGraphWrapperPass>();
  95. AU.setPreservesAll(); // Does not transform code
  96. }
  97. //------------------------------------------------
  98. // Implement the AliasAnalysis API
  99. //
  100. AliasResult alias(const MemoryLocation &LocA,
  101. const MemoryLocation &LocB) override;
  102. ModRefResult getModRefInfo(ImmutableCallSite CS,
  103. const MemoryLocation &Loc) override;
  104. ModRefResult getModRefInfo(ImmutableCallSite CS1,
  105. ImmutableCallSite CS2) override {
  106. return AliasAnalysis::getModRefInfo(CS1, CS2);
  107. }
  108. /// getModRefBehavior - Return the behavior of the specified function if
  109. /// called from the specified call site. The call site may be null in which
  110. /// case the most generic behavior of this function should be returned.
  111. ModRefBehavior getModRefBehavior(const Function *F) override {
  112. ModRefBehavior Min = UnknownModRefBehavior;
  113. if (FunctionRecord *FR = getFunctionInfo(F)) {
  114. if (FR->FunctionEffect == 0)
  115. Min = DoesNotAccessMemory;
  116. else if ((FR->FunctionEffect & Mod) == 0)
  117. Min = OnlyReadsMemory;
  118. }
  119. return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
  120. }
  121. /// getModRefBehavior - Return the behavior of the specified function if
  122. /// called from the specified call site. The call site may be null in which
  123. /// case the most generic behavior of this function should be returned.
  124. ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override {
  125. ModRefBehavior Min = UnknownModRefBehavior;
  126. if (const Function *F = CS.getCalledFunction())
  127. if (FunctionRecord *FR = getFunctionInfo(F)) {
  128. if (FR->FunctionEffect == 0)
  129. Min = DoesNotAccessMemory;
  130. else if ((FR->FunctionEffect & Mod) == 0)
  131. Min = OnlyReadsMemory;
  132. }
  133. return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
  134. }
  135. void deleteValue(Value *V) override;
  136. void addEscapingUse(Use &U) override;
  137. /// getAdjustedAnalysisPointer - This method is used when a pass implements
  138. /// an analysis interface through multiple inheritance. If needed, it
  139. /// should override this to adjust the this pointer as needed for the
  140. /// specified pass info.
  141. void *getAdjustedAnalysisPointer(AnalysisID PI) override {
  142. if (PI == &AliasAnalysis::ID)
  143. return (AliasAnalysis *)this;
  144. return this;
  145. }
  146. private:
  147. /// getFunctionInfo - Return the function info for the function, or null if
  148. /// we don't have anything useful to say about it.
  149. FunctionRecord *getFunctionInfo(const Function *F) {
  150. std::map<const Function *, FunctionRecord>::iterator I =
  151. FunctionInfo.find(F);
  152. if (I != FunctionInfo.end())
  153. return &I->second;
  154. return nullptr;
  155. }
  156. void AnalyzeGlobals(Module &M);
  157. void AnalyzeCallGraph(CallGraph &CG, Module &M);
  158. bool AnalyzeUsesOfPointer(Value *V, std::vector<Function *> &Readers,
  159. std::vector<Function *> &Writers,
  160. GlobalValue *OkayStoreDest = nullptr);
  161. bool AnalyzeIndirectGlobalMemory(GlobalValue *GV);
  162. };
  163. }
  164. char GlobalsModRef::ID = 0;
  165. INITIALIZE_AG_PASS_BEGIN(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
  166. "Simple mod/ref analysis for globals", false, true,
  167. false)
  168. INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
  169. INITIALIZE_AG_PASS_END(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
  170. "Simple mod/ref analysis for globals", false, true,
  171. false)
  172. Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
  173. /// AnalyzeGlobals - Scan through the users of all of the internal
  174. /// GlobalValue's in the program. If none of them have their "address taken"
  175. /// (really, their address passed to something nontrivial), record this fact,
  176. /// and record the functions that they are used directly in.
  177. void GlobalsModRef::AnalyzeGlobals(Module &M) {
  178. std::vector<Function *> Readers, Writers;
  179. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
  180. if (I->hasLocalLinkage()) {
  181. if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
  182. // Remember that we are tracking this global.
  183. NonAddressTakenGlobals.insert(I);
  184. ++NumNonAddrTakenFunctions;
  185. }
  186. Readers.clear();
  187. Writers.clear();
  188. }
  189. for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E;
  190. ++I)
  191. if (I->hasLocalLinkage()) {
  192. if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
  193. // Remember that we are tracking this global, and the mod/ref fns
  194. NonAddressTakenGlobals.insert(I);
  195. for (unsigned i = 0, e = Readers.size(); i != e; ++i)
  196. FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
  197. if (!I->isConstant()) // No need to keep track of writers to constants
  198. for (unsigned i = 0, e = Writers.size(); i != e; ++i)
  199. FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
  200. ++NumNonAddrTakenGlobalVars;
  201. // If this global holds a pointer type, see if it is an indirect global.
  202. if (I->getType()->getElementType()->isPointerTy() &&
  203. AnalyzeIndirectGlobalMemory(I))
  204. ++NumIndirectGlobalVars;
  205. }
  206. Readers.clear();
  207. Writers.clear();
  208. }
  209. }
  210. /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
  211. /// If this is used by anything complex (i.e., the address escapes), return
  212. /// true. Also, while we are at it, keep track of those functions that read and
  213. /// write to the value.
  214. ///
  215. /// If OkayStoreDest is non-null, stores into this global are allowed.
  216. bool GlobalsModRef::AnalyzeUsesOfPointer(Value *V,
  217. std::vector<Function *> &Readers,
  218. std::vector<Function *> &Writers,
  219. GlobalValue *OkayStoreDest) {
  220. if (!V->getType()->isPointerTy())
  221. return true;
  222. for (Use &U : V->uses()) {
  223. User *I = U.getUser();
  224. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  225. Readers.push_back(LI->getParent()->getParent());
  226. } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  227. if (V == SI->getOperand(1)) {
  228. Writers.push_back(SI->getParent()->getParent());
  229. } else if (SI->getOperand(1) != OkayStoreDest) {
  230. return true; // Storing the pointer
  231. }
  232. } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
  233. if (AnalyzeUsesOfPointer(I, Readers, Writers))
  234. return true;
  235. } else if (Operator::getOpcode(I) == Instruction::BitCast) {
  236. if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
  237. return true;
  238. } else if (auto CS = CallSite(I)) {
  239. // Make sure that this is just the function being called, not that it is
  240. // passing into the function.
  241. if (!CS.isCallee(&U)) {
  242. // Detect calls to free.
  243. if (isFreeCall(I, TLI))
  244. Writers.push_back(CS->getParent()->getParent());
  245. else
  246. return true; // Argument of an unknown call.
  247. }
  248. } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
  249. if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
  250. return true; // Allow comparison against null.
  251. } else {
  252. return true;
  253. }
  254. }
  255. return false;
  256. }
  257. /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
  258. /// which holds a pointer type. See if the global always points to non-aliased
  259. /// heap memory: that is, all initializers of the globals are allocations, and
  260. /// those allocations have no use other than initialization of the global.
  261. /// Further, all loads out of GV must directly use the memory, not store the
  262. /// pointer somewhere. If this is true, we consider the memory pointed to by
  263. /// GV to be owned by GV and can disambiguate other pointers from it.
  264. bool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
  265. // Keep track of values related to the allocation of the memory, f.e. the
  266. // value produced by the malloc call and any casts.
  267. std::vector<Value *> AllocRelatedValues;
  268. // Walk the user list of the global. If we find anything other than a direct
  269. // load or store, bail out.
  270. for (User *U : GV->users()) {
  271. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  272. // The pointer loaded from the global can only be used in simple ways:
  273. // we allow addressing of it and loading storing to it. We do *not* allow
  274. // storing the loaded pointer somewhere else or passing to a function.
  275. std::vector<Function *> ReadersWriters;
  276. if (AnalyzeUsesOfPointer(LI, ReadersWriters, ReadersWriters))
  277. return false; // Loaded pointer escapes.
  278. // TODO: Could try some IP mod/ref of the loaded pointer.
  279. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  280. // Storing the global itself.
  281. if (SI->getOperand(0) == GV)
  282. return false;
  283. // If storing the null pointer, ignore it.
  284. if (isa<ConstantPointerNull>(SI->getOperand(0)))
  285. continue;
  286. // Check the value being stored.
  287. Value *Ptr = GetUnderlyingObject(SI->getOperand(0),
  288. GV->getParent()->getDataLayout());
  289. if (!isAllocLikeFn(Ptr, TLI))
  290. return false; // Too hard to analyze.
  291. // Analyze all uses of the allocation. If any of them are used in a
  292. // non-simple way (e.g. stored to another global) bail out.
  293. std::vector<Function *> ReadersWriters;
  294. if (AnalyzeUsesOfPointer(Ptr, ReadersWriters, ReadersWriters, GV))
  295. return false; // Loaded pointer escapes.
  296. // Remember that this allocation is related to the indirect global.
  297. AllocRelatedValues.push_back(Ptr);
  298. } else {
  299. // Something complex, bail out.
  300. return false;
  301. }
  302. }
  303. // Okay, this is an indirect global. Remember all of the allocations for
  304. // this global in AllocsForIndirectGlobals.
  305. while (!AllocRelatedValues.empty()) {
  306. AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
  307. AllocRelatedValues.pop_back();
  308. }
  309. IndirectGlobals.insert(GV);
  310. return true;
  311. }
  312. /// AnalyzeCallGraph - At this point, we know the functions where globals are
  313. /// immediately stored to and read from. Propagate this information up the call
  314. /// graph to all callers and compute the mod/ref info for all memory for each
  315. /// function.
  316. void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
  317. // We do a bottom-up SCC traversal of the call graph. In other words, we
  318. // visit all callees before callers (leaf-first).
  319. for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
  320. const std::vector<CallGraphNode *> &SCC = *I;
  321. assert(!SCC.empty() && "SCC with no functions?");
  322. if (!SCC[0]->getFunction()) {
  323. // Calls externally - can't say anything useful. Remove any existing
  324. // function records (may have been created when scanning globals).
  325. for (unsigned i = 0, e = SCC.size(); i != e; ++i)
  326. FunctionInfo.erase(SCC[i]->getFunction());
  327. continue;
  328. }
  329. FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
  330. bool KnowNothing = false;
  331. unsigned FunctionEffect = 0;
  332. // Collect the mod/ref properties due to called functions. We only compute
  333. // one mod-ref set.
  334. for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
  335. Function *F = SCC[i]->getFunction();
  336. if (!F) {
  337. KnowNothing = true;
  338. break;
  339. }
  340. if (F->isDeclaration()) {
  341. // Try to get mod/ref behaviour from function attributes.
  342. if (F->doesNotAccessMemory()) {
  343. // Can't do better than that!
  344. } else if (F->onlyReadsMemory()) {
  345. FunctionEffect |= Ref;
  346. if (!F->isIntrinsic())
  347. // This function might call back into the module and read a global -
  348. // consider every global as possibly being read by this function.
  349. FR.MayReadAnyGlobal = true;
  350. } else {
  351. FunctionEffect |= ModRef;
  352. // Can't say anything useful unless it's an intrinsic - they don't
  353. // read or write global variables of the kind considered here.
  354. KnowNothing = !F->isIntrinsic();
  355. }
  356. continue;
  357. }
  358. for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
  359. CI != E && !KnowNothing; ++CI)
  360. if (Function *Callee = CI->second->getFunction()) {
  361. if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
  362. // Propagate function effect up.
  363. FunctionEffect |= CalleeFR->FunctionEffect;
  364. // Incorporate callee's effects on globals into our info.
  365. for (const auto &G : CalleeFR->GlobalInfo)
  366. FR.GlobalInfo[G.first] |= G.second;
  367. FR.MayReadAnyGlobal |= CalleeFR->MayReadAnyGlobal;
  368. } else {
  369. // Can't say anything about it. However, if it is inside our SCC,
  370. // then nothing needs to be done.
  371. CallGraphNode *CalleeNode = CG[Callee];
  372. if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end())
  373. KnowNothing = true;
  374. }
  375. } else {
  376. KnowNothing = true;
  377. }
  378. }
  379. // If we can't say anything useful about this SCC, remove all SCC functions
  380. // from the FunctionInfo map.
  381. if (KnowNothing) {
  382. for (unsigned i = 0, e = SCC.size(); i != e; ++i)
  383. FunctionInfo.erase(SCC[i]->getFunction());
  384. continue;
  385. }
  386. // Scan the function bodies for explicit loads or stores.
  387. for (auto *Node : SCC) {
  388. if (FunctionEffect == ModRef)
  389. break; // The mod/ref lattice saturates here.
  390. for (Instruction &I : inst_range(Node->getFunction())) {
  391. if (FunctionEffect == ModRef)
  392. break; // The mod/ref lattice saturates here.
  393. // We handle calls specially because the graph-relevant aspects are
  394. // handled above.
  395. if (auto CS = CallSite(&I)) {
  396. if (isAllocationFn(&I, TLI) || isFreeCall(&I, TLI)) {
  397. // FIXME: It is completely unclear why this is necessary and not
  398. // handled by the above graph code.
  399. FunctionEffect |= ModRef;
  400. } else if (Function *Callee = CS.getCalledFunction()) {
  401. // The callgraph doesn't include intrinsic calls.
  402. if (Callee->isIntrinsic()) {
  403. ModRefBehavior Behaviour =
  404. AliasAnalysis::getModRefBehavior(Callee);
  405. FunctionEffect |= (Behaviour & ModRef);
  406. }
  407. }
  408. continue;
  409. }
  410. // All non-call instructions we use the primary predicates for whether
  411. // thay read or write memory.
  412. if (I.mayReadFromMemory())
  413. FunctionEffect |= Ref;
  414. if (I.mayWriteToMemory())
  415. FunctionEffect |= Mod;
  416. }
  417. }
  418. if ((FunctionEffect & Mod) == 0)
  419. ++NumReadMemFunctions;
  420. if (FunctionEffect == 0)
  421. ++NumNoMemFunctions;
  422. FR.FunctionEffect = FunctionEffect;
  423. // Finally, now that we know the full effect on this SCC, clone the
  424. // information to each function in the SCC.
  425. for (unsigned i = 1, e = SCC.size(); i != e; ++i)
  426. FunctionInfo[SCC[i]->getFunction()] = FR;
  427. }
  428. }
  429. /// alias - If one of the pointers is to a global that we are tracking, and the
  430. /// other is some random pointer, we know there cannot be an alias, because the
  431. /// address of the global isn't taken.
  432. AliasResult GlobalsModRef::alias(const MemoryLocation &LocA,
  433. const MemoryLocation &LocB) {
  434. // Get the base object these pointers point to.
  435. const Value *UV1 = GetUnderlyingObject(LocA.Ptr, *DL);
  436. const Value *UV2 = GetUnderlyingObject(LocB.Ptr, *DL);
  437. // If either of the underlying values is a global, they may be non-addr-taken
  438. // globals, which we can answer queries about.
  439. const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
  440. const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
  441. if (GV1 || GV2) {
  442. // If the global's address is taken, pretend we don't know it's a pointer to
  443. // the global.
  444. if (GV1 && !NonAddressTakenGlobals.count(GV1))
  445. GV1 = nullptr;
  446. if (GV2 && !NonAddressTakenGlobals.count(GV2))
  447. GV2 = nullptr;
  448. // If the two pointers are derived from two different non-addr-taken
  449. // globals, or if one is and the other isn't, we know these can't alias.
  450. if ((GV1 || GV2) && GV1 != GV2)
  451. return NoAlias;
  452. // Otherwise if they are both derived from the same addr-taken global, we
  453. // can't know the two accesses don't overlap.
  454. }
  455. // These pointers may be based on the memory owned by an indirect global. If
  456. // so, we may be able to handle this. First check to see if the base pointer
  457. // is a direct load from an indirect global.
  458. GV1 = GV2 = nullptr;
  459. if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
  460. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
  461. if (IndirectGlobals.count(GV))
  462. GV1 = GV;
  463. if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
  464. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
  465. if (IndirectGlobals.count(GV))
  466. GV2 = GV;
  467. // These pointers may also be from an allocation for the indirect global. If
  468. // so, also handle them.
  469. if (AllocsForIndirectGlobals.count(UV1))
  470. GV1 = AllocsForIndirectGlobals[UV1];
  471. if (AllocsForIndirectGlobals.count(UV2))
  472. GV2 = AllocsForIndirectGlobals[UV2];
  473. // Now that we know whether the two pointers are related to indirect globals,
  474. // use this to disambiguate the pointers. If either pointer is based on an
  475. // indirect global and if they are not both based on the same indirect global,
  476. // they cannot alias.
  477. if ((GV1 || GV2) && GV1 != GV2)
  478. return NoAlias;
  479. return AliasAnalysis::alias(LocA, LocB);
  480. }
  481. AliasAnalysis::ModRefResult
  482. GlobalsModRef::getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc) {
  483. unsigned Known = ModRef;
  484. // If we are asking for mod/ref info of a direct call with a pointer to a
  485. // global we are tracking, return information if we have it.
  486. const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
  487. if (const GlobalValue *GV =
  488. dyn_cast<GlobalValue>(GetUnderlyingObject(Loc.Ptr, DL)))
  489. if (GV->hasLocalLinkage())
  490. if (const Function *F = CS.getCalledFunction())
  491. if (NonAddressTakenGlobals.count(GV))
  492. if (const FunctionRecord *FR = getFunctionInfo(F))
  493. Known = FR->getInfoForGlobal(GV);
  494. if (Known == NoModRef)
  495. return NoModRef; // No need to query other mod/ref analyses
  496. return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, Loc));
  497. }
  498. //===----------------------------------------------------------------------===//
  499. // Methods to update the analysis as a result of the client transformation.
  500. //
  501. void GlobalsModRef::deleteValue(Value *V) {
  502. if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  503. if (NonAddressTakenGlobals.erase(GV)) {
  504. // This global might be an indirect global. If so, remove it and remove
  505. // any AllocRelatedValues for it.
  506. if (IndirectGlobals.erase(GV)) {
  507. // Remove any entries in AllocsForIndirectGlobals for this global.
  508. for (std::map<const Value *, const GlobalValue *>::iterator
  509. I = AllocsForIndirectGlobals.begin(),
  510. E = AllocsForIndirectGlobals.end();
  511. I != E;) {
  512. if (I->second == GV) {
  513. AllocsForIndirectGlobals.erase(I++);
  514. } else {
  515. ++I;
  516. }
  517. }
  518. }
  519. }
  520. }
  521. // Otherwise, if this is an allocation related to an indirect global, remove
  522. // it.
  523. AllocsForIndirectGlobals.erase(V);
  524. AliasAnalysis::deleteValue(V);
  525. }
  526. void GlobalsModRef::addEscapingUse(Use &U) {
  527. // For the purposes of this analysis, it is conservatively correct to treat
  528. // a newly escaping value equivalently to a deleted one. We could perhaps
  529. // be more precise by processing the new use and attempting to update our
  530. // saved analysis results to accommodate it.
  531. deleteValue(U);
  532. AliasAnalysis::addEscapingUse(U);
  533. }