SparseMultiSet.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/SparseMultiSet.h - Sparse multiset --------------*- 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 the SparseMultiSet class, which adds multiset behavior to
  16. /// the SparseSet.
  17. ///
  18. /// A sparse multiset holds a small number of objects identified by integer keys
  19. /// from a moderately sized universe. The sparse multiset uses more memory than
  20. /// other containers in order to provide faster operations. Any key can map to
  21. /// multiple values. A SparseMultiSetNode class is provided, which serves as a
  22. /// convenient base class for the contents of a SparseMultiSet.
  23. ///
  24. //===----------------------------------------------------------------------===//
  25. #ifndef LLVM_ADT_SPARSEMULTISET_H
  26. #define LLVM_ADT_SPARSEMULTISET_H
  27. #include "llvm/ADT/identity.h"
  28. #include "llvm/ADT/SmallVector.h"
  29. #include "llvm/ADT/SparseSet.h"
  30. #include <cassert>
  31. #include <cstdint>
  32. #include <cstdlib>
  33. #include <iterator>
  34. #include <limits>
  35. #include <utility>
  36. namespace llvm {
  37. /// Fast multiset implementation for objects that can be identified by small
  38. /// unsigned keys.
  39. ///
  40. /// SparseMultiSet allocates memory proportional to the size of the key
  41. /// universe, so it is not recommended for building composite data structures.
  42. /// It is useful for algorithms that require a single set with fast operations.
  43. ///
  44. /// Compared to DenseSet and DenseMap, SparseMultiSet provides constant-time
  45. /// fast clear() as fast as a vector. The find(), insert(), and erase()
  46. /// operations are all constant time, and typically faster than a hash table.
  47. /// The iteration order doesn't depend on numerical key values, it only depends
  48. /// on the order of insert() and erase() operations. Iteration order is the
  49. /// insertion order. Iteration is only provided over elements of equivalent
  50. /// keys, but iterators are bidirectional.
  51. ///
  52. /// Compared to BitVector, SparseMultiSet<unsigned> uses 8x-40x more memory, but
  53. /// offers constant-time clear() and size() operations as well as fast iteration
  54. /// independent on the size of the universe.
  55. ///
  56. /// SparseMultiSet contains a dense vector holding all the objects and a sparse
  57. /// array holding indexes into the dense vector. Most of the memory is used by
  58. /// the sparse array which is the size of the key universe. The SparseT template
  59. /// parameter provides a space/speed tradeoff for sets holding many elements.
  60. ///
  61. /// When SparseT is uint32_t, find() only touches up to 3 cache lines, but the
  62. /// sparse array uses 4 x Universe bytes.
  63. ///
  64. /// When SparseT is uint8_t (the default), find() touches up to 3+[N/256] cache
  65. /// lines, but the sparse array is 4x smaller. N is the number of elements in
  66. /// the set.
  67. ///
  68. /// For sets that may grow to thousands of elements, SparseT should be set to
  69. /// uint16_t or uint32_t.
  70. ///
  71. /// Multiset behavior is provided by providing doubly linked lists for values
  72. /// that are inlined in the dense vector. SparseMultiSet is a good choice when
  73. /// one desires a growable number of entries per key, as it will retain the
  74. /// SparseSet algorithmic properties despite being growable. Thus, it is often a
  75. /// better choice than a SparseSet of growable containers or a vector of
  76. /// vectors. SparseMultiSet also keeps iterators valid after erasure (provided
  77. /// the iterators don't point to the element erased), allowing for more
  78. /// intuitive and fast removal.
  79. ///
  80. /// @tparam ValueT The type of objects in the set.
  81. /// @tparam KeyFunctorT A functor that computes an unsigned index from KeyT.
  82. /// @tparam SparseT An unsigned integer type. See above.
  83. ///
  84. template<typename ValueT,
  85. typename KeyFunctorT = identity<unsigned>,
  86. typename SparseT = uint8_t>
  87. class SparseMultiSet {
  88. static_assert(std::is_unsigned_v<SparseT>,
  89. "SparseT must be an unsigned integer type");
  90. /// The actual data that's stored, as a doubly-linked list implemented via
  91. /// indices into the DenseVector. The doubly linked list is implemented
  92. /// circular in Prev indices, and INVALID-terminated in Next indices. This
  93. /// provides efficient access to list tails. These nodes can also be
  94. /// tombstones, in which case they are actually nodes in a single-linked
  95. /// freelist of recyclable slots.
  96. struct SMSNode {
  97. static constexpr unsigned INVALID = ~0U;
  98. ValueT Data;
  99. unsigned Prev;
  100. unsigned Next;
  101. SMSNode(ValueT D, unsigned P, unsigned N) : Data(D), Prev(P), Next(N) {}
  102. /// List tails have invalid Nexts.
  103. bool isTail() const {
  104. return Next == INVALID;
  105. }
  106. /// Whether this node is a tombstone node, and thus is in our freelist.
  107. bool isTombstone() const {
  108. return Prev == INVALID;
  109. }
  110. /// Since the list is circular in Prev, all non-tombstone nodes have a valid
  111. /// Prev.
  112. bool isValid() const { return Prev != INVALID; }
  113. };
  114. using KeyT = typename KeyFunctorT::argument_type;
  115. using DenseT = SmallVector<SMSNode, 8>;
  116. DenseT Dense;
  117. SparseT *Sparse = nullptr;
  118. unsigned Universe = 0;
  119. KeyFunctorT KeyIndexOf;
  120. SparseSetValFunctor<KeyT, ValueT, KeyFunctorT> ValIndexOf;
  121. /// We have a built-in recycler for reusing tombstone slots. This recycler
  122. /// puts a singly-linked free list into tombstone slots, allowing us quick
  123. /// erasure, iterator preservation, and dense size.
  124. unsigned FreelistIdx = SMSNode::INVALID;
  125. unsigned NumFree = 0;
  126. unsigned sparseIndex(const ValueT &Val) const {
  127. assert(ValIndexOf(Val) < Universe &&
  128. "Invalid key in set. Did object mutate?");
  129. return ValIndexOf(Val);
  130. }
  131. unsigned sparseIndex(const SMSNode &N) const { return sparseIndex(N.Data); }
  132. /// Whether the given entry is the head of the list. List heads's previous
  133. /// pointers are to the tail of the list, allowing for efficient access to the
  134. /// list tail. D must be a valid entry node.
  135. bool isHead(const SMSNode &D) const {
  136. assert(D.isValid() && "Invalid node for head");
  137. return Dense[D.Prev].isTail();
  138. }
  139. /// Whether the given entry is a singleton entry, i.e. the only entry with
  140. /// that key.
  141. bool isSingleton(const SMSNode &N) const {
  142. assert(N.isValid() && "Invalid node for singleton");
  143. // Is N its own predecessor?
  144. return &Dense[N.Prev] == &N;
  145. }
  146. /// Add in the given SMSNode. Uses a free entry in our freelist if
  147. /// available. Returns the index of the added node.
  148. unsigned addValue(const ValueT& V, unsigned Prev, unsigned Next) {
  149. if (NumFree == 0) {
  150. Dense.push_back(SMSNode(V, Prev, Next));
  151. return Dense.size() - 1;
  152. }
  153. // Peel off a free slot
  154. unsigned Idx = FreelistIdx;
  155. unsigned NextFree = Dense[Idx].Next;
  156. assert(Dense[Idx].isTombstone() && "Non-tombstone free?");
  157. Dense[Idx] = SMSNode(V, Prev, Next);
  158. FreelistIdx = NextFree;
  159. --NumFree;
  160. return Idx;
  161. }
  162. /// Make the current index a new tombstone. Pushes it onto the freelist.
  163. void makeTombstone(unsigned Idx) {
  164. Dense[Idx].Prev = SMSNode::INVALID;
  165. Dense[Idx].Next = FreelistIdx;
  166. FreelistIdx = Idx;
  167. ++NumFree;
  168. }
  169. public:
  170. using value_type = ValueT;
  171. using reference = ValueT &;
  172. using const_reference = const ValueT &;
  173. using pointer = ValueT *;
  174. using const_pointer = const ValueT *;
  175. using size_type = unsigned;
  176. SparseMultiSet() = default;
  177. SparseMultiSet(const SparseMultiSet &) = delete;
  178. SparseMultiSet &operator=(const SparseMultiSet &) = delete;
  179. ~SparseMultiSet() { free(Sparse); }
  180. /// Set the universe size which determines the largest key the set can hold.
  181. /// The universe must be sized before any elements can be added.
  182. ///
  183. /// @param U Universe size. All object keys must be less than U.
  184. ///
  185. void setUniverse(unsigned U) {
  186. // It's not hard to resize the universe on a non-empty set, but it doesn't
  187. // seem like a likely use case, so we can add that code when we need it.
  188. assert(empty() && "Can only resize universe on an empty map");
  189. // Hysteresis prevents needless reallocations.
  190. if (U >= Universe/4 && U <= Universe)
  191. return;
  192. free(Sparse);
  193. // The Sparse array doesn't actually need to be initialized, so malloc
  194. // would be enough here, but that will cause tools like valgrind to
  195. // complain about branching on uninitialized data.
  196. Sparse = static_cast<SparseT*>(safe_calloc(U, sizeof(SparseT)));
  197. Universe = U;
  198. }
  199. /// Our iterators are iterators over the collection of objects that share a
  200. /// key.
  201. template <typename SMSPtrTy> class iterator_base {
  202. friend class SparseMultiSet;
  203. public:
  204. using iterator_category = std::bidirectional_iterator_tag;
  205. using value_type = ValueT;
  206. using difference_type = std::ptrdiff_t;
  207. using pointer = value_type *;
  208. using reference = value_type &;
  209. private:
  210. SMSPtrTy SMS;
  211. unsigned Idx;
  212. unsigned SparseIdx;
  213. iterator_base(SMSPtrTy P, unsigned I, unsigned SI)
  214. : SMS(P), Idx(I), SparseIdx(SI) {}
  215. /// Whether our iterator has fallen outside our dense vector.
  216. bool isEnd() const {
  217. if (Idx == SMSNode::INVALID)
  218. return true;
  219. assert(Idx < SMS->Dense.size() && "Out of range, non-INVALID Idx?");
  220. return false;
  221. }
  222. /// Whether our iterator is properly keyed, i.e. the SparseIdx is valid
  223. bool isKeyed() const { return SparseIdx < SMS->Universe; }
  224. unsigned Prev() const { return SMS->Dense[Idx].Prev; }
  225. unsigned Next() const { return SMS->Dense[Idx].Next; }
  226. void setPrev(unsigned P) { SMS->Dense[Idx].Prev = P; }
  227. void setNext(unsigned N) { SMS->Dense[Idx].Next = N; }
  228. public:
  229. reference operator*() const {
  230. assert(isKeyed() && SMS->sparseIndex(SMS->Dense[Idx].Data) == SparseIdx &&
  231. "Dereferencing iterator of invalid key or index");
  232. return SMS->Dense[Idx].Data;
  233. }
  234. pointer operator->() const { return &operator*(); }
  235. /// Comparison operators
  236. bool operator==(const iterator_base &RHS) const {
  237. // end compares equal
  238. if (SMS == RHS.SMS && Idx == RHS.Idx) {
  239. assert((isEnd() || SparseIdx == RHS.SparseIdx) &&
  240. "Same dense entry, but different keys?");
  241. return true;
  242. }
  243. return false;
  244. }
  245. bool operator!=(const iterator_base &RHS) const {
  246. return !operator==(RHS);
  247. }
  248. /// Increment and decrement operators
  249. iterator_base &operator--() { // predecrement - Back up
  250. assert(isKeyed() && "Decrementing an invalid iterator");
  251. assert((isEnd() || !SMS->isHead(SMS->Dense[Idx])) &&
  252. "Decrementing head of list");
  253. // If we're at the end, then issue a new find()
  254. if (isEnd())
  255. Idx = SMS->findIndex(SparseIdx).Prev();
  256. else
  257. Idx = Prev();
  258. return *this;
  259. }
  260. iterator_base &operator++() { // preincrement - Advance
  261. assert(!isEnd() && isKeyed() && "Incrementing an invalid/end iterator");
  262. Idx = Next();
  263. return *this;
  264. }
  265. iterator_base operator--(int) { // postdecrement
  266. iterator_base I(*this);
  267. --*this;
  268. return I;
  269. }
  270. iterator_base operator++(int) { // postincrement
  271. iterator_base I(*this);
  272. ++*this;
  273. return I;
  274. }
  275. };
  276. using iterator = iterator_base<SparseMultiSet *>;
  277. using const_iterator = iterator_base<const SparseMultiSet *>;
  278. // Convenience types
  279. using RangePair = std::pair<iterator, iterator>;
  280. /// Returns an iterator past this container. Note that such an iterator cannot
  281. /// be decremented, but will compare equal to other end iterators.
  282. iterator end() { return iterator(this, SMSNode::INVALID, SMSNode::INVALID); }
  283. const_iterator end() const {
  284. return const_iterator(this, SMSNode::INVALID, SMSNode::INVALID);
  285. }
  286. /// Returns true if the set is empty.
  287. ///
  288. /// This is not the same as BitVector::empty().
  289. ///
  290. bool empty() const { return size() == 0; }
  291. /// Returns the number of elements in the set.
  292. ///
  293. /// This is not the same as BitVector::size() which returns the size of the
  294. /// universe.
  295. ///
  296. size_type size() const {
  297. assert(NumFree <= Dense.size() && "Out-of-bounds free entries");
  298. return Dense.size() - NumFree;
  299. }
  300. /// Clears the set. This is a very fast constant time operation.
  301. ///
  302. void clear() {
  303. // Sparse does not need to be cleared, see find().
  304. Dense.clear();
  305. NumFree = 0;
  306. FreelistIdx = SMSNode::INVALID;
  307. }
  308. /// Find an element by its index.
  309. ///
  310. /// @param Idx A valid index to find.
  311. /// @returns An iterator to the element identified by key, or end().
  312. ///
  313. iterator findIndex(unsigned Idx) {
  314. assert(Idx < Universe && "Key out of range");
  315. const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
  316. for (unsigned i = Sparse[Idx], e = Dense.size(); i < e; i += Stride) {
  317. const unsigned FoundIdx = sparseIndex(Dense[i]);
  318. // Check that we're pointing at the correct entry and that it is the head
  319. // of a valid list.
  320. if (Idx == FoundIdx && Dense[i].isValid() && isHead(Dense[i]))
  321. return iterator(this, i, Idx);
  322. // Stride is 0 when SparseT >= unsigned. We don't need to loop.
  323. if (!Stride)
  324. break;
  325. }
  326. return end();
  327. }
  328. /// Find an element by its key.
  329. ///
  330. /// @param Key A valid key to find.
  331. /// @returns An iterator to the element identified by key, or end().
  332. ///
  333. iterator find(const KeyT &Key) {
  334. return findIndex(KeyIndexOf(Key));
  335. }
  336. const_iterator find(const KeyT &Key) const {
  337. iterator I = const_cast<SparseMultiSet*>(this)->findIndex(KeyIndexOf(Key));
  338. return const_iterator(I.SMS, I.Idx, KeyIndexOf(Key));
  339. }
  340. /// Returns the number of elements identified by Key. This will be linear in
  341. /// the number of elements of that key.
  342. size_type count(const KeyT &Key) const {
  343. unsigned Ret = 0;
  344. for (const_iterator It = find(Key); It != end(); ++It)
  345. ++Ret;
  346. return Ret;
  347. }
  348. /// Returns true if this set contains an element identified by Key.
  349. bool contains(const KeyT &Key) const {
  350. return find(Key) != end();
  351. }
  352. /// Return the head and tail of the subset's list, otherwise returns end().
  353. iterator getHead(const KeyT &Key) { return find(Key); }
  354. iterator getTail(const KeyT &Key) {
  355. iterator I = find(Key);
  356. if (I != end())
  357. I = iterator(this, I.Prev(), KeyIndexOf(Key));
  358. return I;
  359. }
  360. /// The bounds of the range of items sharing Key K. First member is the head
  361. /// of the list, and the second member is a decrementable end iterator for
  362. /// that key.
  363. RangePair equal_range(const KeyT &K) {
  364. iterator B = find(K);
  365. iterator E = iterator(this, SMSNode::INVALID, B.SparseIdx);
  366. return std::make_pair(B, E);
  367. }
  368. /// Insert a new element at the tail of the subset list. Returns an iterator
  369. /// to the newly added entry.
  370. iterator insert(const ValueT &Val) {
  371. unsigned Idx = sparseIndex(Val);
  372. iterator I = findIndex(Idx);
  373. unsigned NodeIdx = addValue(Val, SMSNode::INVALID, SMSNode::INVALID);
  374. if (I == end()) {
  375. // Make a singleton list
  376. Sparse[Idx] = NodeIdx;
  377. Dense[NodeIdx].Prev = NodeIdx;
  378. return iterator(this, NodeIdx, Idx);
  379. }
  380. // Stick it at the end.
  381. unsigned HeadIdx = I.Idx;
  382. unsigned TailIdx = I.Prev();
  383. Dense[TailIdx].Next = NodeIdx;
  384. Dense[HeadIdx].Prev = NodeIdx;
  385. Dense[NodeIdx].Prev = TailIdx;
  386. return iterator(this, NodeIdx, Idx);
  387. }
  388. /// Erases an existing element identified by a valid iterator.
  389. ///
  390. /// This invalidates iterators pointing at the same entry, but erase() returns
  391. /// an iterator pointing to the next element in the subset's list. This makes
  392. /// it possible to erase selected elements while iterating over the subset:
  393. ///
  394. /// tie(I, E) = Set.equal_range(Key);
  395. /// while (I != E)
  396. /// if (test(*I))
  397. /// I = Set.erase(I);
  398. /// else
  399. /// ++I;
  400. ///
  401. /// Note that if the last element in the subset list is erased, this will
  402. /// return an end iterator which can be decremented to get the new tail (if it
  403. /// exists):
  404. ///
  405. /// tie(B, I) = Set.equal_range(Key);
  406. /// for (bool isBegin = B == I; !isBegin; /* empty */) {
  407. /// isBegin = (--I) == B;
  408. /// if (test(I))
  409. /// break;
  410. /// I = erase(I);
  411. /// }
  412. iterator erase(iterator I) {
  413. assert(I.isKeyed() && !I.isEnd() && !Dense[I.Idx].isTombstone() &&
  414. "erasing invalid/end/tombstone iterator");
  415. // First, unlink the node from its list. Then swap the node out with the
  416. // dense vector's last entry
  417. iterator NextI = unlink(Dense[I.Idx]);
  418. // Put in a tombstone.
  419. makeTombstone(I.Idx);
  420. return NextI;
  421. }
  422. /// Erase all elements with the given key. This invalidates all
  423. /// iterators of that key.
  424. void eraseAll(const KeyT &K) {
  425. for (iterator I = find(K); I != end(); /* empty */)
  426. I = erase(I);
  427. }
  428. private:
  429. /// Unlink the node from its list. Returns the next node in the list.
  430. iterator unlink(const SMSNode &N) {
  431. if (isSingleton(N)) {
  432. // Singleton is already unlinked
  433. assert(N.Next == SMSNode::INVALID && "Singleton has next?");
  434. return iterator(this, SMSNode::INVALID, ValIndexOf(N.Data));
  435. }
  436. if (isHead(N)) {
  437. // If we're the head, then update the sparse array and our next.
  438. Sparse[sparseIndex(N)] = N.Next;
  439. Dense[N.Next].Prev = N.Prev;
  440. return iterator(this, N.Next, ValIndexOf(N.Data));
  441. }
  442. if (N.isTail()) {
  443. // If we're the tail, then update our head and our previous.
  444. findIndex(sparseIndex(N)).setPrev(N.Prev);
  445. Dense[N.Prev].Next = N.Next;
  446. // Give back an end iterator that can be decremented
  447. iterator I(this, N.Prev, ValIndexOf(N.Data));
  448. return ++I;
  449. }
  450. // Otherwise, just drop us
  451. Dense[N.Next].Prev = N.Prev;
  452. Dense[N.Prev].Next = N.Next;
  453. return iterator(this, N.Next, ValIndexOf(N.Data));
  454. }
  455. };
  456. } // end namespace llvm
  457. #endif // LLVM_ADT_SPARSEMULTISET_H
  458. #ifdef __GNUC__
  459. #pragma GCC diagnostic pop
  460. #endif