AliasAnalysis.h 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  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/None.h"
  45. #include "llvm/ADT/Optional.h"
  46. #include "llvm/ADT/SmallVector.h"
  47. #include "llvm/Analysis/MemoryLocation.h"
  48. #include "llvm/IR/PassManager.h"
  49. #include "llvm/Pass.h"
  50. #include <cstdint>
  51. #include <functional>
  52. #include <memory>
  53. #include <vector>
  54. namespace llvm {
  55. class AnalysisUsage;
  56. class AtomicCmpXchgInst;
  57. class BasicAAResult;
  58. class BasicBlock;
  59. class CatchPadInst;
  60. class CatchReturnInst;
  61. class DominatorTree;
  62. class FenceInst;
  63. class Function;
  64. class InvokeInst;
  65. class PreservedAnalyses;
  66. class TargetLibraryInfo;
  67. class Value;
  68. /// The possible results of an alias query.
  69. ///
  70. /// These results are always computed between two MemoryLocation objects as
  71. /// a query to some alias analysis.
  72. ///
  73. /// Note that these are unscoped enumerations because we would like to support
  74. /// implicitly testing a result for the existence of any possible aliasing with
  75. /// a conversion to bool, but an "enum class" doesn't support this. The
  76. /// canonical names from the literature are suffixed and unique anyways, and so
  77. /// they serve as global constants in LLVM for these results.
  78. ///
  79. /// See docs/AliasAnalysis.html for more information on the specific meanings
  80. /// of these values.
  81. enum AliasResult : uint8_t {
  82. /// The two locations do not alias at all.
  83. ///
  84. /// This value is arranged to convert to false, while all other values
  85. /// convert to true. This allows a boolean context to convert the result to
  86. /// a binary flag indicating whether there is the possibility of aliasing.
  87. NoAlias = 0,
  88. /// The two locations may or may not alias. This is the least precise result.
  89. MayAlias,
  90. /// The two locations alias, but only due to a partial overlap.
  91. PartialAlias,
  92. /// The two locations precisely alias each other.
  93. MustAlias,
  94. };
  95. /// << operator for AliasResult.
  96. raw_ostream &operator<<(raw_ostream &OS, AliasResult AR);
  97. /// Flags indicating whether a memory access modifies or references memory.
  98. ///
  99. /// This is no access at all, a modification, a reference, or both
  100. /// a modification and a reference. These are specifically structured such that
  101. /// they form a three bit matrix and bit-tests for 'mod' or 'ref' or 'must'
  102. /// work with any of the possible values.
  103. enum class ModRefInfo : uint8_t {
  104. /// Must is provided for completeness, but no routines will return only
  105. /// Must today. See definition of Must below.
  106. Must = 0,
  107. /// The access may reference the value stored in memory,
  108. /// a mustAlias relation was found, and no mayAlias or partialAlias found.
  109. MustRef = 1,
  110. /// The access may modify the value stored in memory,
  111. /// a mustAlias relation was found, and no mayAlias or partialAlias found.
  112. MustMod = 2,
  113. /// The access may reference, modify or both the value stored in memory,
  114. /// a mustAlias relation was found, and no mayAlias or partialAlias found.
  115. MustModRef = MustRef | MustMod,
  116. /// The access neither references nor modifies the value stored in memory.
  117. NoModRef = 4,
  118. /// The access may reference the value stored in memory.
  119. Ref = NoModRef | MustRef,
  120. /// The access may modify the value stored in memory.
  121. Mod = NoModRef | MustMod,
  122. /// The access may reference and may modify the value stored in memory.
  123. ModRef = Ref | Mod,
  124. /// About Must:
  125. /// Must is set in a best effort manner.
  126. /// We usually do not try our best to infer Must, instead it is merely
  127. /// another piece of "free" information that is presented when available.
  128. /// Must set means there was certainly a MustAlias found. For calls,
  129. /// where multiple arguments are checked (argmemonly), this translates to
  130. /// only MustAlias or NoAlias was found.
  131. /// Must is not set for RAR accesses, even if the two locations must
  132. /// alias. The reason is that two read accesses translate to an early return
  133. /// of NoModRef. An additional alias check to set Must may be
  134. /// expensive. Other cases may also not set Must(e.g. callCapturesBefore).
  135. /// We refer to Must being *set* when the most significant bit is *cleared*.
  136. /// Conversely we *clear* Must information by *setting* the Must bit to 1.
  137. };
  138. LLVM_NODISCARD inline bool isNoModRef(const ModRefInfo MRI) {
  139. return (static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef)) ==
  140. static_cast<int>(ModRefInfo::Must);
  141. }
  142. LLVM_NODISCARD inline bool isModOrRefSet(const ModRefInfo MRI) {
  143. return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef);
  144. }
  145. LLVM_NODISCARD inline bool isModAndRefSet(const ModRefInfo MRI) {
  146. return (static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef)) ==
  147. static_cast<int>(ModRefInfo::MustModRef);
  148. }
  149. LLVM_NODISCARD inline bool isModSet(const ModRefInfo MRI) {
  150. return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustMod);
  151. }
  152. LLVM_NODISCARD inline bool isRefSet(const ModRefInfo MRI) {
  153. return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustRef);
  154. }
  155. LLVM_NODISCARD inline bool isMustSet(const ModRefInfo MRI) {
  156. return !(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::NoModRef));
  157. }
  158. LLVM_NODISCARD inline ModRefInfo setMod(const ModRefInfo MRI) {
  159. return ModRefInfo(static_cast<int>(MRI) |
  160. static_cast<int>(ModRefInfo::MustMod));
  161. }
  162. LLVM_NODISCARD inline ModRefInfo setRef(const ModRefInfo MRI) {
  163. return ModRefInfo(static_cast<int>(MRI) |
  164. static_cast<int>(ModRefInfo::MustRef));
  165. }
  166. LLVM_NODISCARD inline ModRefInfo setMust(const ModRefInfo MRI) {
  167. return ModRefInfo(static_cast<int>(MRI) &
  168. static_cast<int>(ModRefInfo::MustModRef));
  169. }
  170. LLVM_NODISCARD inline ModRefInfo setModAndRef(const ModRefInfo MRI) {
  171. return ModRefInfo(static_cast<int>(MRI) |
  172. static_cast<int>(ModRefInfo::MustModRef));
  173. }
  174. LLVM_NODISCARD inline ModRefInfo clearMod(const ModRefInfo MRI) {
  175. return ModRefInfo(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::Ref));
  176. }
  177. LLVM_NODISCARD inline ModRefInfo clearRef(const ModRefInfo MRI) {
  178. return ModRefInfo(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::Mod));
  179. }
  180. LLVM_NODISCARD inline ModRefInfo clearMust(const ModRefInfo MRI) {
  181. return ModRefInfo(static_cast<int>(MRI) |
  182. static_cast<int>(ModRefInfo::NoModRef));
  183. }
  184. LLVM_NODISCARD inline ModRefInfo unionModRef(const ModRefInfo MRI1,
  185. const ModRefInfo MRI2) {
  186. return ModRefInfo(static_cast<int>(MRI1) | static_cast<int>(MRI2));
  187. }
  188. LLVM_NODISCARD inline ModRefInfo intersectModRef(const ModRefInfo MRI1,
  189. const ModRefInfo MRI2) {
  190. return ModRefInfo(static_cast<int>(MRI1) & static_cast<int>(MRI2));
  191. }
  192. /// The locations at which a function might access memory.
  193. ///
  194. /// These are primarily used in conjunction with the \c AccessKind bits to
  195. /// describe both the nature of access and the locations of access for a
  196. /// function call.
  197. enum FunctionModRefLocation {
  198. /// Base case is no access to memory.
  199. FMRL_Nowhere = 0,
  200. /// Access to memory via argument pointers.
  201. FMRL_ArgumentPointees = 8,
  202. /// Memory that is inaccessible via LLVM IR.
  203. FMRL_InaccessibleMem = 16,
  204. /// Access to any memory.
  205. FMRL_Anywhere = 32 | FMRL_InaccessibleMem | FMRL_ArgumentPointees
  206. };
  207. /// Summary of how a function affects memory in the program.
  208. ///
  209. /// Loads from constant globals are not considered memory accesses for this
  210. /// interface. Also, functions may freely modify stack space local to their
  211. /// invocation without having to report it through these interfaces.
  212. enum FunctionModRefBehavior {
  213. /// This function does not perform any non-local loads or stores to memory.
  214. ///
  215. /// This property corresponds to the GCC 'const' attribute.
  216. /// This property corresponds to the LLVM IR 'readnone' attribute.
  217. /// This property corresponds to the IntrNoMem LLVM intrinsic flag.
  218. FMRB_DoesNotAccessMemory =
  219. FMRL_Nowhere | static_cast<int>(ModRefInfo::NoModRef),
  220. /// The only memory references in this function (if it has any) are
  221. /// non-volatile loads from objects pointed to by its pointer-typed
  222. /// arguments, with arbitrary offsets.
  223. ///
  224. /// This property corresponds to the combination of the IntrReadMem
  225. /// and IntrArgMemOnly LLVM intrinsic flags.
  226. FMRB_OnlyReadsArgumentPointees =
  227. FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::Ref),
  228. /// The only memory references in this function (if it has any) are
  229. /// non-volatile stores from objects pointed to by its pointer-typed
  230. /// arguments, with arbitrary offsets.
  231. ///
  232. /// This property corresponds to the combination of the IntrWriteMem
  233. /// and IntrArgMemOnly LLVM intrinsic flags.
  234. FMRB_OnlyWritesArgumentPointees =
  235. FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::Mod),
  236. /// The only memory references in this function (if it has any) are
  237. /// non-volatile loads and stores from objects pointed to by its
  238. /// pointer-typed arguments, with arbitrary offsets.
  239. ///
  240. /// This property corresponds to the IntrArgMemOnly LLVM intrinsic flag.
  241. FMRB_OnlyAccessesArgumentPointees =
  242. FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::ModRef),
  243. /// The only memory references in this function (if it has any) are
  244. /// reads of memory that is otherwise inaccessible via LLVM IR.
  245. ///
  246. /// This property corresponds to the LLVM IR inaccessiblememonly attribute.
  247. FMRB_OnlyReadsInaccessibleMem =
  248. FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::Ref),
  249. /// The only memory references in this function (if it has any) are
  250. /// writes to memory that is otherwise inaccessible via LLVM IR.
  251. ///
  252. /// This property corresponds to the LLVM IR inaccessiblememonly attribute.
  253. FMRB_OnlyWritesInaccessibleMem =
  254. FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::Mod),
  255. /// The only memory references in this function (if it has any) are
  256. /// references of memory that is otherwise inaccessible via LLVM IR.
  257. ///
  258. /// This property corresponds to the LLVM IR inaccessiblememonly attribute.
  259. FMRB_OnlyAccessesInaccessibleMem =
  260. FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::ModRef),
  261. /// The function may perform non-volatile loads from objects pointed
  262. /// to by its pointer-typed arguments, with arbitrary offsets, and
  263. /// it may also perform loads of memory that is otherwise
  264. /// inaccessible via LLVM IR.
  265. ///
  266. /// This property corresponds to the LLVM IR
  267. /// inaccessiblemem_or_argmemonly attribute.
  268. FMRB_OnlyReadsInaccessibleOrArgMem = FMRL_InaccessibleMem |
  269. FMRL_ArgumentPointees |
  270. static_cast<int>(ModRefInfo::Ref),
  271. /// The function may perform non-volatile stores to objects pointed
  272. /// to by its pointer-typed arguments, with arbitrary offsets, and
  273. /// it may also perform stores of memory that is otherwise
  274. /// inaccessible via LLVM IR.
  275. ///
  276. /// This property corresponds to the LLVM IR
  277. /// inaccessiblemem_or_argmemonly attribute.
  278. FMRB_OnlyWritesInaccessibleOrArgMem = FMRL_InaccessibleMem |
  279. FMRL_ArgumentPointees |
  280. static_cast<int>(ModRefInfo::Mod),
  281. /// The function may perform non-volatile loads and stores of objects
  282. /// pointed to by its pointer-typed arguments, with arbitrary offsets, and
  283. /// it may also perform loads and stores of memory that is otherwise
  284. /// inaccessible via LLVM IR.
  285. ///
  286. /// This property corresponds to the LLVM IR
  287. /// inaccessiblemem_or_argmemonly attribute.
  288. FMRB_OnlyAccessesInaccessibleOrArgMem = FMRL_InaccessibleMem |
  289. FMRL_ArgumentPointees |
  290. static_cast<int>(ModRefInfo::ModRef),
  291. /// This function does not perform any non-local stores or volatile loads,
  292. /// but may read from any memory location.
  293. ///
  294. /// This property corresponds to the GCC 'pure' attribute.
  295. /// This property corresponds to the LLVM IR 'readonly' attribute.
  296. /// This property corresponds to the IntrReadMem LLVM intrinsic flag.
  297. FMRB_OnlyReadsMemory = FMRL_Anywhere | static_cast<int>(ModRefInfo::Ref),
  298. // This function does not read from memory anywhere, but may write to any
  299. // memory location.
  300. //
  301. // This property corresponds to the LLVM IR 'writeonly' attribute.
  302. // This property corresponds to the IntrWriteMem LLVM intrinsic flag.
  303. FMRB_OnlyWritesMemory = FMRL_Anywhere | static_cast<int>(ModRefInfo::Mod),
  304. /// This indicates that the function could not be classified into one of the
  305. /// behaviors above.
  306. FMRB_UnknownModRefBehavior =
  307. FMRL_Anywhere | static_cast<int>(ModRefInfo::ModRef)
  308. };
  309. // Wrapper method strips bits significant only in FunctionModRefBehavior,
  310. // to obtain a valid ModRefInfo. The benefit of using the wrapper is that if
  311. // ModRefInfo enum changes, the wrapper can be updated to & with the new enum
  312. // entry with all bits set to 1.
  313. LLVM_NODISCARD inline ModRefInfo
  314. createModRefInfo(const FunctionModRefBehavior FMRB) {
  315. return ModRefInfo(FMRB & static_cast<int>(ModRefInfo::ModRef));
  316. }
  317. /// This class stores info we want to provide to or retain within an alias
  318. /// query. By default, the root query is stateless and starts with a freshly
  319. /// constructed info object. Specific alias analyses can use this query info to
  320. /// store per-query state that is important for recursive or nested queries to
  321. /// avoid recomputing. To enable preserving this state across multiple queries
  322. /// where safe (due to the IR not changing), use a `BatchAAResults` wrapper.
  323. /// The information stored in an `AAQueryInfo` is currently limitted to the
  324. /// caches used by BasicAA, but can further be extended to fit other AA needs.
  325. class AAQueryInfo {
  326. public:
  327. using LocPair = std::pair<MemoryLocation, MemoryLocation>;
  328. struct CacheEntry {
  329. AliasResult Result;
  330. /// Number of times a NoAlias assumption has been used.
  331. /// 0 for assumptions that have not been used, -1 for definitive results.
  332. int NumAssumptionUses;
  333. /// Whether this is a definitive (non-assumption) result.
  334. bool isDefinitive() const { return NumAssumptionUses < 0; }
  335. };
  336. using AliasCacheT = SmallDenseMap<LocPair, CacheEntry, 8>;
  337. AliasCacheT AliasCache;
  338. using IsCapturedCacheT = SmallDenseMap<const Value *, bool, 8>;
  339. IsCapturedCacheT IsCapturedCache;
  340. /// How many active NoAlias assumption uses there are.
  341. int NumAssumptionUses = 0;
  342. /// Location pairs for which an assumption based result is currently stored.
  343. /// Used to remove all potentially incorrect results from the cache if an
  344. /// assumption is disproven.
  345. SmallVector<AAQueryInfo::LocPair, 4> AssumptionBasedResults;
  346. AAQueryInfo() : AliasCache(), IsCapturedCache() {}
  347. };
  348. class BatchAAResults;
  349. class AAResults {
  350. public:
  351. // Make these results default constructable and movable. We have to spell
  352. // these out because MSVC won't synthesize them.
  353. AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {}
  354. AAResults(AAResults &&Arg);
  355. ~AAResults();
  356. /// Register a specific AA result.
  357. template <typename AAResultT> void addAAResult(AAResultT &AAResult) {
  358. // FIXME: We should use a much lighter weight system than the usual
  359. // polymorphic pattern because we don't own AAResult. It should
  360. // ideally involve two pointers and no separate allocation.
  361. AAs.emplace_back(new Model<AAResultT>(AAResult, *this));
  362. }
  363. /// Register a function analysis ID that the results aggregation depends on.
  364. ///
  365. /// This is used in the new pass manager to implement the invalidation logic
  366. /// where we must invalidate the results aggregation if any of our component
  367. /// analyses become invalid.
  368. void addAADependencyID(AnalysisKey *ID) { AADeps.push_back(ID); }
  369. /// Handle invalidation events in the new pass manager.
  370. ///
  371. /// The aggregation is invalidated if any of the underlying analyses is
  372. /// invalidated.
  373. bool invalidate(Function &F, const PreservedAnalyses &PA,
  374. FunctionAnalysisManager::Invalidator &Inv);
  375. //===--------------------------------------------------------------------===//
  376. /// \name Alias Queries
  377. /// @{
  378. /// The main low level interface to the alias analysis implementation.
  379. /// Returns an AliasResult indicating whether the two pointers are aliased to
  380. /// each other. This is the interface that must be implemented by specific
  381. /// alias analysis implementations.
  382. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
  383. /// A convenience wrapper around the primary \c alias interface.
  384. AliasResult alias(const Value *V1, LocationSize V1Size, const Value *V2,
  385. LocationSize V2Size) {
  386. return alias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
  387. }
  388. /// A convenience wrapper around the primary \c alias interface.
  389. AliasResult alias(const Value *V1, const Value *V2) {
  390. return alias(MemoryLocation::getBeforeOrAfter(V1),
  391. MemoryLocation::getBeforeOrAfter(V2));
  392. }
  393. /// A trivial helper function to check to see if the specified pointers are
  394. /// no-alias.
  395. bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
  396. return alias(LocA, LocB) == NoAlias;
  397. }
  398. /// A convenience wrapper around the \c isNoAlias helper interface.
  399. bool isNoAlias(const Value *V1, LocationSize V1Size, const Value *V2,
  400. LocationSize V2Size) {
  401. return isNoAlias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
  402. }
  403. /// A convenience wrapper around the \c isNoAlias helper interface.
  404. bool isNoAlias(const Value *V1, const Value *V2) {
  405. return isNoAlias(MemoryLocation::getBeforeOrAfter(V1),
  406. MemoryLocation::getBeforeOrAfter(V2));
  407. }
  408. /// A trivial helper function to check to see if the specified pointers are
  409. /// must-alias.
  410. bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
  411. return alias(LocA, LocB) == MustAlias;
  412. }
  413. /// A convenience wrapper around the \c isMustAlias helper interface.
  414. bool isMustAlias(const Value *V1, const Value *V2) {
  415. return alias(V1, LocationSize::precise(1), V2, LocationSize::precise(1)) ==
  416. MustAlias;
  417. }
  418. /// Checks whether the given location points to constant memory, or if
  419. /// \p OrLocal is true whether it points to a local alloca.
  420. bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false);
  421. /// A convenience wrapper around the primary \c pointsToConstantMemory
  422. /// interface.
  423. bool pointsToConstantMemory(const Value *P, bool OrLocal = false) {
  424. return pointsToConstantMemory(MemoryLocation::getBeforeOrAfter(P), OrLocal);
  425. }
  426. /// @}
  427. //===--------------------------------------------------------------------===//
  428. /// \name Simple mod/ref information
  429. /// @{
  430. /// Get the ModRef info associated with a pointer argument of a call. The
  431. /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
  432. /// that these bits do not necessarily account for the overall behavior of
  433. /// the function, but rather only provide additional per-argument
  434. /// information. This never sets ModRefInfo::Must.
  435. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx);
  436. /// Return the behavior of the given call site.
  437. FunctionModRefBehavior getModRefBehavior(const CallBase *Call);
  438. /// Return the behavior when calling the given function.
  439. FunctionModRefBehavior getModRefBehavior(const Function *F);
  440. /// Checks if the specified call is known to never read or write memory.
  441. ///
  442. /// Note that if the call only reads from known-constant memory, it is also
  443. /// legal to return true. Also, calls that unwind the stack are legal for
  444. /// this predicate.
  445. ///
  446. /// Many optimizations (such as CSE and LICM) can be performed on such calls
  447. /// without worrying about aliasing properties, and many calls have this
  448. /// property (e.g. calls to 'sin' and 'cos').
  449. ///
  450. /// This property corresponds to the GCC 'const' attribute.
  451. bool doesNotAccessMemory(const CallBase *Call) {
  452. return getModRefBehavior(Call) == FMRB_DoesNotAccessMemory;
  453. }
  454. /// Checks if the specified function is known to never read or write memory.
  455. ///
  456. /// Note that if the function only reads from known-constant memory, it is
  457. /// also legal to return true. Also, function that unwind the stack are legal
  458. /// for this predicate.
  459. ///
  460. /// Many optimizations (such as CSE and LICM) can be performed on such calls
  461. /// to such functions without worrying about aliasing properties, and many
  462. /// functions have this property (e.g. 'sin' and 'cos').
  463. ///
  464. /// This property corresponds to the GCC 'const' attribute.
  465. bool doesNotAccessMemory(const Function *F) {
  466. return getModRefBehavior(F) == FMRB_DoesNotAccessMemory;
  467. }
  468. /// Checks if the specified call is known to only read from non-volatile
  469. /// memory (or not access memory at all).
  470. ///
  471. /// Calls that unwind the stack are legal for this predicate.
  472. ///
  473. /// This property allows many common optimizations to be performed in the
  474. /// absence of interfering store instructions, such as CSE of strlen calls.
  475. ///
  476. /// This property corresponds to the GCC 'pure' attribute.
  477. bool onlyReadsMemory(const CallBase *Call) {
  478. return onlyReadsMemory(getModRefBehavior(Call));
  479. }
  480. /// Checks if the specified function is known to only read from non-volatile
  481. /// memory (or not access memory at all).
  482. ///
  483. /// Functions that unwind the stack are legal for this predicate.
  484. ///
  485. /// This property allows many common optimizations to be performed in the
  486. /// absence of interfering store instructions, such as CSE of strlen calls.
  487. ///
  488. /// This property corresponds to the GCC 'pure' attribute.
  489. bool onlyReadsMemory(const Function *F) {
  490. return onlyReadsMemory(getModRefBehavior(F));
  491. }
  492. /// Checks if functions with the specified behavior are known to only read
  493. /// from non-volatile memory (or not access memory at all).
  494. static bool onlyReadsMemory(FunctionModRefBehavior MRB) {
  495. return !isModSet(createModRefInfo(MRB));
  496. }
  497. /// Checks if functions with the specified behavior are known to only write
  498. /// memory (or not access memory at all).
  499. static bool doesNotReadMemory(FunctionModRefBehavior MRB) {
  500. return !isRefSet(createModRefInfo(MRB));
  501. }
  502. /// Checks if functions with the specified behavior are known to read and
  503. /// write at most from objects pointed to by their pointer-typed arguments
  504. /// (with arbitrary offsets).
  505. static bool onlyAccessesArgPointees(FunctionModRefBehavior MRB) {
  506. return !((unsigned)MRB & FMRL_Anywhere & ~FMRL_ArgumentPointees);
  507. }
  508. /// Checks if functions with the specified behavior are known to potentially
  509. /// read or write from objects pointed to be their pointer-typed arguments
  510. /// (with arbitrary offsets).
  511. static bool doesAccessArgPointees(FunctionModRefBehavior MRB) {
  512. return isModOrRefSet(createModRefInfo(MRB)) &&
  513. ((unsigned)MRB & FMRL_ArgumentPointees);
  514. }
  515. /// Checks if functions with the specified behavior are known to read and
  516. /// write at most from memory that is inaccessible from LLVM IR.
  517. static bool onlyAccessesInaccessibleMem(FunctionModRefBehavior MRB) {
  518. return !((unsigned)MRB & FMRL_Anywhere & ~FMRL_InaccessibleMem);
  519. }
  520. /// Checks if functions with the specified behavior are known to potentially
  521. /// read or write from memory that is inaccessible from LLVM IR.
  522. static bool doesAccessInaccessibleMem(FunctionModRefBehavior MRB) {
  523. return isModOrRefSet(createModRefInfo(MRB)) &&
  524. ((unsigned)MRB & FMRL_InaccessibleMem);
  525. }
  526. /// Checks if functions with the specified behavior are known to read and
  527. /// write at most from memory that is inaccessible from LLVM IR or objects
  528. /// pointed to by their pointer-typed arguments (with arbitrary offsets).
  529. static bool onlyAccessesInaccessibleOrArgMem(FunctionModRefBehavior MRB) {
  530. return !((unsigned)MRB & FMRL_Anywhere &
  531. ~(FMRL_InaccessibleMem | FMRL_ArgumentPointees));
  532. }
  533. /// getModRefInfo (for call sites) - Return information about whether
  534. /// a particular call site modifies or reads the specified memory location.
  535. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc);
  536. /// getModRefInfo (for call sites) - A convenience wrapper.
  537. ModRefInfo getModRefInfo(const CallBase *Call, const Value *P,
  538. LocationSize Size) {
  539. return getModRefInfo(Call, MemoryLocation(P, Size));
  540. }
  541. /// getModRefInfo (for loads) - Return information about whether
  542. /// a particular load modifies or reads the specified memory location.
  543. ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc);
  544. /// getModRefInfo (for loads) - A convenience wrapper.
  545. ModRefInfo getModRefInfo(const LoadInst *L, const Value *P,
  546. LocationSize Size) {
  547. return getModRefInfo(L, MemoryLocation(P, Size));
  548. }
  549. /// getModRefInfo (for stores) - Return information about whether
  550. /// a particular store modifies or reads the specified memory location.
  551. ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc);
  552. /// getModRefInfo (for stores) - A convenience wrapper.
  553. ModRefInfo getModRefInfo(const StoreInst *S, const Value *P,
  554. LocationSize Size) {
  555. return getModRefInfo(S, MemoryLocation(P, Size));
  556. }
  557. /// getModRefInfo (for fences) - Return information about whether
  558. /// a particular store modifies or reads the specified memory location.
  559. ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc);
  560. /// getModRefInfo (for fences) - A convenience wrapper.
  561. ModRefInfo getModRefInfo(const FenceInst *S, const Value *P,
  562. LocationSize Size) {
  563. return getModRefInfo(S, MemoryLocation(P, Size));
  564. }
  565. /// getModRefInfo (for cmpxchges) - Return information about whether
  566. /// a particular cmpxchg modifies or reads the specified memory location.
  567. ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX,
  568. const MemoryLocation &Loc);
  569. /// getModRefInfo (for cmpxchges) - A convenience wrapper.
  570. ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX, const Value *P,
  571. LocationSize Size) {
  572. return getModRefInfo(CX, MemoryLocation(P, Size));
  573. }
  574. /// getModRefInfo (for atomicrmws) - Return information about whether
  575. /// a particular atomicrmw modifies or reads the specified memory location.
  576. ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc);
  577. /// getModRefInfo (for atomicrmws) - A convenience wrapper.
  578. ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const Value *P,
  579. LocationSize Size) {
  580. return getModRefInfo(RMW, MemoryLocation(P, Size));
  581. }
  582. /// getModRefInfo (for va_args) - Return information about whether
  583. /// a particular va_arg modifies or reads the specified memory location.
  584. ModRefInfo getModRefInfo(const VAArgInst *I, const MemoryLocation &Loc);
  585. /// getModRefInfo (for va_args) - A convenience wrapper.
  586. ModRefInfo getModRefInfo(const VAArgInst *I, const Value *P,
  587. LocationSize Size) {
  588. return getModRefInfo(I, MemoryLocation(P, Size));
  589. }
  590. /// getModRefInfo (for catchpads) - Return information about whether
  591. /// a particular catchpad modifies or reads the specified memory location.
  592. ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc);
  593. /// getModRefInfo (for catchpads) - A convenience wrapper.
  594. ModRefInfo getModRefInfo(const CatchPadInst *I, const Value *P,
  595. LocationSize Size) {
  596. return getModRefInfo(I, MemoryLocation(P, Size));
  597. }
  598. /// getModRefInfo (for catchrets) - Return information about whether
  599. /// a particular catchret modifies or reads the specified memory location.
  600. ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc);
  601. /// getModRefInfo (for catchrets) - A convenience wrapper.
  602. ModRefInfo getModRefInfo(const CatchReturnInst *I, const Value *P,
  603. LocationSize Size) {
  604. return getModRefInfo(I, MemoryLocation(P, Size));
  605. }
  606. /// Check whether or not an instruction may read or write the optionally
  607. /// specified memory location.
  608. ///
  609. ///
  610. /// An instruction that doesn't read or write memory may be trivially LICM'd
  611. /// for example.
  612. ///
  613. /// For function calls, this delegates to the alias-analysis specific
  614. /// call-site mod-ref behavior queries. Otherwise it delegates to the specific
  615. /// helpers above.
  616. ModRefInfo getModRefInfo(const Instruction *I,
  617. const Optional<MemoryLocation> &OptLoc) {
  618. AAQueryInfo AAQIP;
  619. return getModRefInfo(I, OptLoc, AAQIP);
  620. }
  621. /// A convenience wrapper for constructing the memory location.
  622. ModRefInfo getModRefInfo(const Instruction *I, const Value *P,
  623. LocationSize Size) {
  624. return getModRefInfo(I, MemoryLocation(P, Size));
  625. }
  626. /// Return information about whether a call and an instruction may refer to
  627. /// the same memory locations.
  628. ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call);
  629. /// Return information about whether two call sites may refer to the same set
  630. /// of memory locations. See the AA documentation for details:
  631. /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
  632. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2);
  633. /// Return information about whether a particular call site modifies
  634. /// or reads the specified memory location \p MemLoc before instruction \p I
  635. /// in a BasicBlock.
  636. /// Early exits in callCapturesBefore may lead to ModRefInfo::Must not being
  637. /// set.
  638. ModRefInfo callCapturesBefore(const Instruction *I,
  639. const MemoryLocation &MemLoc, DominatorTree *DT);
  640. /// A convenience wrapper to synthesize a memory location.
  641. ModRefInfo callCapturesBefore(const Instruction *I, const Value *P,
  642. LocationSize Size, DominatorTree *DT) {
  643. return callCapturesBefore(I, MemoryLocation(P, Size), DT);
  644. }
  645. /// @}
  646. //===--------------------------------------------------------------------===//
  647. /// \name Higher level methods for querying mod/ref information.
  648. /// @{
  649. /// Check if it is possible for execution of the specified basic block to
  650. /// modify the location Loc.
  651. bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc);
  652. /// A convenience wrapper synthesizing a memory location.
  653. bool canBasicBlockModify(const BasicBlock &BB, const Value *P,
  654. LocationSize Size) {
  655. return canBasicBlockModify(BB, MemoryLocation(P, Size));
  656. }
  657. /// Check if it is possible for the execution of the specified instructions
  658. /// to mod\ref (according to the mode) the location Loc.
  659. ///
  660. /// The instructions to consider are all of the instructions in the range of
  661. /// [I1,I2] INCLUSIVE. I1 and I2 must be in the same basic block.
  662. bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
  663. const MemoryLocation &Loc,
  664. const ModRefInfo Mode);
  665. /// A convenience wrapper synthesizing a memory location.
  666. bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
  667. const Value *Ptr, LocationSize Size,
  668. const ModRefInfo Mode) {
  669. return canInstructionRangeModRef(I1, I2, MemoryLocation(Ptr, Size), Mode);
  670. }
  671. private:
  672. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
  673. AAQueryInfo &AAQI);
  674. bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  675. bool OrLocal = false);
  676. ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call2,
  677. AAQueryInfo &AAQIP);
  678. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
  679. AAQueryInfo &AAQI);
  680. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  681. AAQueryInfo &AAQI);
  682. ModRefInfo getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc,
  683. AAQueryInfo &AAQI);
  684. ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc,
  685. AAQueryInfo &AAQI);
  686. ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc,
  687. AAQueryInfo &AAQI);
  688. ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc,
  689. AAQueryInfo &AAQI);
  690. ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX,
  691. const MemoryLocation &Loc, AAQueryInfo &AAQI);
  692. ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc,
  693. AAQueryInfo &AAQI);
  694. ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc,
  695. AAQueryInfo &AAQI);
  696. ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc,
  697. AAQueryInfo &AAQI);
  698. ModRefInfo getModRefInfo(const Instruction *I,
  699. const Optional<MemoryLocation> &OptLoc,
  700. AAQueryInfo &AAQIP);
  701. class Concept;
  702. template <typename T> class Model;
  703. template <typename T> friend class AAResultBase;
  704. const TargetLibraryInfo &TLI;
  705. std::vector<std::unique_ptr<Concept>> AAs;
  706. std::vector<AnalysisKey *> AADeps;
  707. /// Query depth used to distinguish recursive queries.
  708. unsigned Depth = 0;
  709. friend class BatchAAResults;
  710. };
  711. /// This class is a wrapper over an AAResults, and it is intended to be used
  712. /// only when there are no IR changes inbetween queries. BatchAAResults is
  713. /// reusing the same `AAQueryInfo` to preserve the state across queries,
  714. /// esentially making AA work in "batch mode". The internal state cannot be
  715. /// cleared, so to go "out-of-batch-mode", the user must either use AAResults,
  716. /// or create a new BatchAAResults.
  717. class BatchAAResults {
  718. AAResults &AA;
  719. AAQueryInfo AAQI;
  720. public:
  721. BatchAAResults(AAResults &AAR) : AA(AAR), AAQI() {}
  722. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
  723. return AA.alias(LocA, LocB, AAQI);
  724. }
  725. bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) {
  726. return AA.pointsToConstantMemory(Loc, AAQI, OrLocal);
  727. }
  728. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc) {
  729. return AA.getModRefInfo(Call, Loc, AAQI);
  730. }
  731. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2) {
  732. return AA.getModRefInfo(Call1, Call2, AAQI);
  733. }
  734. ModRefInfo getModRefInfo(const Instruction *I,
  735. const Optional<MemoryLocation> &OptLoc) {
  736. return AA.getModRefInfo(I, OptLoc, AAQI);
  737. }
  738. ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call2) {
  739. return AA.getModRefInfo(I, Call2, AAQI);
  740. }
  741. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
  742. return AA.getArgModRefInfo(Call, ArgIdx);
  743. }
  744. FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
  745. return AA.getModRefBehavior(Call);
  746. }
  747. bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
  748. return alias(LocA, LocB) == MustAlias;
  749. }
  750. bool isMustAlias(const Value *V1, const Value *V2) {
  751. return alias(MemoryLocation(V1, LocationSize::precise(1)),
  752. MemoryLocation(V2, LocationSize::precise(1))) == MustAlias;
  753. }
  754. };
  755. /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis
  756. /// pointer or reference.
  757. using AliasAnalysis = AAResults;
  758. /// A private abstract base class describing the concept of an individual alias
  759. /// analysis implementation.
  760. ///
  761. /// This interface is implemented by any \c Model instantiation. It is also the
  762. /// interface which a type used to instantiate the model must provide.
  763. ///
  764. /// All of these methods model methods by the same name in the \c
  765. /// AAResults class. Only differences and specifics to how the
  766. /// implementations are called are documented here.
  767. class AAResults::Concept {
  768. public:
  769. virtual ~Concept() = 0;
  770. /// An update API used internally by the AAResults to provide
  771. /// a handle back to the top level aggregation.
  772. virtual void setAAResults(AAResults *NewAAR) = 0;
  773. //===--------------------------------------------------------------------===//
  774. /// \name Alias Queries
  775. /// @{
  776. /// The main low level interface to the alias analysis implementation.
  777. /// Returns an AliasResult indicating whether the two pointers are aliased to
  778. /// each other. This is the interface that must be implemented by specific
  779. /// alias analysis implementations.
  780. virtual AliasResult alias(const MemoryLocation &LocA,
  781. const MemoryLocation &LocB, AAQueryInfo &AAQI) = 0;
  782. /// Checks whether the given location points to constant memory, or if
  783. /// \p OrLocal is true whether it points to a local alloca.
  784. virtual bool pointsToConstantMemory(const MemoryLocation &Loc,
  785. AAQueryInfo &AAQI, bool OrLocal) = 0;
  786. /// @}
  787. //===--------------------------------------------------------------------===//
  788. /// \name Simple mod/ref information
  789. /// @{
  790. /// Get the ModRef info associated with a pointer argument of a callsite. The
  791. /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
  792. /// that these bits do not necessarily account for the overall behavior of
  793. /// the function, but rather only provide additional per-argument
  794. /// information.
  795. virtual ModRefInfo getArgModRefInfo(const CallBase *Call,
  796. unsigned ArgIdx) = 0;
  797. /// Return the behavior of the given call site.
  798. virtual FunctionModRefBehavior getModRefBehavior(const CallBase *Call) = 0;
  799. /// Return the behavior when calling the given function.
  800. virtual FunctionModRefBehavior getModRefBehavior(const Function *F) = 0;
  801. /// getModRefInfo (for call sites) - Return information about whether
  802. /// a particular call site modifies or reads the specified memory location.
  803. virtual ModRefInfo getModRefInfo(const CallBase *Call,
  804. const MemoryLocation &Loc,
  805. AAQueryInfo &AAQI) = 0;
  806. /// Return information about whether two call sites may refer to the same set
  807. /// of memory locations. See the AA documentation for details:
  808. /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
  809. virtual ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  810. AAQueryInfo &AAQI) = 0;
  811. /// @}
  812. };
  813. /// A private class template which derives from \c Concept and wraps some other
  814. /// type.
  815. ///
  816. /// This models the concept by directly forwarding each interface point to the
  817. /// wrapped type which must implement a compatible interface. This provides
  818. /// a type erased binding.
  819. template <typename AAResultT> class AAResults::Model final : public Concept {
  820. AAResultT &Result;
  821. public:
  822. explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) {
  823. Result.setAAResults(&AAR);
  824. }
  825. ~Model() override = default;
  826. void setAAResults(AAResults *NewAAR) override { Result.setAAResults(NewAAR); }
  827. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
  828. AAQueryInfo &AAQI) override {
  829. return Result.alias(LocA, LocB, AAQI);
  830. }
  831. bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  832. bool OrLocal) override {
  833. return Result.pointsToConstantMemory(Loc, AAQI, OrLocal);
  834. }
  835. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) override {
  836. return Result.getArgModRefInfo(Call, ArgIdx);
  837. }
  838. FunctionModRefBehavior getModRefBehavior(const CallBase *Call) override {
  839. return Result.getModRefBehavior(Call);
  840. }
  841. FunctionModRefBehavior getModRefBehavior(const Function *F) override {
  842. return Result.getModRefBehavior(F);
  843. }
  844. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
  845. AAQueryInfo &AAQI) override {
  846. return Result.getModRefInfo(Call, Loc, AAQI);
  847. }
  848. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  849. AAQueryInfo &AAQI) override {
  850. return Result.getModRefInfo(Call1, Call2, AAQI);
  851. }
  852. };
  853. /// A CRTP-driven "mixin" base class to help implement the function alias
  854. /// analysis results concept.
  855. ///
  856. /// Because of the nature of many alias analysis implementations, they often
  857. /// only implement a subset of the interface. This base class will attempt to
  858. /// implement the remaining portions of the interface in terms of simpler forms
  859. /// of the interface where possible, and otherwise provide conservatively
  860. /// correct fallback implementations.
  861. ///
  862. /// Implementors of an alias analysis should derive from this CRTP, and then
  863. /// override specific methods that they wish to customize. There is no need to
  864. /// use virtual anywhere, the CRTP base class does static dispatch to the
  865. /// derived type passed into it.
  866. template <typename DerivedT> class AAResultBase {
  867. // Expose some parts of the interface only to the AAResults::Model
  868. // for wrapping. Specifically, this allows the model to call our
  869. // setAAResults method without exposing it as a fully public API.
  870. friend class AAResults::Model<DerivedT>;
  871. /// A pointer to the AAResults object that this AAResult is
  872. /// aggregated within. May be null if not aggregated.
  873. AAResults *AAR = nullptr;
  874. /// Helper to dispatch calls back through the derived type.
  875. DerivedT &derived() { return static_cast<DerivedT &>(*this); }
  876. /// A setter for the AAResults pointer, which is used to satisfy the
  877. /// AAResults::Model contract.
  878. void setAAResults(AAResults *NewAAR) { AAR = NewAAR; }
  879. protected:
  880. /// This proxy class models a common pattern where we delegate to either the
  881. /// top-level \c AAResults aggregation if one is registered, or to the
  882. /// current result if none are registered.
  883. class AAResultsProxy {
  884. AAResults *AAR;
  885. DerivedT &CurrentResult;
  886. public:
  887. AAResultsProxy(AAResults *AAR, DerivedT &CurrentResult)
  888. : AAR(AAR), CurrentResult(CurrentResult) {}
  889. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
  890. AAQueryInfo &AAQI) {
  891. return AAR ? AAR->alias(LocA, LocB, AAQI)
  892. : CurrentResult.alias(LocA, LocB, AAQI);
  893. }
  894. bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  895. bool OrLocal) {
  896. return AAR ? AAR->pointsToConstantMemory(Loc, AAQI, OrLocal)
  897. : CurrentResult.pointsToConstantMemory(Loc, AAQI, OrLocal);
  898. }
  899. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
  900. return AAR ? AAR->getArgModRefInfo(Call, ArgIdx)
  901. : CurrentResult.getArgModRefInfo(Call, ArgIdx);
  902. }
  903. FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
  904. return AAR ? AAR->getModRefBehavior(Call)
  905. : CurrentResult.getModRefBehavior(Call);
  906. }
  907. FunctionModRefBehavior getModRefBehavior(const Function *F) {
  908. return AAR ? AAR->getModRefBehavior(F) : CurrentResult.getModRefBehavior(F);
  909. }
  910. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
  911. AAQueryInfo &AAQI) {
  912. return AAR ? AAR->getModRefInfo(Call, Loc, AAQI)
  913. : CurrentResult.getModRefInfo(Call, Loc, AAQI);
  914. }
  915. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  916. AAQueryInfo &AAQI) {
  917. return AAR ? AAR->getModRefInfo(Call1, Call2, AAQI)
  918. : CurrentResult.getModRefInfo(Call1, Call2, AAQI);
  919. }
  920. };
  921. explicit AAResultBase() = default;
  922. // Provide all the copy and move constructors so that derived types aren't
  923. // constrained.
  924. AAResultBase(const AAResultBase &Arg) {}
  925. AAResultBase(AAResultBase &&Arg) {}
  926. /// Get a proxy for the best AA result set to query at this time.
  927. ///
  928. /// When this result is part of a larger aggregation, this will proxy to that
  929. /// aggregation. When this result is used in isolation, it will just delegate
  930. /// back to the derived class's implementation.
  931. ///
  932. /// Note that callers of this need to take considerable care to not cause
  933. /// performance problems when they use this routine, in the case of a large
  934. /// number of alias analyses being aggregated, it can be expensive to walk
  935. /// back across the chain.
  936. AAResultsProxy getBestAAResults() { return AAResultsProxy(AAR, derived()); }
  937. public:
  938. AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
  939. AAQueryInfo &AAQI) {
  940. return MayAlias;
  941. }
  942. bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
  943. bool OrLocal) {
  944. return false;
  945. }
  946. ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
  947. return ModRefInfo::ModRef;
  948. }
  949. FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
  950. return FMRB_UnknownModRefBehavior;
  951. }
  952. FunctionModRefBehavior getModRefBehavior(const Function *F) {
  953. return FMRB_UnknownModRefBehavior;
  954. }
  955. ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
  956. AAQueryInfo &AAQI) {
  957. return ModRefInfo::ModRef;
  958. }
  959. ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
  960. AAQueryInfo &AAQI) {
  961. return ModRefInfo::ModRef;
  962. }
  963. };
  964. /// Return true if this pointer is returned by a noalias function.
  965. bool isNoAliasCall(const Value *V);
  966. /// Return true if this pointer refers to a distinct and identifiable object.
  967. /// This returns true for:
  968. /// Global Variables and Functions (but not Global Aliases)
  969. /// Allocas
  970. /// ByVal and NoAlias Arguments
  971. /// NoAlias returns (e.g. calls to malloc)
  972. ///
  973. bool isIdentifiedObject(const Value *V);
  974. /// Return true if V is umabigously identified at the function-level.
  975. /// Different IdentifiedFunctionLocals can't alias.
  976. /// Further, an IdentifiedFunctionLocal can not alias with any function
  977. /// arguments other than itself, which is not necessarily true for
  978. /// IdentifiedObjects.
  979. bool isIdentifiedFunctionLocal(const Value *V);
  980. /// A manager for alias analyses.
  981. ///
  982. /// This class can have analyses registered with it and when run, it will run
  983. /// all of them and aggregate their results into single AA results interface
  984. /// that dispatches across all of the alias analysis results available.
  985. ///
  986. /// Note that the order in which analyses are registered is very significant.
  987. /// That is the order in which the results will be aggregated and queried.
  988. ///
  989. /// This manager effectively wraps the AnalysisManager for registering alias
  990. /// analyses. When you register your alias analysis with this manager, it will
  991. /// ensure the analysis itself is registered with its AnalysisManager.
  992. ///
  993. /// The result of this analysis is only invalidated if one of the particular
  994. /// aggregated AA results end up being invalidated. This removes the need to
  995. /// explicitly preserve the results of `AAManager`. Note that analyses should no
  996. /// longer be registered once the `AAManager` is run.
  997. class AAManager : public AnalysisInfoMixin<AAManager> {
  998. public:
  999. using Result = AAResults;
  1000. /// Register a specific AA result.
  1001. template <typename AnalysisT> void registerFunctionAnalysis() {
  1002. ResultGetters.push_back(&getFunctionAAResultImpl<AnalysisT>);
  1003. }
  1004. /// Register a specific AA result.
  1005. template <typename AnalysisT> void registerModuleAnalysis() {
  1006. ResultGetters.push_back(&getModuleAAResultImpl<AnalysisT>);
  1007. }
  1008. Result run(Function &F, FunctionAnalysisManager &AM);
  1009. private:
  1010. friend AnalysisInfoMixin<AAManager>;
  1011. static AnalysisKey Key;
  1012. SmallVector<void (*)(Function &F, FunctionAnalysisManager &AM,
  1013. AAResults &AAResults),
  1014. 4> ResultGetters;
  1015. template <typename AnalysisT>
  1016. static void getFunctionAAResultImpl(Function &F,
  1017. FunctionAnalysisManager &AM,
  1018. AAResults &AAResults) {
  1019. AAResults.addAAResult(AM.template getResult<AnalysisT>(F));
  1020. AAResults.addAADependencyID(AnalysisT::ID());
  1021. }
  1022. template <typename AnalysisT>
  1023. static void getModuleAAResultImpl(Function &F, FunctionAnalysisManager &AM,
  1024. AAResults &AAResults) {
  1025. auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
  1026. if (auto *R =
  1027. MAMProxy.template getCachedResult<AnalysisT>(*F.getParent())) {
  1028. AAResults.addAAResult(*R);
  1029. MAMProxy
  1030. .template registerOuterAnalysisInvalidation<AnalysisT, AAManager>();
  1031. }
  1032. }
  1033. };
  1034. /// A wrapper pass to provide the legacy pass manager access to a suitably
  1035. /// prepared AAResults object.
  1036. class AAResultsWrapperPass : public FunctionPass {
  1037. std::unique_ptr<AAResults> AAR;
  1038. public:
  1039. static char ID;
  1040. AAResultsWrapperPass();
  1041. AAResults &getAAResults() { return *AAR; }
  1042. const AAResults &getAAResults() const { return *AAR; }
  1043. bool runOnFunction(Function &F) override;
  1044. void getAnalysisUsage(AnalysisUsage &AU) const override;
  1045. };
  1046. /// A wrapper pass for external alias analyses. This just squirrels away the
  1047. /// callback used to run any analyses and register their results.
  1048. struct ExternalAAWrapperPass : ImmutablePass {
  1049. using CallbackT = std::function<void(Pass &, Function &, AAResults &)>;
  1050. CallbackT CB;
  1051. static char ID;
  1052. ExternalAAWrapperPass();
  1053. explicit ExternalAAWrapperPass(CallbackT CB);
  1054. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1055. AU.setPreservesAll();
  1056. }
  1057. };
  1058. FunctionPass *createAAResultsWrapperPass();
  1059. /// A wrapper pass around a callback which can be used to populate the
  1060. /// AAResults in the AAResultsWrapperPass from an external AA.
  1061. ///
  1062. /// The callback provided here will be used each time we prepare an AAResults
  1063. /// object, and will receive a reference to the function wrapper pass, the
  1064. /// function, and the AAResults object to populate. This should be used when
  1065. /// setting up a custom pass pipeline to inject a hook into the AA results.
  1066. ImmutablePass *createExternalAAWrapperPass(
  1067. std::function<void(Pass &, Function &, AAResults &)> Callback);
  1068. /// A helper for the legacy pass manager to create a \c AAResults
  1069. /// object populated to the best of our ability for a particular function when
  1070. /// inside of a \c ModulePass or a \c CallGraphSCCPass.
  1071. ///
  1072. /// If a \c ModulePass or a \c CallGraphSCCPass calls \p
  1073. /// createLegacyPMAAResults, it also needs to call \p addUsedAAAnalyses in \p
  1074. /// getAnalysisUsage.
  1075. AAResults createLegacyPMAAResults(Pass &P, Function &F, BasicAAResult &BAR);
  1076. /// A helper for the legacy pass manager to populate \p AU to add uses to make
  1077. /// sure the analyses required by \p createLegacyPMAAResults are available.
  1078. void getAAResultsAnalysisUsage(AnalysisUsage &AU);
  1079. } // end namespace llvm
  1080. #endif // LLVM_ANALYSIS_ALIASANALYSIS_H
  1081. #ifdef __GNUC__
  1082. #pragma GCC diagnostic pop
  1083. #endif