Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:09

0001 //===- llvm/ADT/SparseMultiSet.h - Sparse multiset --------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 ///
0009 /// \file
0010 /// This file defines the SparseMultiSet class, which adds multiset behavior to
0011 /// the SparseSet.
0012 ///
0013 /// A sparse multiset holds a small number of objects identified by integer keys
0014 /// from a moderately sized universe. The sparse multiset uses more memory than
0015 /// other containers in order to provide faster operations. Any key can map to
0016 /// multiple values. A SparseMultiSetNode class is provided, which serves as a
0017 /// convenient base class for the contents of a SparseMultiSet.
0018 ///
0019 //===----------------------------------------------------------------------===//
0020 
0021 #ifndef LLVM_ADT_SPARSEMULTISET_H
0022 #define LLVM_ADT_SPARSEMULTISET_H
0023 
0024 #include "llvm/ADT/identity.h"
0025 #include "llvm/ADT/SmallVector.h"
0026 #include "llvm/ADT/SparseSet.h"
0027 #include <cassert>
0028 #include <cstdint>
0029 #include <cstdlib>
0030 #include <iterator>
0031 #include <limits>
0032 #include <utility>
0033 
0034 namespace llvm {
0035 
0036 /// Fast multiset implementation for objects that can be identified by small
0037 /// unsigned keys.
0038 ///
0039 /// SparseMultiSet allocates memory proportional to the size of the key
0040 /// universe, so it is not recommended for building composite data structures.
0041 /// It is useful for algorithms that require a single set with fast operations.
0042 ///
0043 /// Compared to DenseSet and DenseMap, SparseMultiSet provides constant-time
0044 /// fast clear() as fast as a vector.  The find(), insert(), and erase()
0045 /// operations are all constant time, and typically faster than a hash table.
0046 /// The iteration order doesn't depend on numerical key values, it only depends
0047 /// on the order of insert() and erase() operations.  Iteration order is the
0048 /// insertion order. Iteration is only provided over elements of equivalent
0049 /// keys, but iterators are bidirectional.
0050 ///
0051 /// Compared to BitVector, SparseMultiSet<unsigned> uses 8x-40x more memory, but
0052 /// offers constant-time clear() and size() operations as well as fast iteration
0053 /// independent on the size of the universe.
0054 ///
0055 /// SparseMultiSet contains a dense vector holding all the objects and a sparse
0056 /// array holding indexes into the dense vector.  Most of the memory is used by
0057 /// the sparse array which is the size of the key universe. The SparseT template
0058 /// parameter provides a space/speed tradeoff for sets holding many elements.
0059 ///
0060 /// When SparseT is uint32_t, find() only touches up to 3 cache lines, but the
0061 /// sparse array uses 4 x Universe bytes.
0062 ///
0063 /// When SparseT is uint8_t (the default), find() touches up to 3+[N/256] cache
0064 /// lines, but the sparse array is 4x smaller.  N is the number of elements in
0065 /// the set.
0066 ///
0067 /// For sets that may grow to thousands of elements, SparseT should be set to
0068 /// uint16_t or uint32_t.
0069 ///
0070 /// Multiset behavior is provided by providing doubly linked lists for values
0071 /// that are inlined in the dense vector. SparseMultiSet is a good choice when
0072 /// one desires a growable number of entries per key, as it will retain the
0073 /// SparseSet algorithmic properties despite being growable. Thus, it is often a
0074 /// better choice than a SparseSet of growable containers or a vector of
0075 /// vectors. SparseMultiSet also keeps iterators valid after erasure (provided
0076 /// the iterators don't point to the element erased), allowing for more
0077 /// intuitive and fast removal.
0078 ///
0079 /// @tparam ValueT      The type of objects in the set.
0080 /// @tparam KeyFunctorT A functor that computes an unsigned index from KeyT.
0081 /// @tparam SparseT     An unsigned integer type. See above.
0082 ///
0083 template<typename ValueT,
0084          typename KeyFunctorT = identity<unsigned>,
0085          typename SparseT = uint8_t>
0086 class SparseMultiSet {
0087   static_assert(std::is_unsigned_v<SparseT>,
0088                 "SparseT must be an unsigned integer type");
0089 
0090   /// The actual data that's stored, as a doubly-linked list implemented via
0091   /// indices into the DenseVector.  The doubly linked list is implemented
0092   /// circular in Prev indices, and INVALID-terminated in Next indices. This
0093   /// provides efficient access to list tails. These nodes can also be
0094   /// tombstones, in which case they are actually nodes in a single-linked
0095   /// freelist of recyclable slots.
0096   struct SMSNode {
0097     static constexpr unsigned INVALID = ~0U;
0098 
0099     ValueT Data;
0100     unsigned Prev;
0101     unsigned Next;
0102 
0103     SMSNode(ValueT D, unsigned P, unsigned N) : Data(D), Prev(P), Next(N) {}
0104 
0105     /// List tails have invalid Nexts.
0106     bool isTail() const {
0107       return Next == INVALID;
0108     }
0109 
0110     /// Whether this node is a tombstone node, and thus is in our freelist.
0111     bool isTombstone() const {
0112       return Prev == INVALID;
0113     }
0114 
0115     /// Since the list is circular in Prev, all non-tombstone nodes have a valid
0116     /// Prev.
0117     bool isValid() const { return Prev != INVALID; }
0118   };
0119 
0120   using KeyT = typename KeyFunctorT::argument_type;
0121   using DenseT = SmallVector<SMSNode, 8>;
0122   DenseT Dense;
0123   SparseT *Sparse = nullptr;
0124   unsigned Universe = 0;
0125   KeyFunctorT KeyIndexOf;
0126   SparseSetValFunctor<KeyT, ValueT, KeyFunctorT> ValIndexOf;
0127 
0128   /// We have a built-in recycler for reusing tombstone slots. This recycler
0129   /// puts a singly-linked free list into tombstone slots, allowing us quick
0130   /// erasure, iterator preservation, and dense size.
0131   unsigned FreelistIdx = SMSNode::INVALID;
0132   unsigned NumFree = 0;
0133 
0134   unsigned sparseIndex(const ValueT &Val) const {
0135     assert(ValIndexOf(Val) < Universe &&
0136            "Invalid key in set. Did object mutate?");
0137     return ValIndexOf(Val);
0138   }
0139   unsigned sparseIndex(const SMSNode &N) const { return sparseIndex(N.Data); }
0140 
0141   /// Whether the given entry is the head of the list. List heads's previous
0142   /// pointers are to the tail of the list, allowing for efficient access to the
0143   /// list tail. D must be a valid entry node.
0144   bool isHead(const SMSNode &D) const {
0145     assert(D.isValid() && "Invalid node for head");
0146     return Dense[D.Prev].isTail();
0147   }
0148 
0149   /// Whether the given entry is a singleton entry, i.e. the only entry with
0150   /// that key.
0151   bool isSingleton(const SMSNode &N) const {
0152     assert(N.isValid() && "Invalid node for singleton");
0153     // Is N its own predecessor?
0154     return &Dense[N.Prev] == &N;
0155   }
0156 
0157   /// Add in the given SMSNode. Uses a free entry in our freelist if
0158   /// available. Returns the index of the added node.
0159   unsigned addValue(const ValueT& V, unsigned Prev, unsigned Next) {
0160     if (NumFree == 0) {
0161       Dense.push_back(SMSNode(V, Prev, Next));
0162       return Dense.size() - 1;
0163     }
0164 
0165     // Peel off a free slot
0166     unsigned Idx = FreelistIdx;
0167     unsigned NextFree = Dense[Idx].Next;
0168     assert(Dense[Idx].isTombstone() && "Non-tombstone free?");
0169 
0170     Dense[Idx] = SMSNode(V, Prev, Next);
0171     FreelistIdx = NextFree;
0172     --NumFree;
0173     return Idx;
0174   }
0175 
0176   /// Make the current index a new tombstone. Pushes it onto the freelist.
0177   void makeTombstone(unsigned Idx) {
0178     Dense[Idx].Prev = SMSNode::INVALID;
0179     Dense[Idx].Next = FreelistIdx;
0180     FreelistIdx = Idx;
0181     ++NumFree;
0182   }
0183 
0184 public:
0185   using value_type = ValueT;
0186   using reference = ValueT &;
0187   using const_reference = const ValueT &;
0188   using pointer = ValueT *;
0189   using const_pointer = const ValueT *;
0190   using size_type = unsigned;
0191 
0192   SparseMultiSet() = default;
0193   SparseMultiSet(const SparseMultiSet &) = delete;
0194   SparseMultiSet &operator=(const SparseMultiSet &) = delete;
0195   ~SparseMultiSet() { free(Sparse); }
0196 
0197   /// Set the universe size which determines the largest key the set can hold.
0198   /// The universe must be sized before any elements can be added.
0199   ///
0200   /// @param U Universe size. All object keys must be less than U.
0201   ///
0202   void setUniverse(unsigned U) {
0203     // It's not hard to resize the universe on a non-empty set, but it doesn't
0204     // seem like a likely use case, so we can add that code when we need it.
0205     assert(empty() && "Can only resize universe on an empty map");
0206     // Hysteresis prevents needless reallocations.
0207     if (U >= Universe/4 && U <= Universe)
0208       return;
0209     free(Sparse);
0210     // The Sparse array doesn't actually need to be initialized, so malloc
0211     // would be enough here, but that will cause tools like valgrind to
0212     // complain about branching on uninitialized data.
0213     Sparse = static_cast<SparseT*>(safe_calloc(U, sizeof(SparseT)));
0214     Universe = U;
0215   }
0216 
0217   /// Our iterators are iterators over the collection of objects that share a
0218   /// key.
0219   template <typename SMSPtrTy> class iterator_base {
0220     friend class SparseMultiSet;
0221 
0222   public:
0223     using iterator_category = std::bidirectional_iterator_tag;
0224     using value_type = ValueT;
0225     using difference_type = std::ptrdiff_t;
0226     using pointer = value_type *;
0227     using reference = value_type &;
0228 
0229   private:
0230     SMSPtrTy SMS;
0231     unsigned Idx;
0232     unsigned SparseIdx;
0233 
0234     iterator_base(SMSPtrTy P, unsigned I, unsigned SI)
0235       : SMS(P), Idx(I), SparseIdx(SI) {}
0236 
0237     /// Whether our iterator has fallen outside our dense vector.
0238     bool isEnd() const {
0239       if (Idx == SMSNode::INVALID)
0240         return true;
0241 
0242       assert(Idx < SMS->Dense.size() && "Out of range, non-INVALID Idx?");
0243       return false;
0244     }
0245 
0246     /// Whether our iterator is properly keyed, i.e. the SparseIdx is valid
0247     bool isKeyed() const { return SparseIdx < SMS->Universe; }
0248 
0249     unsigned Prev() const { return SMS->Dense[Idx].Prev; }
0250     unsigned Next() const { return SMS->Dense[Idx].Next; }
0251 
0252     void setPrev(unsigned P) { SMS->Dense[Idx].Prev = P; }
0253     void setNext(unsigned N) { SMS->Dense[Idx].Next = N; }
0254 
0255   public:
0256     reference operator*() const {
0257       assert(isKeyed() && SMS->sparseIndex(SMS->Dense[Idx].Data) == SparseIdx &&
0258              "Dereferencing iterator of invalid key or index");
0259 
0260       return SMS->Dense[Idx].Data;
0261     }
0262     pointer operator->() const { return &operator*(); }
0263 
0264     /// Comparison operators
0265     bool operator==(const iterator_base &RHS) const {
0266       // end compares equal
0267       if (SMS == RHS.SMS && Idx == RHS.Idx) {
0268         assert((isEnd() || SparseIdx == RHS.SparseIdx) &&
0269                "Same dense entry, but different keys?");
0270         return true;
0271       }
0272 
0273       return false;
0274     }
0275 
0276     bool operator!=(const iterator_base &RHS) const {
0277       return !operator==(RHS);
0278     }
0279 
0280     /// Increment and decrement operators
0281     iterator_base &operator--() { // predecrement - Back up
0282       assert(isKeyed() && "Decrementing an invalid iterator");
0283       assert((isEnd() || !SMS->isHead(SMS->Dense[Idx])) &&
0284              "Decrementing head of list");
0285 
0286       // If we're at the end, then issue a new find()
0287       if (isEnd())
0288         Idx = SMS->findIndex(SparseIdx).Prev();
0289       else
0290         Idx = Prev();
0291 
0292       return *this;
0293     }
0294     iterator_base &operator++() { // preincrement - Advance
0295       assert(!isEnd() && isKeyed() && "Incrementing an invalid/end iterator");
0296       Idx = Next();
0297       return *this;
0298     }
0299     iterator_base operator--(int) { // postdecrement
0300       iterator_base I(*this);
0301       --*this;
0302       return I;
0303     }
0304     iterator_base operator++(int) { // postincrement
0305       iterator_base I(*this);
0306       ++*this;
0307       return I;
0308     }
0309   };
0310 
0311   using iterator = iterator_base<SparseMultiSet *>;
0312   using const_iterator = iterator_base<const SparseMultiSet *>;
0313 
0314   // Convenience types
0315   using RangePair = std::pair<iterator, iterator>;
0316 
0317   /// Returns an iterator past this container. Note that such an iterator cannot
0318   /// be decremented, but will compare equal to other end iterators.
0319   iterator end() { return iterator(this, SMSNode::INVALID, SMSNode::INVALID); }
0320   const_iterator end() const {
0321     return const_iterator(this, SMSNode::INVALID, SMSNode::INVALID);
0322   }
0323 
0324   /// Returns true if the set is empty.
0325   ///
0326   /// This is not the same as BitVector::empty().
0327   ///
0328   bool empty() const { return size() == 0; }
0329 
0330   /// Returns the number of elements in the set.
0331   ///
0332   /// This is not the same as BitVector::size() which returns the size of the
0333   /// universe.
0334   ///
0335   size_type size() const {
0336     assert(NumFree <= Dense.size() && "Out-of-bounds free entries");
0337     return Dense.size() - NumFree;
0338   }
0339 
0340   /// Clears the set.  This is a very fast constant time operation.
0341   ///
0342   void clear() {
0343     // Sparse does not need to be cleared, see find().
0344     Dense.clear();
0345     NumFree = 0;
0346     FreelistIdx = SMSNode::INVALID;
0347   }
0348 
0349   /// Find an element by its index.
0350   ///
0351   /// @param   Idx A valid index to find.
0352   /// @returns An iterator to the element identified by key, or end().
0353   ///
0354   iterator findIndex(unsigned Idx) {
0355     assert(Idx < Universe && "Key out of range");
0356     const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
0357     for (unsigned i = Sparse[Idx], e = Dense.size(); i < e; i += Stride) {
0358       const unsigned FoundIdx = sparseIndex(Dense[i]);
0359       // Check that we're pointing at the correct entry and that it is the head
0360       // of a valid list.
0361       if (Idx == FoundIdx && Dense[i].isValid() && isHead(Dense[i]))
0362         return iterator(this, i, Idx);
0363       // Stride is 0 when SparseT >= unsigned.  We don't need to loop.
0364       if (!Stride)
0365         break;
0366     }
0367     return end();
0368   }
0369 
0370   /// Find an element by its key.
0371   ///
0372   /// @param   Key A valid key to find.
0373   /// @returns An iterator to the element identified by key, or end().
0374   ///
0375   iterator find(const KeyT &Key) {
0376     return findIndex(KeyIndexOf(Key));
0377   }
0378 
0379   const_iterator find(const KeyT &Key) const {
0380     iterator I = const_cast<SparseMultiSet*>(this)->findIndex(KeyIndexOf(Key));
0381     return const_iterator(I.SMS, I.Idx, KeyIndexOf(Key));
0382   }
0383 
0384   /// Returns the number of elements identified by Key. This will be linear in
0385   /// the number of elements of that key.
0386   size_type count(const KeyT &Key) const {
0387     unsigned Ret = 0;
0388     for (const_iterator It = find(Key); It != end(); ++It)
0389       ++Ret;
0390 
0391     return Ret;
0392   }
0393 
0394   /// Returns true if this set contains an element identified by Key.
0395   bool contains(const KeyT &Key) const {
0396     return find(Key) != end();
0397   }
0398 
0399   /// Return the head and tail of the subset's list, otherwise returns end().
0400   iterator getHead(const KeyT &Key) { return find(Key); }
0401   iterator getTail(const KeyT &Key) {
0402     iterator I = find(Key);
0403     if (I != end())
0404       I = iterator(this, I.Prev(), KeyIndexOf(Key));
0405     return I;
0406   }
0407 
0408   /// The bounds of the range of items sharing Key K. First member is the head
0409   /// of the list, and the second member is a decrementable end iterator for
0410   /// that key.
0411   RangePair equal_range(const KeyT &K) {
0412     iterator B = find(K);
0413     iterator E = iterator(this, SMSNode::INVALID, B.SparseIdx);
0414     return std::make_pair(B, E);
0415   }
0416 
0417   /// Insert a new element at the tail of the subset list. Returns an iterator
0418   /// to the newly added entry.
0419   iterator insert(const ValueT &Val) {
0420     unsigned Idx = sparseIndex(Val);
0421     iterator I = findIndex(Idx);
0422 
0423     unsigned NodeIdx = addValue(Val, SMSNode::INVALID, SMSNode::INVALID);
0424 
0425     if (I == end()) {
0426       // Make a singleton list
0427       Sparse[Idx] = NodeIdx;
0428       Dense[NodeIdx].Prev = NodeIdx;
0429       return iterator(this, NodeIdx, Idx);
0430     }
0431 
0432     // Stick it at the end.
0433     unsigned HeadIdx = I.Idx;
0434     unsigned TailIdx = I.Prev();
0435     Dense[TailIdx].Next = NodeIdx;
0436     Dense[HeadIdx].Prev = NodeIdx;
0437     Dense[NodeIdx].Prev = TailIdx;
0438 
0439     return iterator(this, NodeIdx, Idx);
0440   }
0441 
0442   /// Erases an existing element identified by a valid iterator.
0443   ///
0444   /// This invalidates iterators pointing at the same entry, but erase() returns
0445   /// an iterator pointing to the next element in the subset's list. This makes
0446   /// it possible to erase selected elements while iterating over the subset:
0447   ///
0448   ///   tie(I, E) = Set.equal_range(Key);
0449   ///   while (I != E)
0450   ///     if (test(*I))
0451   ///       I = Set.erase(I);
0452   ///     else
0453   ///       ++I;
0454   ///
0455   /// Note that if the last element in the subset list is erased, this will
0456   /// return an end iterator which can be decremented to get the new tail (if it
0457   /// exists):
0458   ///
0459   ///  tie(B, I) = Set.equal_range(Key);
0460   ///  for (bool isBegin = B == I; !isBegin; /* empty */) {
0461   ///    isBegin = (--I) == B;
0462   ///    if (test(I))
0463   ///      break;
0464   ///    I = erase(I);
0465   ///  }
0466   iterator erase(iterator I) {
0467     assert(I.isKeyed() && !I.isEnd() && !Dense[I.Idx].isTombstone() &&
0468            "erasing invalid/end/tombstone iterator");
0469 
0470     // First, unlink the node from its list. Then swap the node out with the
0471     // dense vector's last entry
0472     iterator NextI = unlink(Dense[I.Idx]);
0473 
0474     // Put in a tombstone.
0475     makeTombstone(I.Idx);
0476 
0477     return NextI;
0478   }
0479 
0480   /// Erase all elements with the given key. This invalidates all
0481   /// iterators of that key.
0482   void eraseAll(const KeyT &K) {
0483     for (iterator I = find(K); I != end(); /* empty */)
0484       I = erase(I);
0485   }
0486 
0487 private:
0488   /// Unlink the node from its list. Returns the next node in the list.
0489   iterator unlink(const SMSNode &N) {
0490     if (isSingleton(N)) {
0491       // Singleton is already unlinked
0492       assert(N.Next == SMSNode::INVALID && "Singleton has next?");
0493       return iterator(this, SMSNode::INVALID, ValIndexOf(N.Data));
0494     }
0495 
0496     if (isHead(N)) {
0497       // If we're the head, then update the sparse array and our next.
0498       Sparse[sparseIndex(N)] = N.Next;
0499       Dense[N.Next].Prev = N.Prev;
0500       return iterator(this, N.Next, ValIndexOf(N.Data));
0501     }
0502 
0503     if (N.isTail()) {
0504       // If we're the tail, then update our head and our previous.
0505       findIndex(sparseIndex(N)).setPrev(N.Prev);
0506       Dense[N.Prev].Next = N.Next;
0507 
0508       // Give back an end iterator that can be decremented
0509       iterator I(this, N.Prev, ValIndexOf(N.Data));
0510       return ++I;
0511     }
0512 
0513     // Otherwise, just drop us
0514     Dense[N.Next].Prev = N.Prev;
0515     Dense[N.Prev].Next = N.Next;
0516     return iterator(this, N.Next, ValIndexOf(N.Data));
0517   }
0518 };
0519 
0520 } // end namespace llvm
0521 
0522 #endif // LLVM_ADT_SPARSEMULTISET_H