Line data Source code
1 : //===- llvm/ADT/SparseSet.h - Sparse set ------------------------*- 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 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.
13 : //
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.
17 : //
18 : //===----------------------------------------------------------------------===//
19 :
20 : #ifndef LLVM_ADT_SPARSESET_H
21 : #define LLVM_ADT_SPARSESET_H
22 :
23 : #include "llvm/ADT/STLExtras.h"
24 : #include "llvm/ADT/SmallVector.h"
25 : #include "llvm/Support/Allocator.h"
26 : #include <cassert>
27 : #include <cstdint>
28 : #include <cstdlib>
29 : #include <limits>
30 : #include <utility>
31 :
32 : namespace llvm {
33 :
34 : /// SparseSetValTraits - Objects in a SparseSet are identified by keys that can
35 : /// be uniquely converted to a small integer less than the set's universe. This
36 : /// class allows the set to hold values that differ from the set's key type as
37 : /// long as an index can still be derived from the value. SparseSet never
38 : /// directly compares ValueT, only their indices, so it can map keys to
39 : /// arbitrary values. SparseSetValTraits computes the index from the value
40 : /// object. To compute the index from a key, SparseSet uses a separate
41 : /// KeyFunctorT template argument.
42 : ///
43 : /// A simple type declaration, SparseSet<Type>, handles these cases:
44 : /// - unsigned key, identity index, identity value
45 : /// - unsigned key, identity index, fat value providing getSparseSetIndex()
46 : ///
47 : /// The type declaration SparseSet<Type, UnaryFunction> handles:
48 : /// - unsigned key, remapped index, identity value (virtual registers)
49 : /// - pointer key, pointer-derived index, identity value (node+ID)
50 : /// - pointer key, pointer-derived index, fat value with getSparseSetIndex()
51 : ///
52 : /// Only other, unexpected cases require specializing SparseSetValTraits.
53 : ///
54 : /// For best results, ValueT should not require a destructor.
55 : ///
56 : template<typename ValueT>
57 : struct SparseSetValTraits {
58 : static unsigned getValIndex(const ValueT &Val) {
59 136296054 : return Val.getSparseSetIndex();
60 : }
61 : };
62 :
63 : /// SparseSetValFunctor - Helper class for selecting SparseSetValTraits. The
64 : /// generic implementation handles ValueT classes which either provide
65 : /// getSparseSetIndex() or specialize SparseSetValTraits<>.
66 : ///
67 : template<typename KeyT, typename ValueT, typename KeyFunctorT>
68 : struct SparseSetValFunctor {
69 0 : unsigned operator()(const ValueT &Val) const {
70 0 : return SparseSetValTraits<ValueT>::getValIndex(Val);
71 : }
72 0 : };
73 0 :
74 : /// SparseSetValFunctor<KeyT, KeyT> - Helper class for the common case of
75 0 : /// identity key/value sets.
76 0 : template<typename KeyT, typename KeyFunctorT>
77 : struct SparseSetValFunctor<KeyT, KeyT, KeyFunctorT> {
78 0 : unsigned operator()(const KeyT &Key) const {
79 0 : return KeyFunctorT()(Key);
80 : }
81 0 : };
82 0 :
83 : /// SparseSet - Fast set implmentation for objects that can be identified by
84 : /// small unsigned keys.
85 : ///
86 : /// SparseSet allocates memory proportional to the size of the key universe, so
87 : /// it is not recommended for building composite data structures. It is useful
88 : /// for algorithms that require a single set with fast operations.
89 : ///
90 0 : /// Compared to DenseSet and DenseMap, SparseSet provides constant-time fast
91 0 : /// clear() and iteration as fast as a vector. The find(), insert(), and
92 : /// erase() operations are all constant time, and typically faster than a hash
93 : /// table. The iteration order doesn't depend on numerical key values, it only
94 : /// depends on the order of insert() and erase() operations. When no elements
95 : /// have been erased, the iteration order is the insertion order.
96 : ///
97 : /// Compared to BitVector, SparseSet<unsigned> uses 8x-40x more memory, but
98 : /// offers constant-time clear() and size() operations as well as fast
99 : /// iteration independent on the size of the universe.
100 : ///
101 : /// SparseSet contains a dense vector holding all the objects and a sparse
102 : /// array holding indexes into the dense vector. Most of the memory is used by
103 : /// the sparse array which is the size of the key universe. The SparseT
104 : /// template parameter provides a space/speed tradeoff for sets holding many
105 : /// elements.
106 : ///
107 : /// When SparseT is uint32_t, find() only touches 2 cache lines, but the sparse
108 : /// array uses 4 x Universe bytes.
109 : ///
110 : /// When SparseT is uint8_t (the default), find() touches up to 2+[N/256] cache
111 : /// lines, but the sparse array is 4x smaller. N is the number of elements in
112 : /// the set.
113 : ///
114 : /// For sets that may grow to thousands of elements, SparseT should be set to
115 : /// uint16_t or uint32_t.
116 : ///
117 : /// @tparam ValueT The type of objects in the set.
118 : /// @tparam KeyFunctorT A functor that computes an unsigned index from KeyT.
119 : /// @tparam SparseT An unsigned integer type. See above.
120 : ///
121 : template<typename ValueT,
122 : typename KeyFunctorT = identity<unsigned>,
123 : typename SparseT = uint8_t>
124 : class SparseSet {
125 : static_assert(std::numeric_limits<SparseT>::is_integer &&
126 : !std::numeric_limits<SparseT>::is_signed,
127 : "SparseT must be an unsigned integer type");
128 :
129 : using KeyT = typename KeyFunctorT::argument_type;
130 : using DenseT = SmallVector<ValueT, 8>;
131 : using size_type = unsigned;
132 : DenseT Dense;
133 : SparseT *Sparse = nullptr;
134 : unsigned Universe = 0;
135 : KeyFunctorT KeyIndexOf;
136 : SparseSetValFunctor<KeyT, ValueT, KeyFunctorT> ValIndexOf;
137 :
138 : public:
139 : using value_type = ValueT;
140 : using reference = ValueT &;
141 : using const_reference = const ValueT &;
142 : using pointer = ValueT *;
143 : using const_pointer = const ValueT *;
144 :
145 1709956 : SparseSet() = default;
146 : SparseSet(const SparseSet &) = delete;
147 : SparseSet &operator=(const SparseSet &) = delete;
148 2024066 : ~SparseSet() { free(Sparse); }
149 :
150 : /// setUniverse - Set the universe size which determines the largest key the
151 : /// set can hold. The universe must be sized before any elements can be
152 : /// added.
153 : ///
154 : /// @param U Universe size. All object keys must be less than U.
155 : ///
156 0 : void setUniverse(unsigned U) {
157 234344 : // It's not hard to resize the universe on a non-empty set, but it doesn't
158 : // seem like a likely use case, so we can add that code when we need it.
159 : assert(empty() && "Can only resize universe on an empty map");
160 10 : // Hysteresis prevents needless reallocations.
161 0 : if (U >= Universe/4 && U <= Universe)
162 0 : return;
163 0 : free(Sparse);
164 : // The Sparse array doesn't actually need to be initialized, so malloc
165 : // would be enough here, but that will cause tools like valgrind to
166 : // complain about branching on uninitialized data.
167 0 : Sparse = static_cast<SparseT*>(safe_calloc(U, sizeof(SparseT)));
168 0 : Universe = U;
169 : }
170 0 :
171 : // Import trivial vector stuff from DenseT.
172 : using iterator = typename DenseT::iterator;
173 0 : using const_iterator = typename DenseT::const_iterator;
174 0 :
175 0 : const_iterator begin() const { return Dense.begin(); }
176 0 : const_iterator end() const { return Dense.end(); }
177 0 : iterator begin() { return Dense.begin(); }
178 : iterator end() { return Dense.end(); }
179 0 :
180 0 : /// empty - Returns true if the set is empty.
181 0 : ///
182 0 : /// This is not the same as BitVector::empty().
183 : ///
184 4330168 : bool empty() const { return Dense.empty(); }
185 :
186 : /// size - Returns the number of elements in the set.
187 0 : ///
188 0 : /// This is not the same as BitVector::size() which returns the size of the
189 0 : /// universe.
190 0 : ///
191 55995456 : size_type size() const { return Dense.size(); }
192 :
193 0 : /// clear - Clears the set. This is a very fast constant time operation.
194 0 : ///
195 0 : void clear() {
196 0 : // Sparse does not need to be cleared, see find().
197 : Dense.clear();
198 : }
199 :
200 : /// findIndex - Find an element by its index.
201 0 : ///
202 0 : /// @param Idx A valid index to find.
203 0 : /// @returns An iterator to the element identified by key, or end().
204 : ///
205 : iterator findIndex(unsigned Idx) {
206 : assert(Idx < Universe && "Key out of range");
207 0 : const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
208 81635806 : for (unsigned i = Sparse[Idx], e = size(); i < e; i += Stride) {
209 36622846 : const unsigned FoundIdx = ValIndexOf(Dense[i]);
210 : assert(FoundIdx < Universe && "Invalid key in set. Did object mutate?");
211 36622846 : if (Idx == FoundIdx)
212 4857920 : return begin() + i;
213 : // Stride is 0 when SparseT >= unsigned. We don't need to loop.
214 : if (!Stride)
215 : break;
216 : }
217 : return end();
218 : }
219 262759622 :
220 : /// find - Find an element by its key.
221 : ///
222 : /// @param Key A valid key to find.
223 : /// @returns An iterator to the element identified by key, or end().
224 : ///
225 0 : iterator find(const KeyT &Key) {
226 0 : return findIndex(KeyIndexOf(Key));
227 : }
228 :
229 0 : const_iterator find(const KeyT &Key) const {
230 0 : return const_cast<SparseSet*>(this)->findIndex(KeyIndexOf(Key));
231 5852257 : }
232 :
233 48834967 : /// count - Returns 1 if this set contains an element identified by Key,
234 : /// 0 otherwise.
235 : ///
236 284318048 : size_type count(const KeyT &Key) const {
237 67242673 : return find(Key) == end() ? 0 : 1;
238 : }
239 66510671 :
240 : /// insert - Attempts to insert a new element.
241 : ///
242 : /// If Val is successfully inserted, return (I, true), where I is an iterator
243 : /// pointing to the newly inserted element.
244 : ///
245 16971185 : /// If the set already contains an element with the same key as Val, return
246 : /// (I, false), where I is an iterator pointing to the existing element.
247 : ///
248 7821732 : /// Insertion invalidates all iterators.
249 5420837 : ///
250 47531672 : std::pair<iterator, bool> insert(const ValueT &Val) {
251 52945907 : unsigned Idx = ValIndexOf(Val);
252 : iterator I = findIndex(Idx);
253 47531672 : if (I != end())
254 8847649 : return std::make_pair(I, false);
255 37846818 : Sparse[Idx] = size();
256 37846818 : Dense.push_back(Val);
257 37846818 : return std::make_pair(end() - 1, true);
258 5404531 : }
259 0 :
260 0 : /// array subscript - If an element already exists with this key, return it.
261 0 : /// Otherwise, automatically construct a new value from Key, insert it,
262 : /// and return the newly inserted element.
263 0 : ValueT &operator[](const KeyT &Key) {
264 2042 : return *insert(ValueT(Key)).first;
265 0 : }
266 0 :
267 : ValueT pop_back_val() {
268 0 : // Sparse does not need to be cleared, see find().
269 0 : return Dense.pop_back_val();
270 0 : }
271 702 :
272 0 : /// erase - Erases an existing element identified by a valid iterator.
273 : ///
274 : /// This invalidates all iterators, but erase() returns an iterator pointing
275 0 : /// to the next element. This makes it possible to erase selected elements
276 0 : /// while iterating over the set:
277 : ///
278 : /// for (SparseSet::iterator I = Set.begin(); I != Set.end();)
279 : /// if (test(*I))
280 : /// I = Set.erase(I);
281 : /// else
282 0 : /// ++I;
283 0 : ///
284 175176721 : /// Note that end() changes when elements are erased, unlike std::list.
285 136243310 : ///
286 51149816 : iterator erase(iterator I) {
287 175176721 : assert(unsigned(I - begin()) < size() && "Invalid iterator");
288 16567031 : if (I != end() - 1) {
289 167588767 : *I = Dense.back();
290 167587772 : unsigned BackIdx = ValIndexOf(Dense.back());
291 154270956 : assert(BackIdx < Universe && "Invalid key in set. Did object mutate?");
292 13317811 : Sparse[BackIdx] = I - begin();
293 34582785 : }
294 : // This depends on SmallVector::pop_back() not invalidating iterators.
295 34582785 : // std::vector::pop_back() doesn't give that guarantee.
296 40434896 : Dense.pop_back();
297 22418788 : return I;
298 16971182 : }
299 22823293 :
300 16971182 : /// erase - Erases an element identified by Key, if it exists.
301 2400887 : ///
302 137812882 : /// @param Key The key identifying the element to erase.
303 137812882 : /// @returns True when an element was erased, false if no element was found.
304 : ///
305 135412349 : bool erase(const KeyT &Key) {
306 0 : iterator I = find(Key);
307 133958841 : if (I == end())
308 133959195 : return false;
309 133958841 : erase(I);
310 176 : return true;
311 176 : }
312 176 : };
313 :
314 5851757 : } // end namespace llvm
315 5851757 :
316 : #endif // LLVM_ADT_SPARSESET_H
|