SparseMultiSet.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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() { delete[] Sparse; } // HLSL Change: Use overridable operator new
  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. // HLSL Change Begin: Use overridable operator new/delete
  184. delete[] Sparse;
  185. // The Sparse array doesn't actually need to be initialized, so malloc
  186. // would be enough here, but that will cause tools like valgrind to
  187. // complain about branching on uninitialized data.
  188. Sparse = new SparseT[U];
  189. std::memset(Sparse, 0, U * sizeof(SparseT));
  190. // HLSL Change End
  191. Universe = U;
  192. }
  193. /// Our iterators are iterators over the collection of objects that share a
  194. /// key.
  195. template<typename SMSPtrTy>
  196. class iterator_base : public std::iterator<std::bidirectional_iterator_tag,
  197. ValueT> {
  198. friend class SparseMultiSet;
  199. SMSPtrTy SMS;
  200. unsigned Idx;
  201. unsigned SparseIdx;
  202. iterator_base(SMSPtrTy P, unsigned I, unsigned SI)
  203. : SMS(P), Idx(I), SparseIdx(SI) { }
  204. /// Whether our iterator has fallen outside our dense vector.
  205. bool isEnd() const {
  206. if (Idx == SMSNode::INVALID)
  207. return true;
  208. assert(Idx < SMS->Dense.size() && "Out of range, non-INVALID Idx?");
  209. return false;
  210. }
  211. /// Whether our iterator is properly keyed, i.e. the SparseIdx is valid
  212. bool isKeyed() const { return SparseIdx < SMS->Universe; }
  213. unsigned Prev() const { return SMS->Dense[Idx].Prev; }
  214. unsigned Next() const { return SMS->Dense[Idx].Next; }
  215. void setPrev(unsigned P) { SMS->Dense[Idx].Prev = P; }
  216. void setNext(unsigned N) { SMS->Dense[Idx].Next = N; }
  217. public:
  218. typedef std::iterator<std::bidirectional_iterator_tag, ValueT> super;
  219. typedef typename super::value_type value_type;
  220. typedef typename super::difference_type difference_type;
  221. typedef typename super::pointer pointer;
  222. typedef typename super::reference reference;
  223. reference operator*() const {
  224. assert(isKeyed() && SMS->sparseIndex(SMS->Dense[Idx].Data) == SparseIdx &&
  225. "Dereferencing iterator of invalid key or index");
  226. return SMS->Dense[Idx].Data;
  227. }
  228. pointer operator->() const { return &operator*(); }
  229. /// Comparison operators
  230. bool operator==(const iterator_base &RHS) const {
  231. // end compares equal
  232. if (SMS == RHS.SMS && Idx == RHS.Idx) {
  233. assert((isEnd() || SparseIdx == RHS.SparseIdx) &&
  234. "Same dense entry, but different keys?");
  235. return true;
  236. }
  237. return false;
  238. }
  239. bool operator!=(const iterator_base &RHS) const {
  240. return !operator==(RHS);
  241. }
  242. /// Increment and decrement operators
  243. iterator_base &operator--() { // predecrement - Back up
  244. assert(isKeyed() && "Decrementing an invalid iterator");
  245. assert((isEnd() || !SMS->isHead(SMS->Dense[Idx])) &&
  246. "Decrementing head of list");
  247. // If we're at the end, then issue a new find()
  248. if (isEnd())
  249. Idx = SMS->findIndex(SparseIdx).Prev();
  250. else
  251. Idx = Prev();
  252. return *this;
  253. }
  254. iterator_base &operator++() { // preincrement - Advance
  255. assert(!isEnd() && isKeyed() && "Incrementing an invalid/end iterator");
  256. Idx = Next();
  257. return *this;
  258. }
  259. iterator_base operator--(int) { // postdecrement
  260. iterator_base I(*this);
  261. --*this;
  262. return I;
  263. }
  264. iterator_base operator++(int) { // postincrement
  265. iterator_base I(*this);
  266. ++*this;
  267. return I;
  268. }
  269. };
  270. typedef iterator_base<SparseMultiSet *> iterator;
  271. typedef iterator_base<const SparseMultiSet *> const_iterator;
  272. // Convenience types
  273. typedef std::pair<iterator, iterator> RangePair;
  274. /// Returns an iterator past this container. Note that such an iterator cannot
  275. /// be decremented, but will compare equal to other end iterators.
  276. iterator end() { return iterator(this, SMSNode::INVALID, SMSNode::INVALID); }
  277. const_iterator end() const {
  278. return const_iterator(this, SMSNode::INVALID, SMSNode::INVALID);
  279. }
  280. /// Returns true if the set is empty.
  281. ///
  282. /// This is not the same as BitVector::empty().
  283. ///
  284. bool empty() const { return size() == 0; }
  285. /// Returns the number of elements in the set.
  286. ///
  287. /// This is not the same as BitVector::size() which returns the size of the
  288. /// universe.
  289. ///
  290. size_type size() const {
  291. assert(NumFree <= Dense.size() && "Out-of-bounds free entries");
  292. return Dense.size() - NumFree;
  293. }
  294. /// Clears the set. This is a very fast constant time operation.
  295. ///
  296. void clear() {
  297. // Sparse does not need to be cleared, see find().
  298. Dense.clear();
  299. NumFree = 0;
  300. FreelistIdx = SMSNode::INVALID;
  301. }
  302. /// Find an element by its index.
  303. ///
  304. /// @param Idx A valid index to find.
  305. /// @returns An iterator to the element identified by key, or end().
  306. ///
  307. iterator findIndex(unsigned Idx) {
  308. assert(Idx < Universe && "Key out of range");
  309. const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
  310. for (unsigned i = Sparse[Idx], e = Dense.size(); i < e; i += Stride) {
  311. const unsigned FoundIdx = sparseIndex(Dense[i]);
  312. // Check that we're pointing at the correct entry and that it is the head
  313. // of a valid list.
  314. if (Idx == FoundIdx && Dense[i].isValid() && isHead(Dense[i]))
  315. return iterator(this, i, Idx);
  316. // Stride is 0 when SparseT >= unsigned. We don't need to loop.
  317. if (!Stride)
  318. break;
  319. }
  320. return end();
  321. }
  322. /// Find an element by its key.
  323. ///
  324. /// @param Key A valid key to find.
  325. /// @returns An iterator to the element identified by key, or end().
  326. ///
  327. iterator find(const KeyT &Key) {
  328. return findIndex(KeyIndexOf(Key));
  329. }
  330. const_iterator find(const KeyT &Key) const {
  331. iterator I = const_cast<SparseMultiSet*>(this)->findIndex(KeyIndexOf(Key));
  332. return const_iterator(I.SMS, I.Idx, KeyIndexOf(Key));
  333. }
  334. /// Returns the number of elements identified by Key. This will be linear in
  335. /// the number of elements of that key.
  336. size_type count(const KeyT &Key) const {
  337. unsigned Ret = 0;
  338. for (const_iterator It = find(Key); It != end(); ++It)
  339. ++Ret;
  340. return Ret;
  341. }
  342. /// Returns true if this set contains an element identified by Key.
  343. bool contains(const KeyT &Key) const {
  344. return find(Key) != end();
  345. }
  346. /// Return the head and tail of the subset's list, otherwise returns end().
  347. iterator getHead(const KeyT &Key) { return find(Key); }
  348. iterator getTail(const KeyT &Key) {
  349. iterator I = find(Key);
  350. if (I != end())
  351. I = iterator(this, I.Prev(), KeyIndexOf(Key));
  352. return I;
  353. }
  354. /// The bounds of the range of items sharing Key K. First member is the head
  355. /// of the list, and the second member is a decrementable end iterator for
  356. /// that key.
  357. RangePair equal_range(const KeyT &K) {
  358. iterator B = find(K);
  359. iterator E = iterator(this, SMSNode::INVALID, B.SparseIdx);
  360. return make_pair(B, E);
  361. }
  362. /// Insert a new element at the tail of the subset list. Returns an iterator
  363. /// to the newly added entry.
  364. iterator insert(const ValueT &Val) {
  365. unsigned Idx = sparseIndex(Val);
  366. iterator I = findIndex(Idx);
  367. unsigned NodeIdx = addValue(Val, SMSNode::INVALID, SMSNode::INVALID);
  368. if (I == end()) {
  369. // Make a singleton list
  370. Sparse[Idx] = NodeIdx;
  371. Dense[NodeIdx].Prev = NodeIdx;
  372. return iterator(this, NodeIdx, Idx);
  373. }
  374. // Stick it at the end.
  375. unsigned HeadIdx = I.Idx;
  376. unsigned TailIdx = I.Prev();
  377. Dense[TailIdx].Next = NodeIdx;
  378. Dense[HeadIdx].Prev = NodeIdx;
  379. Dense[NodeIdx].Prev = TailIdx;
  380. return iterator(this, NodeIdx, Idx);
  381. }
  382. /// Erases an existing element identified by a valid iterator.
  383. ///
  384. /// This invalidates iterators pointing at the same entry, but erase() returns
  385. /// an iterator pointing to the next element in the subset's list. This makes
  386. /// it possible to erase selected elements while iterating over the subset:
  387. ///
  388. /// tie(I, E) = Set.equal_range(Key);
  389. /// while (I != E)
  390. /// if (test(*I))
  391. /// I = Set.erase(I);
  392. /// else
  393. /// ++I;
  394. ///
  395. /// Note that if the last element in the subset list is erased, this will
  396. /// return an end iterator which can be decremented to get the new tail (if it
  397. /// exists):
  398. ///
  399. /// tie(B, I) = Set.equal_range(Key);
  400. /// for (bool isBegin = B == I; !isBegin; /* empty */) {
  401. /// isBegin = (--I) == B;
  402. /// if (test(I))
  403. /// break;
  404. /// I = erase(I);
  405. /// }
  406. iterator erase(iterator I) {
  407. assert(I.isKeyed() && !I.isEnd() && !Dense[I.Idx].isTombstone() &&
  408. "erasing invalid/end/tombstone iterator");
  409. // First, unlink the node from its list. Then swap the node out with the
  410. // dense vector's last entry
  411. iterator NextI = unlink(Dense[I.Idx]);
  412. // Put in a tombstone.
  413. makeTombstone(I.Idx);
  414. return NextI;
  415. }
  416. /// Erase all elements with the given key. This invalidates all
  417. /// iterators of that key.
  418. void eraseAll(const KeyT &K) {
  419. for (iterator I = find(K); I != end(); /* empty */)
  420. I = erase(I);
  421. }
  422. private:
  423. /// Unlink the node from its list. Returns the next node in the list.
  424. iterator unlink(const SMSNode &N) {
  425. if (isSingleton(N)) {
  426. // Singleton is already unlinked
  427. assert(N.Next == SMSNode::INVALID && "Singleton has next?");
  428. return iterator(this, SMSNode::INVALID, ValIndexOf(N.Data));
  429. }
  430. if (isHead(N)) {
  431. // If we're the head, then update the sparse array and our next.
  432. Sparse[sparseIndex(N)] = N.Next;
  433. Dense[N.Next].Prev = N.Prev;
  434. return iterator(this, N.Next, ValIndexOf(N.Data));
  435. }
  436. if (N.isTail()) {
  437. // If we're the tail, then update our head and our previous.
  438. findIndex(sparseIndex(N)).setPrev(N.Prev);
  439. Dense[N.Prev].Next = N.Next;
  440. // Give back an end iterator that can be decremented
  441. iterator I(this, N.Prev, ValIndexOf(N.Data));
  442. return ++I;
  443. }
  444. // Otherwise, just drop us
  445. Dense[N.Next].Prev = N.Prev;
  446. Dense[N.Prev].Next = N.Next;
  447. return iterator(this, N.Next, ValIndexOf(N.Data));
  448. }
  449. };
  450. } // end namespace llvm
  451. #endif