FoldingSet.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/FoldingSet.h - Uniquing Hash Set ----------------*- 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 a hash set that can be used to remove duplication of nodes
  15. // in a graph. This code was originally created by Chris Lattner for use with
  16. // SelectionDAGCSEMap, but was isolated to provide use across the llvm code set.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_ADT_FOLDINGSET_H
  20. #define LLVM_ADT_FOLDINGSET_H
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/iterator.h"
  23. #include "llvm/Support/Allocator.h"
  24. #include <cassert>
  25. #include <cstddef>
  26. #include <cstdint>
  27. #include <utility>
  28. namespace llvm {
  29. /// This folding set used for two purposes:
  30. /// 1. Given information about a node we want to create, look up the unique
  31. /// instance of the node in the set. If the node already exists, return
  32. /// it, otherwise return the bucket it should be inserted into.
  33. /// 2. Given a node that has already been created, remove it from the set.
  34. ///
  35. /// This class is implemented as a single-link chained hash table, where the
  36. /// "buckets" are actually the nodes themselves (the next pointer is in the
  37. /// node). The last node points back to the bucket to simplify node removal.
  38. ///
  39. /// Any node that is to be included in the folding set must be a subclass of
  40. /// FoldingSetNode. The node class must also define a Profile method used to
  41. /// establish the unique bits of data for the node. The Profile method is
  42. /// passed a FoldingSetNodeID object which is used to gather the bits. Just
  43. /// call one of the Add* functions defined in the FoldingSetBase::NodeID class.
  44. /// NOTE: That the folding set does not own the nodes and it is the
  45. /// responsibility of the user to dispose of the nodes.
  46. ///
  47. /// Eg.
  48. /// class MyNode : public FoldingSetNode {
  49. /// private:
  50. /// std::string Name;
  51. /// unsigned Value;
  52. /// public:
  53. /// MyNode(const char *N, unsigned V) : Name(N), Value(V) {}
  54. /// ...
  55. /// void Profile(FoldingSetNodeID &ID) const {
  56. /// ID.AddString(Name);
  57. /// ID.AddInteger(Value);
  58. /// }
  59. /// ...
  60. /// };
  61. ///
  62. /// To define the folding set itself use the FoldingSet template;
  63. ///
  64. /// Eg.
  65. /// FoldingSet<MyNode> MyFoldingSet;
  66. ///
  67. /// Four public methods are available to manipulate the folding set;
  68. ///
  69. /// 1) If you have an existing node that you want add to the set but unsure
  70. /// that the node might already exist then call;
  71. ///
  72. /// MyNode *M = MyFoldingSet.GetOrInsertNode(N);
  73. ///
  74. /// If The result is equal to the input then the node has been inserted.
  75. /// Otherwise, the result is the node existing in the folding set, and the
  76. /// input can be discarded (use the result instead.)
  77. ///
  78. /// 2) If you are ready to construct a node but want to check if it already
  79. /// exists, then call FindNodeOrInsertPos with a FoldingSetNodeID of the bits to
  80. /// check;
  81. ///
  82. /// FoldingSetNodeID ID;
  83. /// ID.AddString(Name);
  84. /// ID.AddInteger(Value);
  85. /// void *InsertPoint;
  86. ///
  87. /// MyNode *M = MyFoldingSet.FindNodeOrInsertPos(ID, InsertPoint);
  88. ///
  89. /// If found then M will be non-NULL, else InsertPoint will point to where it
  90. /// should be inserted using InsertNode.
  91. ///
  92. /// 3) If you get a NULL result from FindNodeOrInsertPos then you can insert a
  93. /// new node with InsertNode;
  94. ///
  95. /// MyFoldingSet.InsertNode(M, InsertPoint);
  96. ///
  97. /// 4) Finally, if you want to remove a node from the folding set call;
  98. ///
  99. /// bool WasRemoved = MyFoldingSet.RemoveNode(M);
  100. ///
  101. /// The result indicates whether the node existed in the folding set.
  102. class FoldingSetNodeID;
  103. class StringRef;
  104. //===----------------------------------------------------------------------===//
  105. /// FoldingSetBase - Implements the folding set functionality. The main
  106. /// structure is an array of buckets. Each bucket is indexed by the hash of
  107. /// the nodes it contains. The bucket itself points to the nodes contained
  108. /// in the bucket via a singly linked list. The last node in the list points
  109. /// back to the bucket to facilitate node removal.
  110. ///
  111. class FoldingSetBase {
  112. protected:
  113. /// Buckets - Array of bucket chains.
  114. void **Buckets;
  115. /// NumBuckets - Length of the Buckets array. Always a power of 2.
  116. unsigned NumBuckets;
  117. /// NumNodes - Number of nodes in the folding set. Growth occurs when NumNodes
  118. /// is greater than twice the number of buckets.
  119. unsigned NumNodes;
  120. explicit FoldingSetBase(unsigned Log2InitSize = 6);
  121. FoldingSetBase(FoldingSetBase &&Arg);
  122. FoldingSetBase &operator=(FoldingSetBase &&RHS);
  123. ~FoldingSetBase();
  124. public:
  125. //===--------------------------------------------------------------------===//
  126. /// Node - This class is used to maintain the singly linked bucket list in
  127. /// a folding set.
  128. class Node {
  129. private:
  130. // NextInFoldingSetBucket - next link in the bucket list.
  131. void *NextInFoldingSetBucket = nullptr;
  132. public:
  133. Node() = default;
  134. // Accessors
  135. void *getNextInBucket() const { return NextInFoldingSetBucket; }
  136. void SetNextInBucket(void *N) { NextInFoldingSetBucket = N; }
  137. };
  138. /// clear - Remove all nodes from the folding set.
  139. void clear();
  140. /// size - Returns the number of nodes in the folding set.
  141. unsigned size() const { return NumNodes; }
  142. /// empty - Returns true if there are no nodes in the folding set.
  143. bool empty() const { return NumNodes == 0; }
  144. /// capacity - Returns the number of nodes permitted in the folding set
  145. /// before a rebucket operation is performed.
  146. unsigned capacity() {
  147. // We allow a load factor of up to 2.0,
  148. // so that means our capacity is NumBuckets * 2
  149. return NumBuckets * 2;
  150. }
  151. protected:
  152. /// Functions provided by the derived class to compute folding properties.
  153. /// This is effectively a vtable for FoldingSetBase, except that we don't
  154. /// actually store a pointer to it in the object.
  155. struct FoldingSetInfo {
  156. /// GetNodeProfile - Instantiations of the FoldingSet template implement
  157. /// this function to gather data bits for the given node.
  158. void (*GetNodeProfile)(const FoldingSetBase *Self, Node *N,
  159. FoldingSetNodeID &ID);
  160. /// NodeEquals - Instantiations of the FoldingSet template implement
  161. /// this function to compare the given node with the given ID.
  162. bool (*NodeEquals)(const FoldingSetBase *Self, Node *N,
  163. const FoldingSetNodeID &ID, unsigned IDHash,
  164. FoldingSetNodeID &TempID);
  165. /// ComputeNodeHash - Instantiations of the FoldingSet template implement
  166. /// this function to compute a hash value for the given node.
  167. unsigned (*ComputeNodeHash)(const FoldingSetBase *Self, Node *N,
  168. FoldingSetNodeID &TempID);
  169. };
  170. private:
  171. /// GrowHashTable - Double the size of the hash table and rehash everything.
  172. void GrowHashTable(const FoldingSetInfo &Info);
  173. /// GrowBucketCount - resize the hash table and rehash everything.
  174. /// NewBucketCount must be a power of two, and must be greater than the old
  175. /// bucket count.
  176. void GrowBucketCount(unsigned NewBucketCount, const FoldingSetInfo &Info);
  177. protected:
  178. // The below methods are protected to encourage subclasses to provide a more
  179. // type-safe API.
  180. /// reserve - Increase the number of buckets such that adding the
  181. /// EltCount-th node won't cause a rebucket operation. reserve is permitted
  182. /// to allocate more space than requested by EltCount.
  183. void reserve(unsigned EltCount, const FoldingSetInfo &Info);
  184. /// RemoveNode - Remove a node from the folding set, returning true if one
  185. /// was removed or false if the node was not in the folding set.
  186. bool RemoveNode(Node *N);
  187. /// GetOrInsertNode - If there is an existing simple Node exactly
  188. /// equal to the specified node, return it. Otherwise, insert 'N' and return
  189. /// it instead.
  190. Node *GetOrInsertNode(Node *N, const FoldingSetInfo &Info);
  191. /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
  192. /// return it. If not, return the insertion token that will make insertion
  193. /// faster.
  194. Node *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos,
  195. const FoldingSetInfo &Info);
  196. /// InsertNode - Insert the specified node into the folding set, knowing that
  197. /// it is not already in the folding set. InsertPos must be obtained from
  198. /// FindNodeOrInsertPos.
  199. void InsertNode(Node *N, void *InsertPos, const FoldingSetInfo &Info);
  200. };
  201. //===----------------------------------------------------------------------===//
  202. /// DefaultFoldingSetTrait - This class provides default implementations
  203. /// for FoldingSetTrait implementations.
  204. template<typename T> struct DefaultFoldingSetTrait {
  205. static void Profile(const T &X, FoldingSetNodeID &ID) {
  206. X.Profile(ID);
  207. }
  208. static void Profile(T &X, FoldingSetNodeID &ID) {
  209. X.Profile(ID);
  210. }
  211. // Equals - Test if the profile for X would match ID, using TempID
  212. // to compute a temporary ID if necessary. The default implementation
  213. // just calls Profile and does a regular comparison. Implementations
  214. // can override this to provide more efficient implementations.
  215. static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash,
  216. FoldingSetNodeID &TempID);
  217. // ComputeHash - Compute a hash value for X, using TempID to
  218. // compute a temporary ID if necessary. The default implementation
  219. // just calls Profile and does a regular hash computation.
  220. // Implementations can override this to provide more efficient
  221. // implementations.
  222. static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID);
  223. };
  224. /// FoldingSetTrait - This trait class is used to define behavior of how
  225. /// to "profile" (in the FoldingSet parlance) an object of a given type.
  226. /// The default behavior is to invoke a 'Profile' method on an object, but
  227. /// through template specialization the behavior can be tailored for specific
  228. /// types. Combined with the FoldingSetNodeWrapper class, one can add objects
  229. /// to FoldingSets that were not originally designed to have that behavior.
  230. template<typename T> struct FoldingSetTrait
  231. : public DefaultFoldingSetTrait<T> {};
  232. /// DefaultContextualFoldingSetTrait - Like DefaultFoldingSetTrait, but
  233. /// for ContextualFoldingSets.
  234. template<typename T, typename Ctx>
  235. struct DefaultContextualFoldingSetTrait {
  236. static void Profile(T &X, FoldingSetNodeID &ID, Ctx Context) {
  237. X.Profile(ID, Context);
  238. }
  239. static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash,
  240. FoldingSetNodeID &TempID, Ctx Context);
  241. static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID,
  242. Ctx Context);
  243. };
  244. /// ContextualFoldingSetTrait - Like FoldingSetTrait, but for
  245. /// ContextualFoldingSets.
  246. template<typename T, typename Ctx> struct ContextualFoldingSetTrait
  247. : public DefaultContextualFoldingSetTrait<T, Ctx> {};
  248. //===--------------------------------------------------------------------===//
  249. /// FoldingSetNodeIDRef - This class describes a reference to an interned
  250. /// FoldingSetNodeID, which can be a useful to store node id data rather
  251. /// than using plain FoldingSetNodeIDs, since the 32-element SmallVector
  252. /// is often much larger than necessary, and the possibility of heap
  253. /// allocation means it requires a non-trivial destructor call.
  254. class FoldingSetNodeIDRef {
  255. const unsigned *Data = nullptr;
  256. size_t Size = 0;
  257. public:
  258. FoldingSetNodeIDRef() = default;
  259. FoldingSetNodeIDRef(const unsigned *D, size_t S) : Data(D), Size(S) {}
  260. /// ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef,
  261. /// used to lookup the node in the FoldingSetBase.
  262. unsigned ComputeHash() const;
  263. bool operator==(FoldingSetNodeIDRef) const;
  264. bool operator!=(FoldingSetNodeIDRef RHS) const { return !(*this == RHS); }
  265. /// Used to compare the "ordering" of two nodes as defined by the
  266. /// profiled bits and their ordering defined by memcmp().
  267. bool operator<(FoldingSetNodeIDRef) const;
  268. const unsigned *getData() const { return Data; }
  269. size_t getSize() const { return Size; }
  270. };
  271. //===--------------------------------------------------------------------===//
  272. /// FoldingSetNodeID - This class is used to gather all the unique data bits of
  273. /// a node. When all the bits are gathered this class is used to produce a
  274. /// hash value for the node.
  275. class FoldingSetNodeID {
  276. /// Bits - Vector of all the data bits that make the node unique.
  277. /// Use a SmallVector to avoid a heap allocation in the common case.
  278. SmallVector<unsigned, 32> Bits;
  279. public:
  280. FoldingSetNodeID() = default;
  281. FoldingSetNodeID(FoldingSetNodeIDRef Ref)
  282. : Bits(Ref.getData(), Ref.getData() + Ref.getSize()) {}
  283. /// Add* - Add various data types to Bit data.
  284. void AddPointer(const void *Ptr);
  285. void AddInteger(signed I);
  286. void AddInteger(unsigned I);
  287. void AddInteger(long I);
  288. void AddInteger(unsigned long I);
  289. void AddInteger(long long I);
  290. void AddInteger(unsigned long long I);
  291. void AddBoolean(bool B) { AddInteger(B ? 1U : 0U); }
  292. void AddString(StringRef String);
  293. void AddNodeID(const FoldingSetNodeID &ID);
  294. template <typename T>
  295. inline void Add(const T &x) { FoldingSetTrait<T>::Profile(x, *this); }
  296. /// clear - Clear the accumulated profile, allowing this FoldingSetNodeID
  297. /// object to be used to compute a new profile.
  298. inline void clear() { Bits.clear(); }
  299. /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used
  300. /// to lookup the node in the FoldingSetBase.
  301. unsigned ComputeHash() const;
  302. /// operator== - Used to compare two nodes to each other.
  303. bool operator==(const FoldingSetNodeID &RHS) const;
  304. bool operator==(const FoldingSetNodeIDRef RHS) const;
  305. bool operator!=(const FoldingSetNodeID &RHS) const { return !(*this == RHS); }
  306. bool operator!=(const FoldingSetNodeIDRef RHS) const { return !(*this ==RHS);}
  307. /// Used to compare the "ordering" of two nodes as defined by the
  308. /// profiled bits and their ordering defined by memcmp().
  309. bool operator<(const FoldingSetNodeID &RHS) const;
  310. bool operator<(const FoldingSetNodeIDRef RHS) const;
  311. /// Intern - Copy this node's data to a memory region allocated from the
  312. /// given allocator and return a FoldingSetNodeIDRef describing the
  313. /// interned data.
  314. FoldingSetNodeIDRef Intern(BumpPtrAllocator &Allocator) const;
  315. };
  316. // Convenience type to hide the implementation of the folding set.
  317. using FoldingSetNode = FoldingSetBase::Node;
  318. template<class T> class FoldingSetIterator;
  319. template<class T> class FoldingSetBucketIterator;
  320. // Definitions of FoldingSetTrait and ContextualFoldingSetTrait functions, which
  321. // require the definition of FoldingSetNodeID.
  322. template<typename T>
  323. inline bool
  324. DefaultFoldingSetTrait<T>::Equals(T &X, const FoldingSetNodeID &ID,
  325. unsigned /*IDHash*/,
  326. FoldingSetNodeID &TempID) {
  327. FoldingSetTrait<T>::Profile(X, TempID);
  328. return TempID == ID;
  329. }
  330. template<typename T>
  331. inline unsigned
  332. DefaultFoldingSetTrait<T>::ComputeHash(T &X, FoldingSetNodeID &TempID) {
  333. FoldingSetTrait<T>::Profile(X, TempID);
  334. return TempID.ComputeHash();
  335. }
  336. template<typename T, typename Ctx>
  337. inline bool
  338. DefaultContextualFoldingSetTrait<T, Ctx>::Equals(T &X,
  339. const FoldingSetNodeID &ID,
  340. unsigned /*IDHash*/,
  341. FoldingSetNodeID &TempID,
  342. Ctx Context) {
  343. ContextualFoldingSetTrait<T, Ctx>::Profile(X, TempID, Context);
  344. return TempID == ID;
  345. }
  346. template<typename T, typename Ctx>
  347. inline unsigned
  348. DefaultContextualFoldingSetTrait<T, Ctx>::ComputeHash(T &X,
  349. FoldingSetNodeID &TempID,
  350. Ctx Context) {
  351. ContextualFoldingSetTrait<T, Ctx>::Profile(X, TempID, Context);
  352. return TempID.ComputeHash();
  353. }
  354. //===----------------------------------------------------------------------===//
  355. /// FoldingSetImpl - An implementation detail that lets us share code between
  356. /// FoldingSet and ContextualFoldingSet.
  357. template <class Derived, class T> class FoldingSetImpl : public FoldingSetBase {
  358. protected:
  359. explicit FoldingSetImpl(unsigned Log2InitSize)
  360. : FoldingSetBase(Log2InitSize) {}
  361. FoldingSetImpl(FoldingSetImpl &&Arg) = default;
  362. FoldingSetImpl &operator=(FoldingSetImpl &&RHS) = default;
  363. ~FoldingSetImpl() = default;
  364. public:
  365. using iterator = FoldingSetIterator<T>;
  366. iterator begin() { return iterator(Buckets); }
  367. iterator end() { return iterator(Buckets+NumBuckets); }
  368. using const_iterator = FoldingSetIterator<const T>;
  369. const_iterator begin() const { return const_iterator(Buckets); }
  370. const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
  371. using bucket_iterator = FoldingSetBucketIterator<T>;
  372. bucket_iterator bucket_begin(unsigned hash) {
  373. return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
  374. }
  375. bucket_iterator bucket_end(unsigned hash) {
  376. return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
  377. }
  378. /// reserve - Increase the number of buckets such that adding the
  379. /// EltCount-th node won't cause a rebucket operation. reserve is permitted
  380. /// to allocate more space than requested by EltCount.
  381. void reserve(unsigned EltCount) {
  382. return FoldingSetBase::reserve(EltCount, Derived::getFoldingSetInfo());
  383. }
  384. /// RemoveNode - Remove a node from the folding set, returning true if one
  385. /// was removed or false if the node was not in the folding set.
  386. bool RemoveNode(T *N) {
  387. return FoldingSetBase::RemoveNode(N);
  388. }
  389. /// GetOrInsertNode - If there is an existing simple Node exactly
  390. /// equal to the specified node, return it. Otherwise, insert 'N' and
  391. /// return it instead.
  392. T *GetOrInsertNode(T *N) {
  393. return static_cast<T *>(
  394. FoldingSetBase::GetOrInsertNode(N, Derived::getFoldingSetInfo()));
  395. }
  396. /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
  397. /// return it. If not, return the insertion token that will make insertion
  398. /// faster.
  399. T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
  400. return static_cast<T *>(FoldingSetBase::FindNodeOrInsertPos(
  401. ID, InsertPos, Derived::getFoldingSetInfo()));
  402. }
  403. /// InsertNode - Insert the specified node into the folding set, knowing that
  404. /// it is not already in the folding set. InsertPos must be obtained from
  405. /// FindNodeOrInsertPos.
  406. void InsertNode(T *N, void *InsertPos) {
  407. FoldingSetBase::InsertNode(N, InsertPos, Derived::getFoldingSetInfo());
  408. }
  409. /// InsertNode - Insert the specified node into the folding set, knowing that
  410. /// it is not already in the folding set.
  411. void InsertNode(T *N) {
  412. T *Inserted = GetOrInsertNode(N);
  413. (void)Inserted;
  414. assert(Inserted == N && "Node already inserted!");
  415. }
  416. };
  417. //===----------------------------------------------------------------------===//
  418. /// FoldingSet - This template class is used to instantiate a specialized
  419. /// implementation of the folding set to the node class T. T must be a
  420. /// subclass of FoldingSetNode and implement a Profile function.
  421. ///
  422. /// Note that this set type is movable and move-assignable. However, its
  423. /// moved-from state is not a valid state for anything other than
  424. /// move-assigning and destroying. This is primarily to enable movable APIs
  425. /// that incorporate these objects.
  426. template <class T>
  427. class FoldingSet : public FoldingSetImpl<FoldingSet<T>, T> {
  428. using Super = FoldingSetImpl<FoldingSet, T>;
  429. using Node = typename Super::Node;
  430. /// GetNodeProfile - Each instantiation of the FoldingSet needs to provide a
  431. /// way to convert nodes into a unique specifier.
  432. static void GetNodeProfile(const FoldingSetBase *, Node *N,
  433. FoldingSetNodeID &ID) {
  434. T *TN = static_cast<T *>(N);
  435. FoldingSetTrait<T>::Profile(*TN, ID);
  436. }
  437. /// NodeEquals - Instantiations may optionally provide a way to compare a
  438. /// node with a specified ID.
  439. static bool NodeEquals(const FoldingSetBase *, Node *N,
  440. const FoldingSetNodeID &ID, unsigned IDHash,
  441. FoldingSetNodeID &TempID) {
  442. T *TN = static_cast<T *>(N);
  443. return FoldingSetTrait<T>::Equals(*TN, ID, IDHash, TempID);
  444. }
  445. /// ComputeNodeHash - Instantiations may optionally provide a way to compute a
  446. /// hash value directly from a node.
  447. static unsigned ComputeNodeHash(const FoldingSetBase *, Node *N,
  448. FoldingSetNodeID &TempID) {
  449. T *TN = static_cast<T *>(N);
  450. return FoldingSetTrait<T>::ComputeHash(*TN, TempID);
  451. }
  452. static const FoldingSetBase::FoldingSetInfo &getFoldingSetInfo() {
  453. static constexpr FoldingSetBase::FoldingSetInfo Info = {
  454. GetNodeProfile, NodeEquals, ComputeNodeHash};
  455. return Info;
  456. }
  457. friend Super;
  458. public:
  459. explicit FoldingSet(unsigned Log2InitSize = 6) : Super(Log2InitSize) {}
  460. FoldingSet(FoldingSet &&Arg) = default;
  461. FoldingSet &operator=(FoldingSet &&RHS) = default;
  462. };
  463. //===----------------------------------------------------------------------===//
  464. /// ContextualFoldingSet - This template class is a further refinement
  465. /// of FoldingSet which provides a context argument when calling
  466. /// Profile on its nodes. Currently, that argument is fixed at
  467. /// initialization time.
  468. ///
  469. /// T must be a subclass of FoldingSetNode and implement a Profile
  470. /// function with signature
  471. /// void Profile(FoldingSetNodeID &, Ctx);
  472. template <class T, class Ctx>
  473. class ContextualFoldingSet
  474. : public FoldingSetImpl<ContextualFoldingSet<T, Ctx>, T> {
  475. // Unfortunately, this can't derive from FoldingSet<T> because the
  476. // construction of the vtable for FoldingSet<T> requires
  477. // FoldingSet<T>::GetNodeProfile to be instantiated, which in turn
  478. // requires a single-argument T::Profile().
  479. using Super = FoldingSetImpl<ContextualFoldingSet, T>;
  480. using Node = typename Super::Node;
  481. Ctx Context;
  482. static const Ctx &getContext(const FoldingSetBase *Base) {
  483. return static_cast<const ContextualFoldingSet*>(Base)->Context;
  484. }
  485. /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
  486. /// way to convert nodes into a unique specifier.
  487. static void GetNodeProfile(const FoldingSetBase *Base, Node *N,
  488. FoldingSetNodeID &ID) {
  489. T *TN = static_cast<T *>(N);
  490. ContextualFoldingSetTrait<T, Ctx>::Profile(*TN, ID, getContext(Base));
  491. }
  492. static bool NodeEquals(const FoldingSetBase *Base, Node *N,
  493. const FoldingSetNodeID &ID, unsigned IDHash,
  494. FoldingSetNodeID &TempID) {
  495. T *TN = static_cast<T *>(N);
  496. return ContextualFoldingSetTrait<T, Ctx>::Equals(*TN, ID, IDHash, TempID,
  497. getContext(Base));
  498. }
  499. static unsigned ComputeNodeHash(const FoldingSetBase *Base, Node *N,
  500. FoldingSetNodeID &TempID) {
  501. T *TN = static_cast<T *>(N);
  502. return ContextualFoldingSetTrait<T, Ctx>::ComputeHash(*TN, TempID,
  503. getContext(Base));
  504. }
  505. static const FoldingSetBase::FoldingSetInfo &getFoldingSetInfo() {
  506. static constexpr FoldingSetBase::FoldingSetInfo Info = {
  507. GetNodeProfile, NodeEquals, ComputeNodeHash};
  508. return Info;
  509. }
  510. friend Super;
  511. public:
  512. explicit ContextualFoldingSet(Ctx Context, unsigned Log2InitSize = 6)
  513. : Super(Log2InitSize), Context(Context) {}
  514. Ctx getContext() const { return Context; }
  515. };
  516. //===----------------------------------------------------------------------===//
  517. /// FoldingSetVector - This template class combines a FoldingSet and a vector
  518. /// to provide the interface of FoldingSet but with deterministic iteration
  519. /// order based on the insertion order. T must be a subclass of FoldingSetNode
  520. /// and implement a Profile function.
  521. template <class T, class VectorT = SmallVector<T*, 8>>
  522. class FoldingSetVector {
  523. FoldingSet<T> Set;
  524. VectorT Vector;
  525. public:
  526. explicit FoldingSetVector(unsigned Log2InitSize = 6) : Set(Log2InitSize) {}
  527. using iterator = pointee_iterator<typename VectorT::iterator>;
  528. iterator begin() { return Vector.begin(); }
  529. iterator end() { return Vector.end(); }
  530. using const_iterator = pointee_iterator<typename VectorT::const_iterator>;
  531. const_iterator begin() const { return Vector.begin(); }
  532. const_iterator end() const { return Vector.end(); }
  533. /// clear - Remove all nodes from the folding set.
  534. void clear() { Set.clear(); Vector.clear(); }
  535. /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
  536. /// return it. If not, return the insertion token that will make insertion
  537. /// faster.
  538. T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
  539. return Set.FindNodeOrInsertPos(ID, InsertPos);
  540. }
  541. /// GetOrInsertNode - If there is an existing simple Node exactly
  542. /// equal to the specified node, return it. Otherwise, insert 'N' and
  543. /// return it instead.
  544. T *GetOrInsertNode(T *N) {
  545. T *Result = Set.GetOrInsertNode(N);
  546. if (Result == N) Vector.push_back(N);
  547. return Result;
  548. }
  549. /// InsertNode - Insert the specified node into the folding set, knowing that
  550. /// it is not already in the folding set. InsertPos must be obtained from
  551. /// FindNodeOrInsertPos.
  552. void InsertNode(T *N, void *InsertPos) {
  553. Set.InsertNode(N, InsertPos);
  554. Vector.push_back(N);
  555. }
  556. /// InsertNode - Insert the specified node into the folding set, knowing that
  557. /// it is not already in the folding set.
  558. void InsertNode(T *N) {
  559. Set.InsertNode(N);
  560. Vector.push_back(N);
  561. }
  562. /// size - Returns the number of nodes in the folding set.
  563. unsigned size() const { return Set.size(); }
  564. /// empty - Returns true if there are no nodes in the folding set.
  565. bool empty() const { return Set.empty(); }
  566. };
  567. //===----------------------------------------------------------------------===//
  568. /// FoldingSetIteratorImpl - This is the common iterator support shared by all
  569. /// folding sets, which knows how to walk the folding set hash table.
  570. class FoldingSetIteratorImpl {
  571. protected:
  572. FoldingSetNode *NodePtr;
  573. FoldingSetIteratorImpl(void **Bucket);
  574. void advance();
  575. public:
  576. bool operator==(const FoldingSetIteratorImpl &RHS) const {
  577. return NodePtr == RHS.NodePtr;
  578. }
  579. bool operator!=(const FoldingSetIteratorImpl &RHS) const {
  580. return NodePtr != RHS.NodePtr;
  581. }
  582. };
  583. template <class T> class FoldingSetIterator : public FoldingSetIteratorImpl {
  584. public:
  585. explicit FoldingSetIterator(void **Bucket) : FoldingSetIteratorImpl(Bucket) {}
  586. T &operator*() const {
  587. return *static_cast<T*>(NodePtr);
  588. }
  589. T *operator->() const {
  590. return static_cast<T*>(NodePtr);
  591. }
  592. inline FoldingSetIterator &operator++() { // Preincrement
  593. advance();
  594. return *this;
  595. }
  596. FoldingSetIterator operator++(int) { // Postincrement
  597. FoldingSetIterator tmp = *this; ++*this; return tmp;
  598. }
  599. };
  600. //===----------------------------------------------------------------------===//
  601. /// FoldingSetBucketIteratorImpl - This is the common bucket iterator support
  602. /// shared by all folding sets, which knows how to walk a particular bucket
  603. /// of a folding set hash table.
  604. class FoldingSetBucketIteratorImpl {
  605. protected:
  606. void *Ptr;
  607. explicit FoldingSetBucketIteratorImpl(void **Bucket);
  608. FoldingSetBucketIteratorImpl(void **Bucket, bool) : Ptr(Bucket) {}
  609. void advance() {
  610. void *Probe = static_cast<FoldingSetNode*>(Ptr)->getNextInBucket();
  611. uintptr_t x = reinterpret_cast<uintptr_t>(Probe) & ~0x1;
  612. Ptr = reinterpret_cast<void*>(x);
  613. }
  614. public:
  615. bool operator==(const FoldingSetBucketIteratorImpl &RHS) const {
  616. return Ptr == RHS.Ptr;
  617. }
  618. bool operator!=(const FoldingSetBucketIteratorImpl &RHS) const {
  619. return Ptr != RHS.Ptr;
  620. }
  621. };
  622. template <class T>
  623. class FoldingSetBucketIterator : public FoldingSetBucketIteratorImpl {
  624. public:
  625. explicit FoldingSetBucketIterator(void **Bucket) :
  626. FoldingSetBucketIteratorImpl(Bucket) {}
  627. FoldingSetBucketIterator(void **Bucket, bool) :
  628. FoldingSetBucketIteratorImpl(Bucket, true) {}
  629. T &operator*() const { return *static_cast<T*>(Ptr); }
  630. T *operator->() const { return static_cast<T*>(Ptr); }
  631. inline FoldingSetBucketIterator &operator++() { // Preincrement
  632. advance();
  633. return *this;
  634. }
  635. FoldingSetBucketIterator operator++(int) { // Postincrement
  636. FoldingSetBucketIterator tmp = *this; ++*this; return tmp;
  637. }
  638. };
  639. //===----------------------------------------------------------------------===//
  640. /// FoldingSetNodeWrapper - This template class is used to "wrap" arbitrary
  641. /// types in an enclosing object so that they can be inserted into FoldingSets.
  642. template <typename T>
  643. class FoldingSetNodeWrapper : public FoldingSetNode {
  644. T data;
  645. public:
  646. template <typename... Ts>
  647. explicit FoldingSetNodeWrapper(Ts &&... Args)
  648. : data(std::forward<Ts>(Args)...) {}
  649. void Profile(FoldingSetNodeID &ID) { FoldingSetTrait<T>::Profile(data, ID); }
  650. T &getValue() { return data; }
  651. const T &getValue() const { return data; }
  652. operator T&() { return data; }
  653. operator const T&() const { return data; }
  654. };
  655. //===----------------------------------------------------------------------===//
  656. /// FastFoldingSetNode - This is a subclass of FoldingSetNode which stores
  657. /// a FoldingSetNodeID value rather than requiring the node to recompute it
  658. /// each time it is needed. This trades space for speed (which can be
  659. /// significant if the ID is long), and it also permits nodes to drop
  660. /// information that would otherwise only be required for recomputing an ID.
  661. class FastFoldingSetNode : public FoldingSetNode {
  662. FoldingSetNodeID FastID;
  663. protected:
  664. explicit FastFoldingSetNode(const FoldingSetNodeID &ID) : FastID(ID) {}
  665. public:
  666. void Profile(FoldingSetNodeID &ID) const { ID.AddNodeID(FastID); }
  667. };
  668. //===----------------------------------------------------------------------===//
  669. // Partial specializations of FoldingSetTrait.
  670. template<typename T> struct FoldingSetTrait<T*> {
  671. static inline void Profile(T *X, FoldingSetNodeID &ID) {
  672. ID.AddPointer(X);
  673. }
  674. };
  675. template <typename T1, typename T2>
  676. struct FoldingSetTrait<std::pair<T1, T2>> {
  677. static inline void Profile(const std::pair<T1, T2> &P,
  678. FoldingSetNodeID &ID) {
  679. ID.Add(P.first);
  680. ID.Add(P.second);
  681. }
  682. };
  683. } // end namespace llvm
  684. #endif // LLVM_ADT_FOLDINGSET_H
  685. #ifdef __GNUC__
  686. #pragma GCC diagnostic pop
  687. #endif