SparseMultiSet.h 18 KB

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