Add a Briggs and Torczon sparse set implementation.
[oota-llvm.git] / include / llvm / ADT / SparseSet.h
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/SmallVector.h"
24
25 namespace llvm {
26
27 /// SparseSetFunctor - Objects in a SparseSet are identified by small integer
28 /// keys.  A functor object is used to compute the key of an object.  The
29 /// functor's operator() must return an unsigned smaller than the universe.
30 ///
31 /// The default functor implementation forwards to a getSparseSetKey() method
32 /// on the object.  It is intended for sparse sets holding ad-hoc structs.
33 ///
34 template<typename ValueT>
35 struct SparseSetFunctor {
36   unsigned operator()(const ValueT &Val) {
37     return Val.getSparseSetKey();
38   }
39 };
40
41 /// SparseSetFunctor<unsigned> - Provide a trivial identity functor for
42 /// SparseSet<unsigned>.
43 ///
44 template<> struct SparseSetFunctor<unsigned> {
45   unsigned operator()(unsigned Val) { return Val; }
46 };
47
48 /// SparseSet - Fast set implementation for objects that can be identified by
49 /// small unsigned keys.
50 ///
51 /// SparseSet allocates memory proportional to the size of the key universe, so
52 /// it is not recommended for building composite data structures.  It is useful
53 /// for algorithms that require a single set with fast operations.
54 ///
55 /// Compared to DenseSet and DenseMap, SparseSet provides constant-time fast
56 /// clear() and iteration as fast as a vector.  The find(), insert(), and
57 /// erase() operations are all constant time, and typically faster than a hash
58 /// table.  The iteration order doesn't depend on numerical key values, it only
59 /// depends on the order of insert() and erase() operations.  When no elements
60 /// have been erased, the iteration order is the insertion order.
61 ///
62 /// Compared to BitVector, SparseSet<unsigned> uses 8x-40x more memory, but
63 /// offers constant-time clear() and size() operations as well as fast
64 /// iteration independent on the size of the universe.
65 ///
66 /// SparseSet contains a dense vector holding all the objects and a sparse
67 /// array holding indexes into the dense vector.  Most of the memory is used by
68 /// the sparse array which is the size of the key universe.  The SparseT
69 /// template parameter provides a space/speed tradeoff for sets holding many
70 /// elements.
71 ///
72 /// When SparseT is uint32_t, find() only touches 2 cache lines, but the sparse
73 /// array uses 4 x Universe bytes.
74 ///
75 /// When SparseT is uint8_t (the default), find() touches up to 2+[N/256] cache
76 /// lines, but the sparse array is 4x smaller.  N is the number of elements in
77 /// the set.
78 ///
79 /// For sets that may grow to thousands of elements, SparseT should be set to
80 /// uint16_t or uint32_t.
81 ///
82 /// @param ValueT      The type of objects in the set.
83 /// @param SparseT     An unsigned integer type. See above.
84 /// @param KeyFunctorT A functor that computes the unsigned key of a ValueT.
85 ///
86 template<typename ValueT,
87          typename SparseT = uint8_t,
88          typename KeyFunctorT = SparseSetFunctor<ValueT> >
89 class SparseSet {
90   typedef SmallVector<ValueT, 8> DenseT;
91   DenseT Dense;
92   SparseT *Sparse;
93   unsigned Universe;
94   KeyFunctorT KeyOf;
95
96   // Disable copy construction and assignment.
97   // This data structure is not meant to be used that way.
98   SparseSet(const SparseSet&); // DO NOT IMPLEMENT.
99   SparseSet &operator=(const SparseSet&); // DO NOT IMPLEMENT.
100
101 public:
102   typedef ValueT value_type;
103   typedef ValueT &reference;
104   typedef const ValueT &const_reference;
105   typedef ValueT *pointer;
106   typedef const ValueT *const_pointer;
107
108   SparseSet() : Sparse(0), Universe(0) {}
109   ~SparseSet() { free(Sparse); }
110
111   /// setUniverse - Set the universe size which determines the largest key the
112   /// set can hold.  The universe must be sized before any elements can be
113   /// added.
114   ///
115   /// @param U Universe size. All object keys must be less than U.
116   ///
117   void setUniverse(unsigned U) {
118     // It's not hard to resize the universe on a non-empty set, but it doesn't
119     // seem like a likely use case, so we can add that code when we need it.
120     assert(empty() && "Can only resize universe on an empty map");
121     // Hysteresis prevents needless reallocations.
122     if (U >= Universe/4 && U <= Universe)
123       return;
124     free(Sparse);
125     // The Sparse array doesn't actually need to be initialized, so malloc
126     // would be enough here, but that will cause tools like valgrind to
127     // complain about branching on uninitialized data.
128     Sparse = reinterpret_cast<SparseT*>(calloc(U, sizeof(SparseT)));
129     Universe = U;
130   }
131
132   // Import trivial vector stuff from DenseT.
133   typedef typename DenseT::iterator iterator;
134   typedef typename DenseT::const_iterator const_iterator;
135
136   const_iterator begin() const { return Dense.begin(); }
137   const_iterator end() const { return Dense.end(); }
138   iterator begin() { return Dense.begin(); }
139   iterator end() { return Dense.end(); }
140
141   /// empty - Returns true if the set is empty.
142   ///
143   /// This is not the same as BitVector::empty().
144   ///
145   bool empty() const { return Dense.empty(); }
146
147   /// size - Returns the number of elements in the set.
148   ///
149   /// This is not the same as BitVector::size() which returns the size of the
150   /// universe.
151   ///
152   unsigned size() const { return Dense.size(); }
153
154   /// clear - Clears the set.  This is a very fast constant time operation.
155   ///
156   void clear() {
157     // Sparse does not need to be cleared, see find().
158     Dense.clear();
159   }
160
161   /// find - Find an element by its key.
162   ///
163   /// @param   Key A valid key to find.
164   /// @returns An iterator to the element identified by key, or end().
165   ///
166   iterator find(unsigned Key) {
167     assert(Key < Universe && "Key out of range");
168     assert(std::numeric_limits<SparseT>::is_integer &&
169            !std::numeric_limits<SparseT>::is_signed &&
170            "SparseT must be an unsigned integer type");
171     const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
172     for (unsigned i = Sparse[Key], e = size(); i < e; i += Stride) {
173       const unsigned FoundKey = KeyOf(Dense[i]);
174       assert(FoundKey < Universe && "Invalid key in set. Did object mutate?");
175       if (Key == FoundKey)
176         return begin() + i;
177       // Stride is 0 when SparseT >= unsigned.  We don't need to loop.
178       if (!Stride)
179         break;
180     }
181     return end();
182   }
183
184   const_iterator find(unsigned Key) const {
185     return const_cast<SparseSet*>(this)->find(Key);
186   }
187
188   /// count - Returns true if this set contains an element identified by Key.
189   ///
190   bool count(unsigned Key) const {
191     return find(Key) != end();
192   }
193
194   /// insert - Attempts to insert a new element.
195   ///
196   /// If Val is successfully inserted, return (I, true), where I is an iterator
197   /// pointing to the newly inserted element.
198   ///
199   /// If the set already contains an element with the same key as Val, return
200   /// (I, false), where I is an iterator pointing to the existing element.
201   ///
202   /// Insertion invalidates all iterators.
203   ///
204   std::pair<iterator, bool> insert(const ValueT &Val) {
205     unsigned Key = KeyOf(Val);
206     iterator I = find(Key);
207     if (I != end())
208       return std::make_pair(I, false);
209     Sparse[Key] = size();
210     Dense.push_back(Val);
211     return std::make_pair(end() - 1, true);
212   }
213
214   /// erase - Erases an existing element identified by a valid iterator.
215   ///
216   /// This invalidates all iterators, but erase() returns an iterator pointing
217   /// to the next element.  This makes it possible to erase selected elements
218   /// while iterating over the set:
219   ///
220   ///   for (SparseSet::iterator I = Set.begin(); I != Set.end();)
221   ///     if (test(*I))
222   ///       I = Set.erase(I);
223   ///     else
224   ///       ++I;
225   ///
226   /// Note that end() changes when elements are erased, unlike std::list.
227   ///
228   iterator erase(iterator I) {
229     assert(I - begin() < size() && "Invalid iterator");
230     if (I != end() - 1) {
231       *I = Dense.back();
232       unsigned BackKey = KeyOf(Dense.back());
233       assert(BackKey < Universe && "Invalid key in set. Did object mutate?");
234       Sparse[BackKey] = I - begin();
235     }
236     // This depends on SmallVector::pop_back() not invalidating iterators.
237     // std::vector::pop_back() doesn't give that guarantee.
238     Dense.pop_back();
239     return I;
240   }
241
242   /// erase - Erases an element identified by Key, if it exists.
243   ///
244   /// @param   Key The key identifying the element to erase.
245   /// @returns True when an element was erased, false if no element was found.
246   ///
247   bool erase(unsigned Key) {
248     iterator I = find(Key);
249     if (I == end())
250       return false;
251     erase(I);
252     return true;
253   }
254
255 };
256
257 } // end namespace llvm
258
259 #endif