AliasSetTracker.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Analysis/AliasSetTracker.h - Build Alias Sets -------*- 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 two classes: AliasSetTracker and AliasSet. These interfaces
  15. // are used to classify a collection of pointer references into a maximal number
  16. // of disjoint sets. Each AliasSet object constructed by the AliasSetTracker
  17. // object refers to memory disjoint from the other sets.
  18. //
  19. // An AliasSetTracker can only be used on immutable IR.
  20. //
  21. //===----------------------------------------------------------------------===//
  22. #ifndef LLVM_ANALYSIS_ALIASSETTRACKER_H
  23. #define LLVM_ANALYSIS_ALIASSETTRACKER_H
  24. #include "llvm/ADT/DenseMap.h"
  25. #include "llvm/ADT/DenseMapInfo.h"
  26. #include "llvm/ADT/ilist.h"
  27. #include "llvm/ADT/ilist_node.h"
  28. #include "llvm/Analysis/MemoryLocation.h"
  29. #include "llvm/IR/Instruction.h"
  30. #include "llvm/IR/PassManager.h"
  31. #include "llvm/IR/ValueHandle.h"
  32. #include <cassert>
  33. #include <cstddef>
  34. #include <iterator>
  35. #include <vector>
  36. namespace llvm {
  37. class AliasResult;
  38. class AliasSetTracker;
  39. class AnyMemSetInst;
  40. class AnyMemTransferInst;
  41. class BasicBlock;
  42. class BatchAAResults;
  43. class LoadInst;
  44. enum class ModRefInfo : uint8_t;
  45. class raw_ostream;
  46. class StoreInst;
  47. class VAArgInst;
  48. class Value;
  49. class AliasSet : public ilist_node<AliasSet> {
  50. friend class AliasSetTracker;
  51. class PointerRec {
  52. Value *Val; // The pointer this record corresponds to.
  53. PointerRec **PrevInList = nullptr;
  54. PointerRec *NextInList = nullptr;
  55. AliasSet *AS = nullptr;
  56. LocationSize Size = LocationSize::mapEmpty();
  57. AAMDNodes AAInfo;
  58. // Whether the size for this record has been set at all. This makes no
  59. // guarantees about the size being known.
  60. bool isSizeSet() const { return Size != LocationSize::mapEmpty(); }
  61. public:
  62. PointerRec(Value *V)
  63. : Val(V), AAInfo(DenseMapInfo<AAMDNodes>::getEmptyKey()) {}
  64. Value *getValue() const { return Val; }
  65. PointerRec *getNext() const { return NextInList; }
  66. bool hasAliasSet() const { return AS != nullptr; }
  67. PointerRec** setPrevInList(PointerRec **PIL) {
  68. PrevInList = PIL;
  69. return &NextInList;
  70. }
  71. bool updateSizeAndAAInfo(LocationSize NewSize, const AAMDNodes &NewAAInfo) {
  72. bool SizeChanged = false;
  73. if (NewSize != Size) {
  74. LocationSize OldSize = Size;
  75. Size = isSizeSet() ? Size.unionWith(NewSize) : NewSize;
  76. SizeChanged = OldSize != Size;
  77. }
  78. if (AAInfo == DenseMapInfo<AAMDNodes>::getEmptyKey())
  79. // We don't have a AAInfo yet. Set it to NewAAInfo.
  80. AAInfo = NewAAInfo;
  81. else {
  82. AAMDNodes Intersection(AAInfo.intersect(NewAAInfo));
  83. SizeChanged |= Intersection != AAInfo;
  84. AAInfo = Intersection;
  85. }
  86. return SizeChanged;
  87. }
  88. LocationSize getSize() const {
  89. assert(isSizeSet() && "Getting an unset size!");
  90. return Size;
  91. }
  92. /// Return the AAInfo, or null if there is no information or conflicting
  93. /// information.
  94. AAMDNodes getAAInfo() const {
  95. // If we have missing or conflicting AAInfo, return null.
  96. if (AAInfo == DenseMapInfo<AAMDNodes>::getEmptyKey() ||
  97. AAInfo == DenseMapInfo<AAMDNodes>::getTombstoneKey())
  98. return AAMDNodes();
  99. return AAInfo;
  100. }
  101. AliasSet *getAliasSet(AliasSetTracker &AST) {
  102. assert(AS && "No AliasSet yet!");
  103. if (AS->Forward) {
  104. AliasSet *OldAS = AS;
  105. AS = OldAS->getForwardedTarget(AST);
  106. AS->addRef();
  107. OldAS->dropRef(AST);
  108. }
  109. return AS;
  110. }
  111. void setAliasSet(AliasSet *as) {
  112. assert(!AS && "Already have an alias set!");
  113. AS = as;
  114. }
  115. void eraseFromList() {
  116. if (NextInList) NextInList->PrevInList = PrevInList;
  117. *PrevInList = NextInList;
  118. if (AS->PtrListEnd == &NextInList) {
  119. AS->PtrListEnd = PrevInList;
  120. assert(*AS->PtrListEnd == nullptr && "List not terminated right!");
  121. }
  122. delete this;
  123. }
  124. };
  125. // Doubly linked list of nodes.
  126. PointerRec *PtrList = nullptr;
  127. PointerRec **PtrListEnd;
  128. // Forwarding pointer.
  129. AliasSet *Forward = nullptr;
  130. /// All instructions without a specific address in this alias set.
  131. std::vector<AssertingVH<Instruction>> UnknownInsts;
  132. /// Number of nodes pointing to this AliasSet plus the number of AliasSets
  133. /// forwarding to it.
  134. unsigned RefCount : 27;
  135. // Signifies that this set should be considered to alias any pointer.
  136. // Use when the tracker holding this set is saturated.
  137. unsigned AliasAny : 1;
  138. /// The kinds of access this alias set models.
  139. ///
  140. /// We keep track of whether this alias set merely refers to the locations of
  141. /// memory (and not any particular access), whether it modifies or references
  142. /// the memory, or whether it does both. The lattice goes from "NoAccess" to
  143. /// either RefAccess or ModAccess, then to ModRefAccess as necessary.
  144. enum AccessLattice {
  145. NoAccess = 0,
  146. RefAccess = 1,
  147. ModAccess = 2,
  148. ModRefAccess = RefAccess | ModAccess
  149. };
  150. unsigned Access : 2;
  151. /// The kind of alias relationship between pointers of the set.
  152. ///
  153. /// These represent conservatively correct alias results between any members
  154. /// of the set. We represent these independently of the values of alias
  155. /// results in order to pack it into a single bit. Lattice goes from
  156. /// MustAlias to MayAlias.
  157. enum AliasLattice {
  158. SetMustAlias = 0, SetMayAlias = 1
  159. };
  160. unsigned Alias : 1;
  161. unsigned SetSize = 0;
  162. void addRef() { ++RefCount; }
  163. void dropRef(AliasSetTracker &AST) {
  164. assert(RefCount >= 1 && "Invalid reference count detected!");
  165. if (--RefCount == 0)
  166. removeFromTracker(AST);
  167. }
  168. public:
  169. AliasSet(const AliasSet &) = delete;
  170. AliasSet &operator=(const AliasSet &) = delete;
  171. /// Accessors...
  172. bool isRef() const { return Access & RefAccess; }
  173. bool isMod() const { return Access & ModAccess; }
  174. bool isMustAlias() const { return Alias == SetMustAlias; }
  175. bool isMayAlias() const { return Alias == SetMayAlias; }
  176. /// Return true if this alias set should be ignored as part of the
  177. /// AliasSetTracker object.
  178. bool isForwardingAliasSet() const { return Forward; }
  179. /// Merge the specified alias set into this alias set.
  180. void mergeSetIn(AliasSet &AS, AliasSetTracker &AST, BatchAAResults &BatchAA);
  181. // Alias Set iteration - Allow access to all of the pointers which are part of
  182. // this alias set.
  183. class iterator;
  184. iterator begin() const { return iterator(PtrList); }
  185. iterator end() const { return iterator(); }
  186. bool empty() const { return PtrList == nullptr; }
  187. // Unfortunately, ilist::size() is linear, so we have to add code to keep
  188. // track of the list's exact size.
  189. unsigned size() { return SetSize; }
  190. void print(raw_ostream &OS) const;
  191. void dump() const;
  192. /// Define an iterator for alias sets... this is just a forward iterator.
  193. class iterator {
  194. PointerRec *CurNode;
  195. public:
  196. using iterator_category = std::forward_iterator_tag;
  197. using value_type = PointerRec;
  198. using difference_type = std::ptrdiff_t;
  199. using pointer = value_type *;
  200. using reference = value_type &;
  201. explicit iterator(PointerRec *CN = nullptr) : CurNode(CN) {}
  202. bool operator==(const iterator& x) const {
  203. return CurNode == x.CurNode;
  204. }
  205. bool operator!=(const iterator& x) const { return !operator==(x); }
  206. value_type &operator*() const {
  207. assert(CurNode && "Dereferencing AliasSet.end()!");
  208. return *CurNode;
  209. }
  210. value_type *operator->() const { return &operator*(); }
  211. Value *getPointer() const { return CurNode->getValue(); }
  212. LocationSize getSize() const { return CurNode->getSize(); }
  213. AAMDNodes getAAInfo() const { return CurNode->getAAInfo(); }
  214. iterator& operator++() { // Preincrement
  215. assert(CurNode && "Advancing past AliasSet.end()!");
  216. CurNode = CurNode->getNext();
  217. return *this;
  218. }
  219. iterator operator++(int) { // Postincrement
  220. iterator tmp = *this; ++*this; return tmp;
  221. }
  222. };
  223. private:
  224. // Can only be created by AliasSetTracker.
  225. AliasSet()
  226. : PtrListEnd(&PtrList), RefCount(0), AliasAny(false), Access(NoAccess),
  227. Alias(SetMustAlias) {}
  228. PointerRec *getSomePointer() const {
  229. return PtrList;
  230. }
  231. /// Return the real alias set this represents. If this has been merged with
  232. /// another set and is forwarding, return the ultimate destination set. This
  233. /// also implements the union-find collapsing as well.
  234. AliasSet *getForwardedTarget(AliasSetTracker &AST) {
  235. if (!Forward) return this;
  236. AliasSet *Dest = Forward->getForwardedTarget(AST);
  237. if (Dest != Forward) {
  238. Dest->addRef();
  239. Forward->dropRef(AST);
  240. Forward = Dest;
  241. }
  242. return Dest;
  243. }
  244. void removeFromTracker(AliasSetTracker &AST);
  245. void addPointer(AliasSetTracker &AST, PointerRec &Entry, LocationSize Size,
  246. const AAMDNodes &AAInfo, bool KnownMustAlias = false,
  247. bool SkipSizeUpdate = false);
  248. void addUnknownInst(Instruction *I, BatchAAResults &AA);
  249. public:
  250. /// If the specified pointer "may" (or must) alias one of the members in the
  251. /// set return the appropriate AliasResult. Otherwise return NoAlias.
  252. AliasResult aliasesPointer(const Value *Ptr, LocationSize Size,
  253. const AAMDNodes &AAInfo, BatchAAResults &AA) const;
  254. ModRefInfo aliasesUnknownInst(const Instruction *Inst,
  255. BatchAAResults &AA) const;
  256. };
  257. inline raw_ostream& operator<<(raw_ostream &OS, const AliasSet &AS) {
  258. AS.print(OS);
  259. return OS;
  260. }
  261. class AliasSetTracker {
  262. BatchAAResults &AA;
  263. ilist<AliasSet> AliasSets;
  264. using PointerMapType = DenseMap<AssertingVH<Value>, AliasSet::PointerRec *>;
  265. // Map from pointers to their node
  266. PointerMapType PointerMap;
  267. public:
  268. /// Create an empty collection of AliasSets, and use the specified alias
  269. /// analysis object to disambiguate load and store addresses.
  270. explicit AliasSetTracker(BatchAAResults &AA) : AA(AA) {}
  271. ~AliasSetTracker() { clear(); }
  272. /// These methods are used to add different types of instructions to the alias
  273. /// sets. Adding a new instruction can result in one of three actions
  274. /// happening:
  275. ///
  276. /// 1. If the instruction doesn't alias any other sets, create a new set.
  277. /// 2. If the instruction aliases exactly one set, add it to the set
  278. /// 3. If the instruction aliases multiple sets, merge the sets, and add
  279. /// the instruction to the result.
  280. ///
  281. /// These methods return true if inserting the instruction resulted in the
  282. /// addition of a new alias set (i.e., the pointer did not alias anything).
  283. ///
  284. void add(Value *Ptr, LocationSize Size, const AAMDNodes &AAInfo); // Add a loc
  285. void add(LoadInst *LI);
  286. void add(StoreInst *SI);
  287. void add(VAArgInst *VAAI);
  288. void add(AnyMemSetInst *MSI);
  289. void add(AnyMemTransferInst *MTI);
  290. void add(Instruction *I); // Dispatch to one of the other add methods...
  291. void add(BasicBlock &BB); // Add all instructions in basic block
  292. void add(const AliasSetTracker &AST); // Add alias relations from another AST
  293. void addUnknown(Instruction *I);
  294. void clear();
  295. /// Return the alias sets that are active.
  296. const ilist<AliasSet> &getAliasSets() const { return AliasSets; }
  297. /// Return the alias set which contains the specified memory location. If
  298. /// the memory location aliases two or more existing alias sets, will have
  299. /// the effect of merging those alias sets before the single resulting alias
  300. /// set is returned.
  301. AliasSet &getAliasSetFor(const MemoryLocation &MemLoc);
  302. /// Return the underlying alias analysis object used by this tracker.
  303. BatchAAResults &getAliasAnalysis() const { return AA; }
  304. using iterator = ilist<AliasSet>::iterator;
  305. using const_iterator = ilist<AliasSet>::const_iterator;
  306. const_iterator begin() const { return AliasSets.begin(); }
  307. const_iterator end() const { return AliasSets.end(); }
  308. iterator begin() { return AliasSets.begin(); }
  309. iterator end() { return AliasSets.end(); }
  310. void print(raw_ostream &OS) const;
  311. void dump() const;
  312. private:
  313. friend class AliasSet;
  314. // The total number of pointers contained in all "may" alias sets.
  315. unsigned TotalMayAliasSetSize = 0;
  316. // A non-null value signifies this AST is saturated. A saturated AST lumps
  317. // all pointers into a single "May" set.
  318. AliasSet *AliasAnyAS = nullptr;
  319. void removeAliasSet(AliasSet *AS);
  320. /// Just like operator[] on the map, except that it creates an entry for the
  321. /// pointer if it doesn't already exist.
  322. AliasSet::PointerRec &getEntryFor(Value *V) {
  323. AliasSet::PointerRec *&Entry = PointerMap[V];
  324. if (!Entry)
  325. Entry = new AliasSet::PointerRec(V);
  326. return *Entry;
  327. }
  328. AliasSet &addPointer(MemoryLocation Loc, AliasSet::AccessLattice E);
  329. AliasSet *mergeAliasSetsForPointer(const Value *Ptr, LocationSize Size,
  330. const AAMDNodes &AAInfo,
  331. bool &MustAliasAll);
  332. /// Merge all alias sets into a single set that is considered to alias any
  333. /// pointer.
  334. AliasSet &mergeAllAliasSets();
  335. AliasSet *findAliasSetForUnknownInst(Instruction *Inst);
  336. };
  337. inline raw_ostream& operator<<(raw_ostream &OS, const AliasSetTracker &AST) {
  338. AST.print(OS);
  339. return OS;
  340. }
  341. class AliasSetsPrinterPass : public PassInfoMixin<AliasSetsPrinterPass> {
  342. raw_ostream &OS;
  343. public:
  344. explicit AliasSetsPrinterPass(raw_ostream &OS);
  345. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  346. };
  347. } // end namespace llvm
  348. #endif // LLVM_ANALYSIS_ALIASSETTRACKER_H
  349. #ifdef __GNUC__
  350. #pragma GCC diagnostic pop
  351. #endif