LLVM 24.0.0git
SparseSet.h
Go to the documentation of this file.
1//===- llvm/ADT/SparseSet.h - Sparse set ------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
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
27#include <cassert>
28#include <cstdint>
29#include <cstdlib>
30#include <limits>
31#include <utility>
32
33namespace llvm {
34
35/// SparseSetValTraits - Objects in a SparseSet are identified by keys that can
36/// be uniquely converted to a small integer less than the set's universe. This
37/// class allows the set to hold values that differ from the set's key type as
38/// long as an index can still be derived from the value. SparseSet never
39/// directly compares ValueT, only their indices, so it can map keys to
40/// arbitrary values. SparseSetValTraits computes the index from the value
41/// object. To compute the index from a key, SparseSet uses a separate
42/// KeyFunctorT template argument.
43///
44/// A simple type declaration, SparseSet<Type>, handles these cases:
45/// - unsigned key, identity index, identity value
46/// - unsigned key, identity index, fat value providing getSparseSetIndex()
47///
48/// The type declaration SparseSet<Type, UnaryFunction> handles:
49/// - unsigned key, remapped index, identity value (virtual registers)
50/// - pointer key, pointer-derived index, identity value (node+ID)
51/// - pointer key, pointer-derived index, fat value with getSparseSetIndex()
52///
53/// Only other, unexpected cases require specializing SparseSetValTraits.
54///
55/// For best results, ValueT should not require a destructor.
56///
57template <typename ValueT> struct SparseSetValTraits {
58 static unsigned getValIndex(const ValueT &Val) {
59 return Val.getSparseSetIndex();
60 }
61};
62
63/// SparseSetValFunctor - Helper class for getting a value's index.
64///
65/// In the generic case, this is done via SparseSetValTraits. When the value
66/// type is the same as the key type, the KeyFunctor is used directly.
67template <typename KeyT, typename ValueT, typename KeyFunctorT>
69 unsigned operator()(const ValueT &Val) const {
70 if constexpr (std::is_same_v<KeyT, ValueT>)
71 return KeyFunctorT()(Val);
72 else
74 }
75};
76
77/// SparseSet - Fast set implementation for objects that can be identified by
78/// small unsigned keys.
79///
80/// SparseSet allocates memory proportional to the size of the key universe, so
81/// it is not recommended for building composite data structures. It is useful
82/// for algorithms that require a single set with fast operations.
83///
84/// Compared to DenseSet and DenseMap, SparseSet provides constant-time fast
85/// clear() and iteration as fast as a vector. The find(), insert(), and
86/// erase() operations are all constant time, and typically faster than a hash
87/// table. The iteration order doesn't depend on numerical key values, it only
88/// depends on the order of insert() and erase() operations. When no elements
89/// have been erased, the iteration order is the insertion order.
90///
91/// Compared to BitVector, SparseSet<unsigned> uses 8x-40x more memory, but
92/// offers constant-time clear() and size() operations as well as fast
93/// iteration independent on the size of the universe.
94///
95/// SparseSet contains a dense vector holding all the objects and a sparse
96/// array holding indexes into the dense vector. Most of the memory is used by
97/// the sparse array which is the size of the key universe. The SparseT
98/// template parameter provides a space/speed tradeoff for sets holding many
99/// elements.
100///
101/// When SparseT is uint32_t, find() only touches 2 cache lines, but the sparse
102/// array uses 4 x Universe bytes.
103///
104/// When SparseT is uint8_t (the default), find() touches up to 2+[N/256] cache
105/// lines, but the sparse array is 4x smaller. N is the number of elements in
106/// the set.
107///
108/// For sets that may grow to thousands of elements, SparseT should be set to
109/// uint16_t or uint32_t.
110///
111/// @tparam ValueT The type of objects in the set.
112/// @tparam KeyT The type of the key, which is passed to the key functor.
113/// @tparam KeyFunctorT A functor that computes an unsigned index from KeyT.
114/// @tparam SparseT An unsigned integer type. See above.
115///
116template <typename ValueT, typename KeyT = unsigned,
117 typename KeyFunctorT = identity, typename SparseT = uint8_t>
119 static_assert(std::is_unsigned_v<SparseT>,
120 "SparseT must be an unsigned integer type");
121
122 using DenseT = SmallVector<ValueT, 8>;
123 using size_type = unsigned;
124 DenseT Dense;
125
126 struct Deleter {
127 void operator()(SparseT *S) { free(S); }
128 };
129 std::unique_ptr<SparseT[], Deleter> Sparse;
130
131 unsigned Universe = 0;
132 KeyFunctorT KeyIndexOf;
134
135public:
136 using value_type = ValueT;
137 using reference = ValueT &;
138 using const_reference = const ValueT &;
139 using pointer = ValueT *;
140 using const_pointer = const ValueT *;
141
142 SparseSet() = default;
143 SparseSet(const SparseSet &) = delete;
144 SparseSet &operator=(const SparseSet &) = delete;
145 SparseSet(SparseSet &&) = default;
146
147 /// setUniverse - Set the universe size which determines the largest key the
148 /// set can hold. The universe must be sized before any elements can be
149 /// added.
150 ///
151 /// @param U Universe size. All object keys must be less than U.
152 ///
153 void setUniverse(unsigned U) {
154 // It's not hard to resize the universe on a non-empty set, but it doesn't
155 // seem like a likely use case, so we can add that code when we need it.
156 assert(empty() && "Can only resize universe on an empty map");
157 // Hysteresis prevents needless reallocations.
158 if (U >= Universe / 4 && U <= Universe)
159 return;
160 // The Sparse array doesn't actually need to be initialized, so malloc
161 // would be enough here, but that will cause tools like valgrind to
162 // complain about branching on uninitialized data.
163 Sparse.reset(static_cast<SparseT *>(safe_calloc(U, sizeof(SparseT))));
164 Universe = U;
165 }
166
167 // Import trivial vector stuff from DenseT.
168 using iterator = typename DenseT::iterator;
170
171 [[nodiscard]] const_iterator begin() const { return Dense.begin(); }
172 [[nodiscard]] const_iterator end() const { return Dense.end(); }
173 [[nodiscard]] iterator begin() { return Dense.begin(); }
174 [[nodiscard]] iterator end() { return Dense.end(); }
175
176 /// empty - Returns true if the set is empty.
177 ///
178 /// This is not the same as BitVector::empty().
179 ///
180 [[nodiscard]] bool empty() const { return Dense.empty(); }
181
182 /// size - Returns the number of elements in the set.
183 ///
184 /// This is not the same as BitVector::size() which returns the size of the
185 /// universe.
186 ///
187 [[nodiscard]] size_type size() const { return Dense.size(); }
188
189 /// clear - Clears the set. This is a very fast constant time operation.
190 ///
191 void clear() {
192 // Sparse does not need to be cleared, see find().
193 Dense.clear();
194 }
195
196 /// findIndex - Find an element by its index.
197 ///
198 /// @param Idx A valid index to find.
199 /// @returns An iterator to the element identified by key, or end().
200 ///
201 iterator findIndex(unsigned Idx) {
202 assert(Idx < Universe && "Key out of range");
203 assert(Sparse != nullptr && "Invalid sparse type");
204 const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
205 for (unsigned i = Sparse[Idx], e = size(); i < e; i += Stride) {
206 const unsigned FoundIdx = ValIndexOf(Dense[i]);
207 assert(FoundIdx < Universe && "Invalid key in set. Did object mutate?");
208 if (Idx == FoundIdx)
209 return begin() + i;
210 // Stride is 0 when SparseT >= unsigned. We don't need to loop.
211 if (!Stride)
212 break;
213 }
214 return end();
215 }
216
217 /// find - Find an element by its key.
218 ///
219 /// @param Key A valid key to find.
220 /// @returns An iterator to the element identified by key, or end().
221 ///
222 [[nodiscard]] iterator find(const KeyT &Key) {
223 return findIndex(KeyIndexOf(Key));
224 }
225
226 [[nodiscard]] const_iterator find(const KeyT &Key) const {
227 return const_cast<SparseSet *>(this)->findIndex(KeyIndexOf(Key));
228 }
229
230 /// Check if the set contains the given \c Key.
231 ///
232 /// @param Key A valid key to find.
233 [[nodiscard]] bool contains(const KeyT &Key) const {
234 return find(Key) != end();
235 }
236
237 /// count - Returns 1 if this set contains an element identified by Key,
238 /// 0 otherwise.
239 ///
240 [[nodiscard]] size_type count(const KeyT &Key) const {
241 return contains(Key) ? 1 : 0;
242 }
243
244 /// insert - Attempts to insert a new element.
245 ///
246 /// If Val is successfully inserted, return (I, true), where I is an iterator
247 /// pointing to the newly inserted element.
248 ///
249 /// If the set already contains an element with the same key as Val, return
250 /// (I, false), where I is an iterator pointing to the existing element.
251 ///
252 /// Insertion invalidates all iterators.
253 ///
254 std::pair<iterator, bool> insert(const ValueT &Val) {
255 unsigned Idx = ValIndexOf(Val);
256 iterator I = findIndex(Idx);
257 if (I != end())
258 return {I, false};
259 Sparse[Idx] = size();
260 Dense.push_back(Val);
261 return {end() - 1, true};
262 }
263
264 /// array subscript - If an element already exists with this key, return it.
265 /// Otherwise, automatically construct a new value from Key, insert it,
266 /// and return the newly inserted element.
267 ValueT &operator[](const KeyT &Key) { return *insert(ValueT(Key)).first; }
268
269 ValueT pop_back_val() {
270 // Sparse does not need to be cleared, see find().
271 return Dense.pop_back_val();
272 }
273
274 /// erase - Erases an existing element identified by a valid iterator.
275 ///
276 /// This invalidates all iterators, but erase() returns an iterator pointing
277 /// to the next element. This makes it possible to erase selected elements
278 /// while iterating over the set:
279 ///
280 /// for (SparseSet::iterator I = Set.begin(); I != Set.end();)
281 /// if (test(*I))
282 /// I = Set.erase(I);
283 /// else
284 /// ++I;
285 ///
286 /// Note that end() changes when elements are erased, unlike std::list.
287 ///
289 assert(unsigned(I - begin()) < size() && "Invalid iterator");
290 if (I != end() - 1) {
291 *I = Dense.back();
292 unsigned BackIdx = ValIndexOf(Dense.back());
293 assert(BackIdx < Universe && "Invalid key in set. Did object mutate?");
294 Sparse[BackIdx] = I - begin();
295 }
296 // This depends on SmallVector::pop_back() not invalidating iterators.
297 // std::vector::pop_back() doesn't give that guarantee.
298 Dense.pop_back();
299 return I;
300 }
301
302 /// erase - Erases an element identified by Key, if it exists.
303 ///
304 /// @param Key The key identifying the element to erase.
305 /// @returns True when an element was erased, false if no element was found.
306 ///
307 bool erase(const KeyT &Key) {
308 iterator I = find(Key);
309 if (I == end())
310 return false;
311 erase(I);
312 return true;
313 }
314};
315
316} // namespace llvm
317
318#endif // LLVM_ADT_SPARSESET_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines MallocAllocator.
#define LLVM_ATTRIBUTE_WARN_UNUSED
Definition Compiler.h:240
#define I(x, y, z)
Definition MD5.cpp:57
This file contains library features backported from future STL versions.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file defines the SmallVector class.
static const BasicSubtargetSubTypeKV * find(StringRef S, ArrayRef< BasicSubtargetSubTypeKV > A)
Find KV in array using binary search.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator erase(iterator I)
erase - Erases an existing element identified by a valid iterator.
Definition SparseSet.h:288
ValueT & operator[](const KeyT &Key)
array subscript - If an element already exists with this key, return it.
Definition SparseSet.h:267
SparseSet & operator=(const SparseSet &)=delete
void clear()
clear - Clears the set.
Definition SparseSet.h:191
const_iterator begin() const
Definition SparseSet.h:171
ValueT value_type
Definition SparseSet.h:136
iterator findIndex(unsigned Idx)
findIndex - Find an element by its index.
Definition SparseSet.h:201
SparseSet(const SparseSet &)=delete
typename DenseT::const_iterator const_iterator
Definition SparseSet.h:169
const_iterator end() const
Definition SparseSet.h:172
bool erase(const KeyT &Key)
erase - Erases an element identified by Key, if it exists.
Definition SparseSet.h:307
typename DenseT::iterator iterator
Definition SparseSet.h:168
ValueT * pointer
Definition SparseSet.h:139
size_type size() const
size - Returns the number of elements in the set.
Definition SparseSet.h:187
const_iterator find(const KeyT &Key) const
Definition SparseSet.h:226
std::pair< iterator, bool > insert(const ValueT &Val)
insert - Attempts to insert a new element.
Definition SparseSet.h:254
ValueT & reference
Definition SparseSet.h:137
iterator begin()
Definition SparseSet.h:173
ValueT pop_back_val()
Definition SparseSet.h:269
iterator end()
Definition SparseSet.h:174
SparseSet(SparseSet &&)=default
size_type count(const KeyT &Key) const
count - Returns 1 if this set contains an element identified by Key, 0 otherwise.
Definition SparseSet.h:240
const ValueT * const_pointer
Definition SparseSet.h:140
SparseSet()=default
const ValueT & const_reference
Definition SparseSet.h:138
iterator find(const KeyT &Key)
find - Find an element by its key.
Definition SparseSet.h:222
bool contains(const KeyT &Key) const
Check if the set contains the given Key.
Definition SparseSet.h:233
void setUniverse(unsigned U)
setUniverse - Set the universe size which determines the largest key the set can hold.
Definition SparseSet.h:153
FollowingPoolPopCache erase(Autorelease)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ATTRIBUTE_RETURNS_NONNULL void * safe_calloc(size_t Count, size_t Sz)
Definition MemAlloc.h:38
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
SparseSetValFunctor - Helper class for getting a value's index.
Definition SparseSet.h:68
unsigned operator()(const ValueT &Val) const
Definition SparseSet.h:69
SparseSetValTraits - Objects in a SparseSet are identified by keys that can be uniquely converted to ...
Definition SparseSet.h:57
static unsigned getValIndex(const ValueT &Val)
Definition SparseSet.h:58