SparseSet.h 11 KB

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