AliasAnalysis.h 55 KB

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