BasicAliasAnalysis.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- BasicAliasAnalysis.h - Stateless, local Alias Analysis ---*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. /// \file
  14. /// This is the interface for LLVM's primary stateless and local alias analysis.
  15. ///
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_ANALYSIS_BASICALIASANALYSIS_H
  18. #define LLVM_ANALYSIS_BASICALIASANALYSIS_H
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/Optional.h"
  21. #include "llvm/ADT/SmallPtrSet.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/Analysis/AliasAnalysis.h"
  24. #include "llvm/IR/PassManager.h"
  25. #include "llvm/Pass.h"
  26. #include <algorithm>
  27. #include <cstdint>
  28. #include <memory>
  29. #include <utility>
  30. namespace llvm {
  31. struct AAMDNodes;
  32. class APInt;
  33. class AssumptionCache;
  34. class BasicBlock;
  35. class DataLayout;
  36. class DominatorTree;
  37. class Function;
  38. class GEPOperator;
  39. class LoopInfo;
  40. class PHINode;
  41. class SelectInst;
  42. class TargetLibraryInfo;
  43. class PhiValues;
  44. class Value;
  45. /// This is the AA result object for the basic, local, and stateless alias
  46. /// analysis. It implements the AA query interface in an entirely stateless
  47. /// manner. As one consequence, it is never invalidated due to IR changes.
  48. /// While it does retain some storage, that is used as an optimization and not
  49. /// to preserve information from query to query. However it does retain handles
  50. /// to various other analyses and must be recomputed when those analyses are.
  51. class BasicAAResult : public AAResultBase<BasicAAResult> {
  52. friend AAResultBase<BasicAAResult>;
  53. const DataLayout &DL;
  54. const Function &F;
  55. const TargetLibraryInfo &TLI;
  56. AssumptionCache &AC;
  57. DominatorTree *DT;
  58. LoopInfo *LI;
  59. PhiValues *PV;
  60. public:
  61. BasicAAResult(const DataLayout &DL, const Function &F,
  62. const TargetLibraryInfo &TLI, AssumptionCache &AC,
  63. DominatorTree *DT = nullptr, LoopInfo *LI = nullptr,
  64. PhiValues *PV = nullptr)
  65. : AAResultBase(), DL(DL), F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), PV(PV)
  66. {}
  67. BasicAAResult(const BasicAAResult &Arg)
  68. : AAResultBase(Arg), DL(Arg.DL), F(Arg.F), TLI(Arg.TLI), AC(Arg.AC),
  69. DT(Arg.DT), LI(Arg.LI), PV(Arg.PV) {}
  70. BasicAAResult(BasicAAResult &&Arg)
  71. : AAResultBase(std::move(Arg)), DL(Arg.DL), F(Arg.F), TLI(Arg.TLI),
  72. AC(Arg.AC), DT(Arg.DT), LI(Arg.LI), PV(Arg.PV) {}
  73. /// Handle invalidation events in the new pass manager.
  74. bool invalidate(Function &Fn, const PreservedAnalyses &PA,
  75. FunctionAnalysisManager::Invalidator &Inv);
  76. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
  77. AAQueryInfo &AAQI);
  78. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
  79. AAQueryInfo &AAQI);
  80. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  81. AAQueryInfo &AAQI);
  82. /// Chases pointers until we find a (constant global) or not.
  83. bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  84. bool OrLocal);
  85. /// Get the location associated with a pointer argument of a callsite.
  86. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx);
  87. /// Returns the behavior when calling the given call site.
  88. FunctionModRefBehavior getModRefBehavior(const CallBase *Call);
  89. /// Returns the behavior when calling the given function. For use when the
  90. /// call site is not known.
  91. FunctionModRefBehavior getModRefBehavior(const Function *Fn);
  92. private:
  93. // A linear transformation of a Value; this class represents ZExt(SExt(V,
  94. // SExtBits), ZExtBits) * Scale + Offset.
  95. struct VariableGEPIndex {
  96. // An opaque Value - we can't decompose this further.
  97. const Value *V;
  98. // We need to track what extensions we've done as we consider the same Value
  99. // with different extensions as different variables in a GEP's linear
  100. // expression;
  101. // e.g.: if V == -1, then sext(x) != zext(x).
  102. unsigned ZExtBits;
  103. unsigned SExtBits;
  104. APInt Scale;
  105. // Context instruction to use when querying information about this index.
  106. const Instruction *CxtI;
  107. bool operator==(const VariableGEPIndex &Other) const {
  108. return V == Other.V && ZExtBits == Other.ZExtBits &&
  109. SExtBits == Other.SExtBits && Scale == Other.Scale;
  110. }
  111. bool operator!=(const VariableGEPIndex &Other) const {
  112. return !operator==(Other);
  113. }
  114. void dump() const {
  115. print(dbgs());
  116. dbgs() << "\n";
  117. }
  118. void print(raw_ostream &OS) const {
  119. OS << "(V=" << V->getName()
  120. << ", zextbits=" << ZExtBits
  121. << ", sextbits=" << SExtBits
  122. << ", scale=" << Scale << ")";
  123. }
  124. };
  125. // Represents the internal structure of a GEP, decomposed into a base pointer,
  126. // constant offsets, and variable scaled indices.
  127. struct DecomposedGEP {
  128. // Base pointer of the GEP
  129. const Value *Base;
  130. // Total constant offset from base.
  131. APInt Offset;
  132. // Scaled variable (non-constant) indices.
  133. SmallVector<VariableGEPIndex, 4> VarIndices;
  134. // Is GEP index scale compile-time constant.
  135. bool HasCompileTimeConstantScale;
  136. void dump() const {
  137. print(dbgs());
  138. dbgs() << "\n";
  139. }
  140. void print(raw_ostream &OS) const {
  141. OS << "(DecomposedGEP Base=" << Base->getName()
  142. << ", Offset=" << Offset
  143. << ", VarIndices=[";
  144. for (size_t i = 0; i < VarIndices.size(); i++) {
  145. if (i != 0)
  146. OS << ", ";
  147. VarIndices[i].print(OS);
  148. }
  149. OS << "], HasCompileTimeConstantScale=" << HasCompileTimeConstantScale
  150. << ")";
  151. }
  152. };
  153. /// Tracks phi nodes we have visited.
  154. ///
  155. /// When interpret "Value" pointer equality as value equality we need to make
  156. /// sure that the "Value" is not part of a cycle. Otherwise, two uses could
  157. /// come from different "iterations" of a cycle and see different values for
  158. /// the same "Value" pointer.
  159. ///
  160. /// The following example shows the problem:
  161. /// %p = phi(%alloca1, %addr2)
  162. /// %l = load %ptr
  163. /// %addr1 = gep, %alloca2, 0, %l
  164. /// %addr2 = gep %alloca2, 0, (%l + 1)
  165. /// alias(%p, %addr1) -> MayAlias !
  166. /// store %l, ...
  167. SmallPtrSet<const BasicBlock *, 8> VisitedPhiBBs;
  168. /// Tracks instructions visited by pointsToConstantMemory.
  169. SmallPtrSet<const Value *, 16> Visited;
  170. static const Value *
  171. GetLinearExpression(const Value *V, APInt &Scale, APInt &Offset,
  172. unsigned &ZExtBits, unsigned &SExtBits,
  173. const DataLayout &DL, unsigned Depth, AssumptionCache *AC,
  174. DominatorTree *DT, bool &NSW, bool &NUW);
  175. static DecomposedGEP
  176. DecomposeGEPExpression(const Value *V, const DataLayout &DL,
  177. AssumptionCache *AC, DominatorTree *DT);
  178. static bool isGEPBaseAtNegativeOffset(const GEPOperator *GEPOp,
  179. const DecomposedGEP &DecompGEP, const DecomposedGEP &DecompObject,
  180. LocationSize ObjectAccessSize);
  181. /// A Heuristic for aliasGEP that searches for a constant offset
  182. /// between the variables.
  183. ///
  184. /// GetLinearExpression has some limitations, as generally zext(%x + 1)
  185. /// != zext(%x) + zext(1) if the arithmetic overflows. GetLinearExpression
  186. /// will therefore conservatively refuse to decompose these expressions.
  187. /// However, we know that, for all %x, zext(%x) != zext(%x + 1), even if
  188. /// the addition overflows.
  189. bool
  190. constantOffsetHeuristic(const SmallVectorImpl<VariableGEPIndex> &VarIndices,
  191. LocationSize V1Size, LocationSize V2Size,
  192. const APInt &BaseOffset, AssumptionCache *AC,
  193. DominatorTree *DT);
  194. bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
  195. void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
  196. const SmallVectorImpl<VariableGEPIndex> &Src);
  197. AliasResult aliasGEP(const GEPOperator *V1, LocationSize V1Size,
  198. const AAMDNodes &V1AAInfo, const Value *V2,
  199. LocationSize V2Size, const AAMDNodes &V2AAInfo,
  200. const Value *UnderlyingV1, const Value *UnderlyingV2,
  201. AAQueryInfo &AAQI);
  202. AliasResult aliasPHI(const PHINode *PN, LocationSize PNSize,
  203. const AAMDNodes &PNAAInfo, const Value *V2,
  204. LocationSize V2Size, const AAMDNodes &V2AAInfo,
  205. AAQueryInfo &AAQI);
  206. AliasResult aliasSelect(const SelectInst *SI, LocationSize SISize,
  207. const AAMDNodes &SIAAInfo, const Value *V2,
  208. LocationSize V2Size, const AAMDNodes &V2AAInfo,
  209. AAQueryInfo &AAQI);
  210. AliasResult aliasCheck(const Value *V1, LocationSize V1Size,
  211. const AAMDNodes &V1AATag, const Value *V2,
  212. LocationSize V2Size, const AAMDNodes &V2AATag,
  213. AAQueryInfo &AAQI);
  214. AliasResult aliasCheckRecursive(const Value *V1, LocationSize V1Size,
  215. const AAMDNodes &V1AATag, const Value *V2,
  216. LocationSize V2Size, const AAMDNodes &V2AATag,
  217. AAQueryInfo &AAQI, const Value *O1,
  218. const Value *O2);
  219. };
  220. /// Analysis pass providing a never-invalidated alias analysis result.
  221. class BasicAA : public AnalysisInfoMixin<BasicAA> {
  222. friend AnalysisInfoMixin<BasicAA>;
  223. static AnalysisKey Key;
  224. public:
  225. using Result = BasicAAResult;
  226. BasicAAResult run(Function &F, FunctionAnalysisManager &AM);
  227. };
  228. /// Legacy wrapper pass to provide the BasicAAResult object.
  229. class BasicAAWrapperPass : public FunctionPass {
  230. std::unique_ptr<BasicAAResult> Result;
  231. virtual void anchor();
  232. public:
  233. static char ID;
  234. BasicAAWrapperPass();
  235. BasicAAResult &getResult() { return *Result; }
  236. const BasicAAResult &getResult() const { return *Result; }
  237. bool runOnFunction(Function &F) override;
  238. void getAnalysisUsage(AnalysisUsage &AU) const override;
  239. };
  240. FunctionPass *createBasicAAWrapperPass();
  241. /// A helper for the legacy pass manager to create a \c BasicAAResult object
  242. /// populated to the best of our ability for a particular function when inside
  243. /// of a \c ModulePass or a \c CallGraphSCCPass.
  244. BasicAAResult createLegacyPMBasicAAResult(Pass &P, Function &F);
  245. /// This class is a functor to be used in legacy module or SCC passes for
  246. /// computing AA results for a function. We store the results in fields so that
  247. /// they live long enough to be queried, but we re-use them each time.
  248. class LegacyAARGetter {
  249. Pass &P;
  250. Optional<BasicAAResult> BAR;
  251. Optional<AAResults> AAR;
  252. public:
  253. LegacyAARGetter(Pass &P) : P(P) {}
  254. AAResults &operator()(Function &F) {
  255. BAR.emplace(createLegacyPMBasicAAResult(P, F));
  256. AAR.emplace(createLegacyPMAAResults(P, F, *BAR));
  257. return *AAR;
  258. }
  259. };
  260. } // end namespace llvm
  261. #endif // LLVM_ANALYSIS_BASICALIASANALYSIS_H
  262. #ifdef __GNUC__
  263. #pragma GCC diagnostic pop
  264. #endif