FoldingSet.h 30 KB

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