1 //===--- llvm/ADT/SparseSet.h - Sparse set ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the SparseSet class derived from the version described in
11 // Briggs, Torczon, "An efficient representation for sparse sets", ACM Letters
12 // on Programming Languages and Systems, Volume 2 Issue 1-4, March-Dec. 1993.
14 // A sparse set holds a small number of objects identified by integer keys from
15 // a moderately sized universe. The sparse set uses more memory than other
16 // containers in order to provide faster operations.
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_ADT_SPARSESET_H
21 #define LLVM_ADT_SPARSESET_H
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Support/DataTypes.h"
29 /// SparseSetFunctor - Objects in a SparseSet are identified by small integer
30 /// keys. A functor object is used to compute the key of an object. The
31 /// functor's operator() must return an unsigned smaller than the universe.
33 /// The default functor implementation forwards to a getSparseSetKey() method
34 /// on the object. It is intended for sparse sets holding ad-hoc structs.
36 template<typename ValueT>
37 struct SparseSetFunctor {
38 unsigned operator()(const ValueT &Val) {
39 return Val.getSparseSetKey();
43 /// SparseSetFunctor<unsigned> - Provide a trivial identity functor for
44 /// SparseSet<unsigned>.
46 template<> struct SparseSetFunctor<unsigned> {
47 unsigned operator()(unsigned Val) { return Val; }
50 /// SparseSet - Fast set implementation for objects that can be identified by
51 /// small unsigned keys.
53 /// SparseSet allocates memory proportional to the size of the key universe, so
54 /// it is not recommended for building composite data structures. It is useful
55 /// for algorithms that require a single set with fast operations.
57 /// Compared to DenseSet and DenseMap, SparseSet provides constant-time fast
58 /// clear() and iteration as fast as a vector. The find(), insert(), and
59 /// erase() operations are all constant time, and typically faster than a hash
60 /// table. The iteration order doesn't depend on numerical key values, it only
61 /// depends on the order of insert() and erase() operations. When no elements
62 /// have been erased, the iteration order is the insertion order.
64 /// Compared to BitVector, SparseSet<unsigned> uses 8x-40x more memory, but
65 /// offers constant-time clear() and size() operations as well as fast
66 /// iteration independent on the size of the universe.
68 /// SparseSet contains a dense vector holding all the objects and a sparse
69 /// array holding indexes into the dense vector. Most of the memory is used by
70 /// the sparse array which is the size of the key universe. The SparseT
71 /// template parameter provides a space/speed tradeoff for sets holding many
74 /// When SparseT is uint32_t, find() only touches 2 cache lines, but the sparse
75 /// array uses 4 x Universe bytes.
77 /// When SparseT is uint8_t (the default), find() touches up to 2+[N/256] cache
78 /// lines, but the sparse array is 4x smaller. N is the number of elements in
81 /// For sets that may grow to thousands of elements, SparseT should be set to
82 /// uint16_t or uint32_t.
84 /// @param ValueT The type of objects in the set.
85 /// @param SparseT An unsigned integer type. See above.
86 /// @param KeyFunctorT A functor that computes the unsigned key of a ValueT.
88 template<typename ValueT,
89 typename SparseT = uint8_t,
90 typename KeyFunctorT = SparseSetFunctor<ValueT> >
92 typedef SmallVector<ValueT, 8> DenseT;
98 // Disable copy construction and assignment.
99 // This data structure is not meant to be used that way.
100 SparseSet(const SparseSet&); // DO NOT IMPLEMENT.
101 SparseSet &operator=(const SparseSet&); // DO NOT IMPLEMENT.
104 typedef ValueT value_type;
105 typedef ValueT &reference;
106 typedef const ValueT &const_reference;
107 typedef ValueT *pointer;
108 typedef const ValueT *const_pointer;
110 SparseSet() : Sparse(0), Universe(0) {}
111 ~SparseSet() { free(Sparse); }
113 /// setUniverse - Set the universe size which determines the largest key the
114 /// set can hold. The universe must be sized before any elements can be
117 /// @param U Universe size. All object keys must be less than U.
119 void setUniverse(unsigned U) {
120 // It's not hard to resize the universe on a non-empty set, but it doesn't
121 // seem like a likely use case, so we can add that code when we need it.
122 assert(empty() && "Can only resize universe on an empty map");
123 // Hysteresis prevents needless reallocations.
124 if (U >= Universe/4 && U <= Universe)
127 // The Sparse array doesn't actually need to be initialized, so malloc
128 // would be enough here, but that will cause tools like valgrind to
129 // complain about branching on uninitialized data.
130 Sparse = reinterpret_cast<SparseT*>(calloc(U, sizeof(SparseT)));
134 // Import trivial vector stuff from DenseT.
135 typedef typename DenseT::iterator iterator;
136 typedef typename DenseT::const_iterator const_iterator;
138 const_iterator begin() const { return Dense.begin(); }
139 const_iterator end() const { return Dense.end(); }
140 iterator begin() { return Dense.begin(); }
141 iterator end() { return Dense.end(); }
143 /// empty - Returns true if the set is empty.
145 /// This is not the same as BitVector::empty().
147 bool empty() const { return Dense.empty(); }
149 /// size - Returns the number of elements in the set.
151 /// This is not the same as BitVector::size() which returns the size of the
154 unsigned size() const { return Dense.size(); }
156 /// clear - Clears the set. This is a very fast constant time operation.
159 // Sparse does not need to be cleared, see find().
163 /// find - Find an element by its key.
165 /// @param Key A valid key to find.
166 /// @returns An iterator to the element identified by key, or end().
168 iterator find(unsigned Key) {
169 assert(Key < Universe && "Key out of range");
170 assert(std::numeric_limits<SparseT>::is_integer &&
171 !std::numeric_limits<SparseT>::is_signed &&
172 "SparseT must be an unsigned integer type");
173 const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
174 for (unsigned i = Sparse[Key], e = size(); i < e; i += Stride) {
175 const unsigned FoundKey = KeyOf(Dense[i]);
176 assert(FoundKey < Universe && "Invalid key in set. Did object mutate?");
179 // Stride is 0 when SparseT >= unsigned. We don't need to loop.
186 const_iterator find(unsigned Key) const {
187 return const_cast<SparseSet*>(this)->find(Key);
190 /// count - Returns true if this set contains an element identified by Key.
192 bool count(unsigned Key) const {
193 return find(Key) != end();
196 /// insert - Attempts to insert a new element.
198 /// If Val is successfully inserted, return (I, true), where I is an iterator
199 /// pointing to the newly inserted element.
201 /// If the set already contains an element with the same key as Val, return
202 /// (I, false), where I is an iterator pointing to the existing element.
204 /// Insertion invalidates all iterators.
206 std::pair<iterator, bool> insert(const ValueT &Val) {
207 unsigned Key = KeyOf(Val);
208 iterator I = find(Key);
210 return std::make_pair(I, false);
211 Sparse[Key] = size();
212 Dense.push_back(Val);
213 return std::make_pair(end() - 1, true);
216 /// array subscript - If an element already exists with this key, return it.
217 /// Otherwise, automatically construct a new value from Key, insert it,
218 /// and return the newly inserted element.
219 ValueT &operator[](unsigned Key) {
220 return *insert(ValueT(Key)).first;
223 /// erase - Erases an existing element identified by a valid iterator.
225 /// This invalidates all iterators, but erase() returns an iterator pointing
226 /// to the next element. This makes it possible to erase selected elements
227 /// while iterating over the set:
229 /// for (SparseSet::iterator I = Set.begin(); I != Set.end();)
231 /// I = Set.erase(I);
235 /// Note that end() changes when elements are erased, unlike std::list.
237 iterator erase(iterator I) {
238 assert(unsigned(I - begin()) < size() && "Invalid iterator");
239 if (I != end() - 1) {
241 unsigned BackKey = KeyOf(Dense.back());
242 assert(BackKey < Universe && "Invalid key in set. Did object mutate?");
243 Sparse[BackKey] = I - begin();
245 // This depends on SmallVector::pop_back() not invalidating iterators.
246 // std::vector::pop_back() doesn't give that guarantee.
251 /// erase - Erases an element identified by Key, if it exists.
253 /// @param Key The key identifying the element to erase.
254 /// @returns True when an element was erased, false if no element was found.
256 bool erase(unsigned Key) {
257 iterator I = find(Key);
266 } // end namespace llvm