AliasAnalysis.h 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Analysis/AliasAnalysis.h - Alias Analysis Interface -*- 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. //
  14. // This file defines the generic AliasAnalysis interface, which is used as the
  15. // common interface used by all clients of alias analysis information, and
  16. // implemented by all alias analysis implementations. Mod/Ref information is
  17. // also captured by this interface.
  18. //
  19. // Implementations of this interface must implement the various virtual methods,
  20. // which automatically provides functionality for the entire suite of client
  21. // APIs.
  22. //
  23. // This API identifies memory regions with the MemoryLocation class. The pointer
  24. // component specifies the base memory address of the region. The Size specifies
  25. // the maximum size (in address units) of the memory region, or
  26. // MemoryLocation::UnknownSize if the size is not known. The TBAA tag
  27. // identifies the "type" of the memory reference; see the
  28. // TypeBasedAliasAnalysis class for details.
  29. //
  30. // Some non-obvious details include:
  31. // - Pointers that point to two completely different objects in memory never
  32. // alias, regardless of the value of the Size component.
  33. // - NoAlias doesn't imply inequal pointers. The most obvious example of this
  34. // is two pointers to constant memory. Even if they are equal, constant
  35. // memory is never stored to, so there will never be any dependencies.
  36. // In this and other situations, the pointers may be both NoAlias and
  37. // MustAlias at the same time. The current API can only return one result,
  38. // though this is rarely a problem in practice.
  39. //
  40. //===----------------------------------------------------------------------===//
  41. #ifndef LLVM_ANALYSIS_ALIASANALYSIS_H
  42. #define LLVM_ANALYSIS_ALIASANALYSIS_H
  43. #include "llvm/ADT/DenseMap.h"
  44. #include "llvm/ADT/Sequence.h"
  45. #include "llvm/ADT/SmallVector.h"
  46. #include "llvm/Analysis/MemoryLocation.h"
  47. #include "llvm/IR/PassManager.h"
  48. #include "llvm/Pass.h"
  49. #include "llvm/Support/ModRef.h"
  50. #include <cstdint>
  51. #include <functional>
  52. #include <memory>
  53. #include <optional>
  54. #include <vector>
  55. namespace llvm {
  56. class AnalysisUsage;
  57. class AtomicCmpXchgInst;
  58. class BasicAAResult;
  59. class BasicBlock;
  60. class CatchPadInst;
  61. class CatchReturnInst;
  62. class DominatorTree;
  63. class FenceInst;
  64. class Function;
  65. class LoopInfo;
  66. class PreservedAnalyses;
  67. class TargetLibraryInfo;
  68. class Value;
  69. template <typename> class SmallPtrSetImpl;
  70. /// The possible results of an alias query.
  71. ///
  72. /// These results are always computed between two MemoryLocation objects as
  73. /// a query to some alias analysis.
  74. ///
  75. /// Note that these are unscoped enumerations because we would like to support
  76. /// implicitly testing a result for the existence of any possible aliasing with
  77. /// a conversion to bool, but an "enum class" doesn't support this. The
  78. /// canonical names from the literature are suffixed and unique anyways, and so
  79. /// they serve as global constants in LLVM for these results.
  80. ///
  81. /// See docs/AliasAnalysis.html for more information on the specific meanings
  82. /// of these values.
  83. class AliasResult {
  84. private:
  85. static const int OffsetBits = 23;
  86. static const int AliasBits = 8;
  87. static_assert(AliasBits + 1 + OffsetBits <= 32,
  88. "AliasResult size is intended to be 4 bytes!");
  89. unsigned int Alias : AliasBits;
  90. unsigned int HasOffset : 1;
  91. signed int Offset : OffsetBits;
  92. public:
  93. enum Kind : uint8_t {
  94. /// The two locations do not alias at all.
  95. ///
  96. /// This value is arranged to convert to false, while all other values
  97. /// convert to true. This allows a boolean context to convert the result to
  98. /// a binary flag indicating whether there is the possibility of aliasing.
  99. NoAlias = 0,
  100. /// The two locations may or may not alias. This is the least precise
  101. /// result.
  102. MayAlias,
  103. /// The two locations alias, but only due to a partial overlap.
  104. PartialAlias,
  105. /// The two locations precisely alias each other.
  106. MustAlias,
  107. };
  108. static_assert(MustAlias < (1 << AliasBits),
  109. "Not enough bit field size for the enum!");
  110. explicit AliasResult() = delete;
  111. constexpr AliasResult(const Kind &Alias)
  112. : Alias(Alias), HasOffset(false), Offset(0) {}
  113. operator Kind() const { return static_cast<Kind>(Alias); }
  114. constexpr bool hasOffset() const { return HasOffset; }
  115. constexpr int32_t getOffset() const {
  116. assert(HasOffset && "No offset!");
  117. return Offset;
  118. }
  119. void setOffset(int32_t NewOffset) {
  120. if (isInt<OffsetBits>(NewOffset)) {
  121. HasOffset = true;
  122. Offset = NewOffset;
  123. }
  124. }
  125. /// Helper for processing AliasResult for swapped memory location pairs.
  126. void swap(bool DoSwap = true) {
  127. if (DoSwap && hasOffset())
  128. setOffset(-getOffset());
  129. }
  130. };
  131. static_assert(sizeof(AliasResult) == 4,
  132. "AliasResult size is intended to be 4 bytes!");
  133. /// << operator for AliasResult.
  134. raw_ostream &operator<<(raw_ostream &OS, AliasResult AR);
  135. /// Virtual base class for providers of capture information.
  136. struct CaptureInfo {
  137. virtual ~CaptureInfo() = 0;
  138. virtual bool isNotCapturedBeforeOrAt(const Value *Object,
  139. const Instruction *I) = 0;
  140. };
  141. /// Context-free CaptureInfo provider, which computes and caches whether an
  142. /// object is captured in the function at all, but does not distinguish whether
  143. /// it was captured before or after the context instruction.
  144. class SimpleCaptureInfo final : public CaptureInfo {
  145. SmallDenseMap<const Value *, bool, 8> IsCapturedCache;
  146. public:
  147. bool isNotCapturedBeforeOrAt(const Value *Object,
  148. const Instruction *I) override;
  149. };
  150. /// Context-sensitive CaptureInfo provider, which computes and caches the
  151. /// earliest common dominator closure of all captures. It provides a good
  152. /// approximation to a precise "captures before" analysis.
  153. class EarliestEscapeInfo final : public CaptureInfo {
  154. DominatorTree &DT;
  155. const LoopInfo &LI;
  156. /// Map from identified local object to an instruction before which it does
  157. /// not escape, or nullptr if it never escapes. The "earliest" instruction
  158. /// may be a conservative approximation, e.g. the first instruction in the
  159. /// function is always a legal choice.
  160. DenseMap<const Value *, Instruction *> EarliestEscapes;
  161. /// Reverse map from instruction to the objects it is the earliest escape for.
  162. /// This is used for cache invalidation purposes.
  163. DenseMap<Instruction *, TinyPtrVector<const Value *>> Inst2Obj;
  164. const SmallPtrSetImpl<const Value *> &EphValues;
  165. public:
  166. EarliestEscapeInfo(DominatorTree &DT, const LoopInfo &LI,
  167. const SmallPtrSetImpl<const Value *> &EphValues)
  168. : DT(DT), LI(LI), EphValues(EphValues) {}
  169. bool isNotCapturedBeforeOrAt(const Value *Object,
  170. const Instruction *I) override;
  171. void removeInstruction(Instruction *I);
  172. };
  173. /// Cache key for BasicAA results. It only includes the pointer and size from
  174. /// MemoryLocation, as BasicAA is AATags independent. Additionally, it includes
  175. /// the value of MayBeCrossIteration, which may affect BasicAA results.
  176. struct AACacheLoc {
  177. using PtrTy = PointerIntPair<const Value *, 1, bool>;
  178. PtrTy Ptr;
  179. LocationSize Size;
  180. AACacheLoc(PtrTy Ptr, LocationSize Size) : Ptr(Ptr), Size(Size) {}
  181. AACacheLoc(const Value *Ptr, LocationSize Size, bool MayBeCrossIteration)
  182. : Ptr(Ptr, MayBeCrossIteration), Size(Size) {}
  183. };
  184. template <> struct DenseMapInfo<AACacheLoc> {
  185. static inline AACacheLoc getEmptyKey() {
  186. return {DenseMapInfo<AACacheLoc::PtrTy>::getEmptyKey(),
  187. DenseMapInfo<LocationSize>::getEmptyKey()};
  188. }
  189. static inline AACacheLoc getTombstoneKey() {
  190. return {DenseMapInfo<AACacheLoc::PtrTy>::getTombstoneKey(),
  191. DenseMapInfo<LocationSize>::getTombstoneKey()};
  192. }
  193. static unsigned getHashValue(const AACacheLoc &Val) {
  194. return DenseMapInfo<AACacheLoc::PtrTy>::getHashValue(Val.Ptr) ^
  195. DenseMapInfo<LocationSize>::getHashValue(Val.Size);
  196. }
  197. static bool isEqual(const AACacheLoc &LHS, const AACacheLoc &RHS) {
  198. return LHS.Ptr == RHS.Ptr && LHS.Size == RHS.Size;
  199. }
  200. };
  201. class AAResults;
  202. /// This class stores info we want to provide to or retain within an alias
  203. /// query. By default, the root query is stateless and starts with a freshly
  204. /// constructed info object. Specific alias analyses can use this query info to
  205. /// store per-query state that is important for recursive or nested queries to
  206. /// avoid recomputing. To enable preserving this state across multiple queries
  207. /// where safe (due to the IR not changing), use a `BatchAAResults` wrapper.
  208. /// The information stored in an `AAQueryInfo` is currently limitted to the
  209. /// caches used by BasicAA, but can further be extended to fit other AA needs.
  210. class AAQueryInfo {
  211. public:
  212. using LocPair = std::pair<AACacheLoc, AACacheLoc>;
  213. struct CacheEntry {
  214. AliasResult Result;
  215. /// Number of times a NoAlias assumption has been used.
  216. /// 0 for assumptions that have not been used, -1 for definitive results.
  217. int NumAssumptionUses;
  218. /// Whether this is a definitive (non-assumption) result.
  219. bool isDefinitive() const { return NumAssumptionUses < 0; }
  220. };
  221. // Alias analysis result aggregration using which this query is performed.
  222. // Can be used to perform recursive queries.
  223. AAResults &AAR;
  224. using AliasCacheT = SmallDenseMap<LocPair, CacheEntry, 8>;
  225. AliasCacheT AliasCache;
  226. CaptureInfo *CI;
  227. /// Query depth used to distinguish recursive queries.
  228. unsigned Depth = 0;
  229. /// How many active NoAlias assumption uses there are.
  230. int NumAssumptionUses = 0;
  231. /// Location pairs for which an assumption based result is currently stored.
  232. /// Used to remove all potentially incorrect results from the cache if an
  233. /// assumption is disproven.
  234. SmallVector<AAQueryInfo::LocPair, 4> AssumptionBasedResults;
  235. /// Tracks whether the accesses may be on different cycle iterations.
  236. ///
  237. /// When interpret "Value" pointer equality as value equality we need to make
  238. /// sure that the "Value" is not part of a cycle. Otherwise, two uses could
  239. /// come from different "iterations" of a cycle and see different values for
  240. /// the same "Value" pointer.
  241. ///
  242. /// The following example shows the problem:
  243. /// %p = phi(%alloca1, %addr2)
  244. /// %l = load %ptr
  245. /// %addr1 = gep, %alloca2, 0, %l
  246. /// %addr2 = gep %alloca2, 0, (%l + 1)
  247. /// alias(%p, %addr1) -> MayAlias !
  248. /// store %l, ...
  249. bool MayBeCrossIteration = false;
  250. AAQueryInfo(AAResults &AAR, CaptureInfo *CI) : AAR(AAR), CI(CI) {}
  251. };
  252. /// AAQueryInfo that uses SimpleCaptureInfo.
  253. class SimpleAAQueryInfo : public AAQueryInfo {
  254. SimpleCaptureInfo CI;
  255. public:
  256. SimpleAAQueryInfo(AAResults &AAR) : AAQueryInfo(AAR, &CI) {}
  257. };
  258. class BatchAAResults;
  259. class AAResults {
  260. public:
  261. // Make these results default constructable and movable. We have to spell
  262. // these out because MSVC won't synthesize them.
  263. AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {}
  264. AAResults(AAResults &&Arg);
  265. ~AAResults();
  266. /// Register a specific AA result.
  267. template <typename AAResultT> void addAAResult(AAResultT &AAResult) {
  268. // FIXME: We should use a much lighter weight system than the usual
  269. // polymorphic pattern because we don't own AAResult. It should
  270. // ideally involve two pointers and no separate allocation.
  271. AAs.emplace_back(new Model<AAResultT>(AAResult, *this));
  272. }
  273. /// Register a function analysis ID that the results aggregation depends on.
  274. ///
  275. /// This is used in the new pass manager to implement the invalidation logic
  276. /// where we must invalidate the results aggregation if any of our component
  277. /// analyses become invalid.
  278. void addAADependencyID(AnalysisKey *ID) { AADeps.push_back(ID); }
  279. /// Handle invalidation events in the new pass manager.
  280. ///
  281. /// The aggregation is invalidated if any of the underlying analyses is
  282. /// invalidated.
  283. bool invalidate(Function &F, const PreservedAnalyses &PA,
  284. FunctionAnalysisManager::Invalidator &Inv);
  285. //===--------------------------------------------------------------------===//
  286. /// \name Alias Queries
  287. /// @{
  288. /// The main low level interface to the alias analysis implementation.
  289. /// Returns an AliasResult indicating whether the two pointers are aliased to
  290. /// each other. This is the interface that must be implemented by specific
  291. /// alias analysis implementations.
  292. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
  293. /// A convenience wrapper around the primary \c alias interface.
  294. AliasResult alias(const Value *V1, LocationSize V1Size, const Value *V2,
  295. LocationSize V2Size) {
  296. return alias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
  297. }
  298. /// A convenience wrapper around the primary \c alias interface.
  299. AliasResult alias(const Value *V1, const Value *V2) {
  300. return alias(MemoryLocation::getBeforeOrAfter(V1),
  301. MemoryLocation::getBeforeOrAfter(V2));
  302. }
  303. /// A trivial helper function to check to see if the specified pointers are
  304. /// no-alias.
  305. bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
  306. return alias(LocA, LocB) == AliasResult::NoAlias;
  307. }
  308. /// A convenience wrapper around the \c isNoAlias helper interface.
  309. bool isNoAlias(const Value *V1, LocationSize V1Size, const Value *V2,
  310. LocationSize V2Size) {
  311. return isNoAlias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
  312. }
  313. /// A convenience wrapper around the \c isNoAlias helper interface.
  314. bool isNoAlias(const Value *V1, const Value *V2) {
  315. return isNoAlias(MemoryLocation::getBeforeOrAfter(V1),
  316. MemoryLocation::getBeforeOrAfter(V2));
  317. }
  318. /// A trivial helper function to check to see if the specified pointers are
  319. /// must-alias.
  320. bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
  321. return alias(LocA, LocB) == AliasResult::MustAlias;
  322. }
  323. /// A convenience wrapper around the \c isMustAlias helper interface.
  324. bool isMustAlias(const Value *V1, const Value *V2) {
  325. return alias(V1, LocationSize::precise(1), V2, LocationSize::precise(1)) ==
  326. AliasResult::MustAlias;
  327. }
  328. /// Checks whether the given location points to constant memory, or if
  329. /// \p OrLocal is true whether it points to a local alloca.
  330. bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) {
  331. return isNoModRef(getModRefInfoMask(Loc, OrLocal));
  332. }
  333. /// A convenience wrapper around the primary \c pointsToConstantMemory
  334. /// interface.
  335. bool pointsToConstantMemory(const Value *P, bool OrLocal = false) {
  336. return pointsToConstantMemory(MemoryLocation::getBeforeOrAfter(P), OrLocal);
  337. }
  338. /// @}
  339. //===--------------------------------------------------------------------===//
  340. /// \name Simple mod/ref information
  341. /// @{
  342. /// Returns a bitmask that should be unconditionally applied to the ModRef
  343. /// info of a memory location. This allows us to eliminate Mod and/or Ref
  344. /// from the ModRef info based on the knowledge that the memory location
  345. /// points to constant and/or locally-invariant memory.
  346. ///
  347. /// If IgnoreLocals is true, then this method returns NoModRef for memory
  348. /// that points to a local alloca.
  349. ModRefInfo getModRefInfoMask(const MemoryLocation &Loc,
  350. bool IgnoreLocals = false);
  351. /// A convenience wrapper around the primary \c getModRefInfoMask
  352. /// interface.
  353. ModRefInfo getModRefInfoMask(const Value *P, bool IgnoreLocals = false) {
  354. return getModRefInfoMask(MemoryLocation::getBeforeOrAfter(P), IgnoreLocals);
  355. }
  356. /// Get the ModRef info associated with a pointer argument of a call. The
  357. /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
  358. /// that these bits do not necessarily account for the overall behavior of
  359. /// the function, but rather only provide additional per-argument
  360. /// information.
  361. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx);
  362. /// Return the behavior of the given call site.
  363. MemoryEffects getMemoryEffects(const CallBase *Call);
  364. /// Return the behavior when calling the given function.
  365. MemoryEffects getMemoryEffects(const Function *F);
  366. /// Checks if the specified call is known to never read or write memory.
  367. ///
  368. /// Note that if the call only reads from known-constant memory, it is also
  369. /// legal to return true. Also, calls that unwind the stack are legal for
  370. /// this predicate.
  371. ///
  372. /// Many optimizations (such as CSE and LICM) can be performed on such calls
  373. /// without worrying about aliasing properties, and many calls have this
  374. /// property (e.g. calls to 'sin' and 'cos').
  375. ///
  376. /// This property corresponds to the GCC 'const' attribute.
  377. bool doesNotAccessMemory(const CallBase *Call) {
  378. return getMemoryEffects(Call).doesNotAccessMemory();
  379. }
  380. /// Checks if the specified function is known to never read or write memory.
  381. ///
  382. /// Note that if the function only reads from known-constant memory, it is
  383. /// also legal to return true. Also, function that unwind the stack are legal
  384. /// for this predicate.
  385. ///
  386. /// Many optimizations (such as CSE and LICM) can be performed on such calls
  387. /// to such functions without worrying about aliasing properties, and many
  388. /// functions have this property (e.g. 'sin' and 'cos').
  389. ///
  390. /// This property corresponds to the GCC 'const' attribute.
  391. bool doesNotAccessMemory(const Function *F) {
  392. return getMemoryEffects(F).doesNotAccessMemory();
  393. }
  394. /// Checks if the specified call is known to only read from non-volatile
  395. /// memory (or not access memory at all).
  396. ///
  397. /// Calls that unwind the stack are legal for this predicate.
  398. ///
  399. /// This property allows many common optimizations to be performed in the
  400. /// absence of interfering store instructions, such as CSE of strlen calls.
  401. ///
  402. /// This property corresponds to the GCC 'pure' attribute.
  403. bool onlyReadsMemory(const CallBase *Call) {
  404. return getMemoryEffects(Call).onlyReadsMemory();
  405. }
  406. /// Checks if the specified function is known to only read from non-volatile
  407. /// memory (or not access memory at all).
  408. ///
  409. /// Functions that unwind the stack are legal for this predicate.
  410. ///
  411. /// This property allows many common optimizations to be performed in the
  412. /// absence of interfering store instructions, such as CSE of strlen calls.
  413. ///
  414. /// This property corresponds to the GCC 'pure' attribute.
  415. bool onlyReadsMemory(const Function *F) {
  416. return getMemoryEffects(F).onlyReadsMemory();
  417. }
  418. /// Check whether or not an instruction may read or write the optionally
  419. /// specified memory location.
  420. ///
  421. ///
  422. /// An instruction that doesn't read or write memory may be trivially LICM'd
  423. /// for example.
  424. ///
  425. /// For function calls, this delegates to the alias-analysis specific
  426. /// call-site mod-ref behavior queries. Otherwise it delegates to the specific
  427. /// helpers above.
  428. ModRefInfo getModRefInfo(const Instruction *I,
  429. const std::optional<MemoryLocation> &OptLoc) {
  430. SimpleAAQueryInfo AAQIP(*this);
  431. return getModRefInfo(I, OptLoc, AAQIP);
  432. }
  433. /// A convenience wrapper for constructing the memory location.
  434. ModRefInfo getModRefInfo(const Instruction *I, const Value *P,
  435. LocationSize Size) {
  436. return getModRefInfo(I, MemoryLocation(P, Size));
  437. }
  438. /// Return information about whether a call and an instruction may refer to
  439. /// the same memory locations.
  440. ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call);
  441. /// Return information about whether a particular call site modifies
  442. /// or reads the specified memory location \p MemLoc before instruction \p I
  443. /// in a BasicBlock.
  444. ModRefInfo callCapturesBefore(const Instruction *I,
  445. const MemoryLocation &MemLoc,
  446. DominatorTree *DT) {
  447. SimpleAAQueryInfo AAQIP(*this);
  448. return callCapturesBefore(I, MemLoc, DT, AAQIP);
  449. }
  450. /// A convenience wrapper to synthesize a memory location.
  451. ModRefInfo callCapturesBefore(const Instruction *I, const Value *P,
  452. LocationSize Size, DominatorTree *DT) {
  453. return callCapturesBefore(I, MemoryLocation(P, Size), DT);
  454. }
  455. /// @}
  456. //===--------------------------------------------------------------------===//
  457. /// \name Higher level methods for querying mod/ref information.
  458. /// @{
  459. /// Check if it is possible for execution of the specified basic block to
  460. /// modify the location Loc.
  461. bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc);
  462. /// A convenience wrapper synthesizing a memory location.
  463. bool canBasicBlockModify(const BasicBlock &BB, const Value *P,
  464. LocationSize Size) {
  465. return canBasicBlockModify(BB, MemoryLocation(P, Size));
  466. }
  467. /// Check if it is possible for the execution of the specified instructions
  468. /// to mod\ref (according to the mode) the location Loc.
  469. ///
  470. /// The instructions to consider are all of the instructions in the range of
  471. /// [I1,I2] INCLUSIVE. I1 and I2 must be in the same basic block.
  472. bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
  473. const MemoryLocation &Loc,
  474. const ModRefInfo Mode);
  475. /// A convenience wrapper synthesizing a memory location.
  476. bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
  477. const Value *Ptr, LocationSize Size,
  478. const ModRefInfo Mode) {
  479. return canInstructionRangeModRef(I1, I2, MemoryLocation(Ptr, Size), Mode);
  480. }
  481. // CtxI can be nullptr, in which case the query is whether or not the aliasing
  482. // relationship holds through the entire function.
  483. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
  484. AAQueryInfo &AAQI, const Instruction *CtxI = nullptr);
  485. bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  486. bool OrLocal = false);
  487. ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  488. bool IgnoreLocals = false);
  489. ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call2,
  490. AAQueryInfo &AAQIP);
  491. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
  492. AAQueryInfo &AAQI);
  493. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  494. AAQueryInfo &AAQI);
  495. ModRefInfo getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc,
  496. AAQueryInfo &AAQI);
  497. ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc,
  498. AAQueryInfo &AAQI);
  499. ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc,
  500. AAQueryInfo &AAQI);
  501. ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc,
  502. AAQueryInfo &AAQI);
  503. ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX,
  504. const MemoryLocation &Loc, AAQueryInfo &AAQI);
  505. ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc,
  506. AAQueryInfo &AAQI);
  507. ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc,
  508. AAQueryInfo &AAQI);
  509. ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc,
  510. AAQueryInfo &AAQI);
  511. ModRefInfo getModRefInfo(const Instruction *I,
  512. const std::optional<MemoryLocation> &OptLoc,
  513. AAQueryInfo &AAQIP);
  514. ModRefInfo callCapturesBefore(const Instruction *I,
  515. const MemoryLocation &MemLoc, DominatorTree *DT,
  516. AAQueryInfo &AAQIP);
  517. MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI);
  518. private:
  519. class Concept;
  520. template <typename T> class Model;
  521. friend class AAResultBase;
  522. const TargetLibraryInfo &TLI;
  523. std::vector<std::unique_ptr<Concept>> AAs;
  524. std::vector<AnalysisKey *> AADeps;
  525. friend class BatchAAResults;
  526. };
  527. /// This class is a wrapper over an AAResults, and it is intended to be used
  528. /// only when there are no IR changes inbetween queries. BatchAAResults is
  529. /// reusing the same `AAQueryInfo` to preserve the state across queries,
  530. /// esentially making AA work in "batch mode". The internal state cannot be
  531. /// cleared, so to go "out-of-batch-mode", the user must either use AAResults,
  532. /// or create a new BatchAAResults.
  533. class BatchAAResults {
  534. AAResults &AA;
  535. AAQueryInfo AAQI;
  536. SimpleCaptureInfo SimpleCI;
  537. public:
  538. BatchAAResults(AAResults &AAR) : AA(AAR), AAQI(AAR, &SimpleCI) {}
  539. BatchAAResults(AAResults &AAR, CaptureInfo *CI) : AA(AAR), AAQI(AAR, CI) {}
  540. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
  541. return AA.alias(LocA, LocB, AAQI);
  542. }
  543. bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) {
  544. return AA.pointsToConstantMemory(Loc, AAQI, OrLocal);
  545. }
  546. ModRefInfo getModRefInfoMask(const MemoryLocation &Loc,
  547. bool IgnoreLocals = false) {
  548. return AA.getModRefInfoMask(Loc, AAQI, IgnoreLocals);
  549. }
  550. ModRefInfo getModRefInfo(const Instruction *I,
  551. const std::optional<MemoryLocation> &OptLoc) {
  552. return AA.getModRefInfo(I, OptLoc, AAQI);
  553. }
  554. ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call2) {
  555. return AA.getModRefInfo(I, Call2, AAQI);
  556. }
  557. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
  558. return AA.getArgModRefInfo(Call, ArgIdx);
  559. }
  560. MemoryEffects getMemoryEffects(const CallBase *Call) {
  561. return AA.getMemoryEffects(Call, AAQI);
  562. }
  563. bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
  564. return alias(LocA, LocB) == AliasResult::MustAlias;
  565. }
  566. bool isMustAlias(const Value *V1, const Value *V2) {
  567. return alias(MemoryLocation(V1, LocationSize::precise(1)),
  568. MemoryLocation(V2, LocationSize::precise(1))) ==
  569. AliasResult::MustAlias;
  570. }
  571. ModRefInfo callCapturesBefore(const Instruction *I,
  572. const MemoryLocation &MemLoc,
  573. DominatorTree *DT) {
  574. return AA.callCapturesBefore(I, MemLoc, DT, AAQI);
  575. }
  576. /// Assume that values may come from different cycle iterations.
  577. void enableCrossIterationMode() {
  578. AAQI.MayBeCrossIteration = true;
  579. }
  580. };
  581. /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis
  582. /// pointer or reference.
  583. using AliasAnalysis = AAResults;
  584. /// A private abstract base class describing the concept of an individual alias
  585. /// analysis implementation.
  586. ///
  587. /// This interface is implemented by any \c Model instantiation. It is also the
  588. /// interface which a type used to instantiate the model must provide.
  589. ///
  590. /// All of these methods model methods by the same name in the \c
  591. /// AAResults class. Only differences and specifics to how the
  592. /// implementations are called are documented here.
  593. class AAResults::Concept {
  594. public:
  595. virtual ~Concept() = 0;
  596. //===--------------------------------------------------------------------===//
  597. /// \name Alias Queries
  598. /// @{
  599. /// The main low level interface to the alias analysis implementation.
  600. /// Returns an AliasResult indicating whether the two pointers are aliased to
  601. /// each other. This is the interface that must be implemented by specific
  602. /// alias analysis implementations.
  603. virtual AliasResult alias(const MemoryLocation &LocA,
  604. const MemoryLocation &LocB, AAQueryInfo &AAQI,
  605. const Instruction *CtxI) = 0;
  606. /// @}
  607. //===--------------------------------------------------------------------===//
  608. /// \name Simple mod/ref information
  609. /// @{
  610. /// Returns a bitmask that should be unconditionally applied to the ModRef
  611. /// info of a memory location. This allows us to eliminate Mod and/or Ref from
  612. /// the ModRef info based on the knowledge that the memory location points to
  613. /// constant and/or locally-invariant memory.
  614. virtual ModRefInfo getModRefInfoMask(const MemoryLocation &Loc,
  615. AAQueryInfo &AAQI,
  616. bool IgnoreLocals) = 0;
  617. /// Get the ModRef info associated with a pointer argument of a callsite. The
  618. /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
  619. /// that these bits do not necessarily account for the overall behavior of
  620. /// the function, but rather only provide additional per-argument
  621. /// information.
  622. virtual ModRefInfo getArgModRefInfo(const CallBase *Call,
  623. unsigned ArgIdx) = 0;
  624. /// Return the behavior of the given call site.
  625. virtual MemoryEffects getMemoryEffects(const CallBase *Call,
  626. AAQueryInfo &AAQI) = 0;
  627. /// Return the behavior when calling the given function.
  628. virtual MemoryEffects getMemoryEffects(const Function *F) = 0;
  629. /// getModRefInfo (for call sites) - Return information about whether
  630. /// a particular call site modifies or reads the specified memory location.
  631. virtual ModRefInfo getModRefInfo(const CallBase *Call,
  632. const MemoryLocation &Loc,
  633. AAQueryInfo &AAQI) = 0;
  634. /// Return information about whether two call sites may refer to the same set
  635. /// of memory locations. See the AA documentation for details:
  636. /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
  637. virtual ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  638. AAQueryInfo &AAQI) = 0;
  639. /// @}
  640. };
  641. /// A private class template which derives from \c Concept and wraps some other
  642. /// type.
  643. ///
  644. /// This models the concept by directly forwarding each interface point to the
  645. /// wrapped type which must implement a compatible interface. This provides
  646. /// a type erased binding.
  647. template <typename AAResultT> class AAResults::Model final : public Concept {
  648. AAResultT &Result;
  649. public:
  650. explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) {}
  651. ~Model() override = default;
  652. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
  653. AAQueryInfo &AAQI, const Instruction *CtxI) override {
  654. return Result.alias(LocA, LocB, AAQI, CtxI);
  655. }
  656. ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  657. bool IgnoreLocals) override {
  658. return Result.getModRefInfoMask(Loc, AAQI, IgnoreLocals);
  659. }
  660. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) override {
  661. return Result.getArgModRefInfo(Call, ArgIdx);
  662. }
  663. MemoryEffects getMemoryEffects(const CallBase *Call,
  664. AAQueryInfo &AAQI) override {
  665. return Result.getMemoryEffects(Call, AAQI);
  666. }
  667. MemoryEffects getMemoryEffects(const Function *F) override {
  668. return Result.getMemoryEffects(F);
  669. }
  670. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
  671. AAQueryInfo &AAQI) override {
  672. return Result.getModRefInfo(Call, Loc, AAQI);
  673. }
  674. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  675. AAQueryInfo &AAQI) override {
  676. return Result.getModRefInfo(Call1, Call2, AAQI);
  677. }
  678. };
  679. /// A base class to help implement the function alias analysis results concept.
  680. ///
  681. /// Because of the nature of many alias analysis implementations, they often
  682. /// only implement a subset of the interface. This base class will attempt to
  683. /// implement the remaining portions of the interface in terms of simpler forms
  684. /// of the interface where possible, and otherwise provide conservatively
  685. /// correct fallback implementations.
  686. ///
  687. /// Implementors of an alias analysis should derive from this class, and then
  688. /// override specific methods that they wish to customize. There is no need to
  689. /// use virtual anywhere.
  690. class AAResultBase {
  691. protected:
  692. explicit AAResultBase() = default;
  693. // Provide all the copy and move constructors so that derived types aren't
  694. // constrained.
  695. AAResultBase(const AAResultBase &Arg) {}
  696. AAResultBase(AAResultBase &&Arg) {}
  697. public:
  698. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
  699. AAQueryInfo &AAQI, const Instruction *I) {
  700. return AliasResult::MayAlias;
  701. }
  702. ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  703. bool IgnoreLocals) {
  704. return ModRefInfo::ModRef;
  705. }
  706. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
  707. return ModRefInfo::ModRef;
  708. }
  709. MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI) {
  710. return MemoryEffects::unknown();
  711. }
  712. MemoryEffects getMemoryEffects(const Function *F) {
  713. return MemoryEffects::unknown();
  714. }
  715. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
  716. AAQueryInfo &AAQI) {
  717. return ModRefInfo::ModRef;
  718. }
  719. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  720. AAQueryInfo &AAQI) {
  721. return ModRefInfo::ModRef;
  722. }
  723. };
  724. /// Return true if this pointer is returned by a noalias function.
  725. bool isNoAliasCall(const Value *V);
  726. /// Return true if this pointer refers to a distinct and identifiable object.
  727. /// This returns true for:
  728. /// Global Variables and Functions (but not Global Aliases)
  729. /// Allocas
  730. /// ByVal and NoAlias Arguments
  731. /// NoAlias returns (e.g. calls to malloc)
  732. ///
  733. bool isIdentifiedObject(const Value *V);
  734. /// Return true if V is umabigously identified at the function-level.
  735. /// Different IdentifiedFunctionLocals can't alias.
  736. /// Further, an IdentifiedFunctionLocal can not alias with any function
  737. /// arguments other than itself, which is not necessarily true for
  738. /// IdentifiedObjects.
  739. bool isIdentifiedFunctionLocal(const Value *V);
  740. /// Returns true if the pointer is one which would have been considered an
  741. /// escape by isNonEscapingLocalObject.
  742. bool isEscapeSource(const Value *V);
  743. /// Return true if Object memory is not visible after an unwind, in the sense
  744. /// that program semantics cannot depend on Object containing any particular
  745. /// value on unwind. If the RequiresNoCaptureBeforeUnwind out parameter is set
  746. /// to true, then the memory is only not visible if the object has not been
  747. /// captured prior to the unwind. Otherwise it is not visible even if captured.
  748. bool isNotVisibleOnUnwind(const Value *Object,
  749. bool &RequiresNoCaptureBeforeUnwind);
  750. /// A manager for alias analyses.
  751. ///
  752. /// This class can have analyses registered with it and when run, it will run
  753. /// all of them and aggregate their results into single AA results interface
  754. /// that dispatches across all of the alias analysis results available.
  755. ///
  756. /// Note that the order in which analyses are registered is very significant.
  757. /// That is the order in which the results will be aggregated and queried.
  758. ///
  759. /// This manager effectively wraps the AnalysisManager for registering alias
  760. /// analyses. When you register your alias analysis with this manager, it will
  761. /// ensure the analysis itself is registered with its AnalysisManager.
  762. ///
  763. /// The result of this analysis is only invalidated if one of the particular
  764. /// aggregated AA results end up being invalidated. This removes the need to
  765. /// explicitly preserve the results of `AAManager`. Note that analyses should no
  766. /// longer be registered once the `AAManager` is run.
  767. class AAManager : public AnalysisInfoMixin<AAManager> {
  768. public:
  769. using Result = AAResults;
  770. /// Register a specific AA result.
  771. template <typename AnalysisT> void registerFunctionAnalysis() {
  772. ResultGetters.push_back(&getFunctionAAResultImpl<AnalysisT>);
  773. }
  774. /// Register a specific AA result.
  775. template <typename AnalysisT> void registerModuleAnalysis() {
  776. ResultGetters.push_back(&getModuleAAResultImpl<AnalysisT>);
  777. }
  778. Result run(Function &F, FunctionAnalysisManager &AM);
  779. private:
  780. friend AnalysisInfoMixin<AAManager>;
  781. static AnalysisKey Key;
  782. SmallVector<void (*)(Function &F, FunctionAnalysisManager &AM,
  783. AAResults &AAResults),
  784. 4> ResultGetters;
  785. template <typename AnalysisT>
  786. static void getFunctionAAResultImpl(Function &F,
  787. FunctionAnalysisManager &AM,
  788. AAResults &AAResults) {
  789. AAResults.addAAResult(AM.template getResult<AnalysisT>(F));
  790. AAResults.addAADependencyID(AnalysisT::ID());
  791. }
  792. template <typename AnalysisT>
  793. static void getModuleAAResultImpl(Function &F, FunctionAnalysisManager &AM,
  794. AAResults &AAResults) {
  795. auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
  796. if (auto *R =
  797. MAMProxy.template getCachedResult<AnalysisT>(*F.getParent())) {
  798. AAResults.addAAResult(*R);
  799. MAMProxy
  800. .template registerOuterAnalysisInvalidation<AnalysisT, AAManager>();
  801. }
  802. }
  803. };
  804. /// A wrapper pass to provide the legacy pass manager access to a suitably
  805. /// prepared AAResults object.
  806. class AAResultsWrapperPass : public FunctionPass {
  807. std::unique_ptr<AAResults> AAR;
  808. public:
  809. static char ID;
  810. AAResultsWrapperPass();
  811. AAResults &getAAResults() { return *AAR; }
  812. const AAResults &getAAResults() const { return *AAR; }
  813. bool runOnFunction(Function &F) override;
  814. void getAnalysisUsage(AnalysisUsage &AU) const override;
  815. };
  816. /// A wrapper pass for external alias analyses. This just squirrels away the
  817. /// callback used to run any analyses and register their results.
  818. struct ExternalAAWrapperPass : ImmutablePass {
  819. using CallbackT = std::function<void(Pass &, Function &, AAResults &)>;
  820. CallbackT CB;
  821. static char ID;
  822. ExternalAAWrapperPass();
  823. explicit ExternalAAWrapperPass(CallbackT CB);
  824. void getAnalysisUsage(AnalysisUsage &AU) const override {
  825. AU.setPreservesAll();
  826. }
  827. };
  828. FunctionPass *createAAResultsWrapperPass();
  829. /// A wrapper pass around a callback which can be used to populate the
  830. /// AAResults in the AAResultsWrapperPass from an external AA.
  831. ///
  832. /// The callback provided here will be used each time we prepare an AAResults
  833. /// object, and will receive a reference to the function wrapper pass, the
  834. /// function, and the AAResults object to populate. This should be used when
  835. /// setting up a custom pass pipeline to inject a hook into the AA results.
  836. ImmutablePass *createExternalAAWrapperPass(
  837. std::function<void(Pass &, Function &, AAResults &)> Callback);
  838. /// A helper for the legacy pass manager to create a \c AAResults
  839. /// object populated to the best of our ability for a particular function when
  840. /// inside of a \c ModulePass or a \c CallGraphSCCPass.
  841. ///
  842. /// If a \c ModulePass or a \c CallGraphSCCPass calls \p
  843. /// createLegacyPMAAResults, it also needs to call \p addUsedAAAnalyses in \p
  844. /// getAnalysisUsage.
  845. AAResults createLegacyPMAAResults(Pass &P, Function &F, BasicAAResult &BAR);
  846. /// A helper for the legacy pass manager to populate \p AU to add uses to make
  847. /// sure the analyses required by \p createLegacyPMAAResults are available.
  848. void getAAResultsAnalysisUsage(AnalysisUsage &AU);
  849. } // end namespace llvm
  850. #endif // LLVM_ANALYSIS_ALIASANALYSIS_H
  851. #ifdef __GNUC__
  852. #pragma GCC diagnostic pop
  853. #endif