SparseMultiSet.h 18 KB

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