Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

308 lines
11 KiB

  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. typedef typename KeyFunctorT::argument_type KeyT;
  115. typedef SmallVector<ValueT, 8> DenseT;
  116. DenseT Dense;
  117. SparseT *Sparse;
  118. unsigned Universe;
  119. KeyFunctorT KeyIndexOf;
  120. SparseSetValFunctor<KeyT, ValueT, KeyFunctorT> ValIndexOf;
  121. // Disable copy construction and assignment.
  122. // This data structure is not meant to be used that way.
  123. SparseSet(const SparseSet&) LLVM_DELETED_FUNCTION;
  124. SparseSet &operator=(const SparseSet&) LLVM_DELETED_FUNCTION;
  125. public:
  126. typedef ValueT value_type;
  127. typedef ValueT &reference;
  128. typedef const ValueT &const_reference;
  129. typedef ValueT *pointer;
  130. typedef const ValueT *const_pointer;
  131. SparseSet() : Sparse(0), Universe(0) {}
  132. ~SparseSet() { free(Sparse); }
  133. /// setUniverse - Set the universe size which determines the largest key the
  134. /// set can hold. The universe must be sized before any elements can be
  135. /// added.
  136. ///
  137. /// @param U Universe size. All object keys must be less than U.
  138. ///
  139. void setUniverse(unsigned U) {
  140. // It's not hard to resize the universe on a non-empty set, but it doesn't
  141. // seem like a likely use case, so we can add that code when we need it.
  142. assert(empty() && "Can only resize universe on an empty map");
  143. // Hysteresis prevents needless reallocations.
  144. if (U >= Universe/4 && U <= Universe)
  145. return;
  146. free(Sparse);
  147. // The Sparse array doesn't actually need to be initialized, so malloc
  148. // would be enough here, but that will cause tools like valgrind to
  149. // complain about branching on uninitialized data.
  150. Sparse = reinterpret_cast<SparseT*>(calloc(U, sizeof(SparseT)));
  151. Universe = U;
  152. }
  153. // Import trivial vector stuff from DenseT.
  154. typedef typename DenseT::iterator iterator;
  155. typedef typename DenseT::const_iterator const_iterator;
  156. const_iterator begin() const { return Dense.begin(); }
  157. const_iterator end() const { return Dense.end(); }
  158. iterator begin() { return Dense.begin(); }
  159. iterator end() { return Dense.end(); }
  160. /// empty - Returns true if the set is empty.
  161. ///
  162. /// This is not the same as BitVector::empty().
  163. ///
  164. bool empty() const { return Dense.empty(); }
  165. /// size - Returns the number of elements in the set.
  166. ///
  167. /// This is not the same as BitVector::size() which returns the size of the
  168. /// universe.
  169. ///
  170. unsigned size() const { return Dense.size(); }
  171. /// clear - Clears the set. This is a very fast constant time operation.
  172. ///
  173. void clear() {
  174. // Sparse does not need to be cleared, see find().
  175. Dense.clear();
  176. }
  177. /// findIndex - Find an element by its index.
  178. ///
  179. /// @param Idx A valid index to find.
  180. /// @returns An iterator to the element identified by key, or end().
  181. ///
  182. iterator findIndex(unsigned Idx) {
  183. assert(Idx < Universe && "Key out of range");
  184. assert(std::numeric_limits<SparseT>::is_integer &&
  185. !std::numeric_limits<SparseT>::is_signed &&
  186. "SparseT must be an unsigned integer type");
  187. const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
  188. for (unsigned i = Sparse[Idx], e = size(); i < e; i += Stride) {
  189. const unsigned FoundIdx = ValIndexOf(Dense[i]);
  190. assert(FoundIdx < Universe && "Invalid key in set. Did object mutate?");
  191. if (Idx == FoundIdx)
  192. return begin() + i;
  193. // Stride is 0 when SparseT >= unsigned. We don't need to loop.
  194. if (!Stride)
  195. break;
  196. }
  197. return end();
  198. }
  199. /// find - Find an element by its key.
  200. ///
  201. /// @param Key A valid key to find.
  202. /// @returns An iterator to the element identified by key, or end().
  203. ///
  204. iterator find(const KeyT &Key) {
  205. return findIndex(KeyIndexOf(Key));
  206. }
  207. const_iterator find(const KeyT &Key) const {
  208. return const_cast<SparseSet*>(this)->findIndex(KeyIndexOf(Key));
  209. }
  210. /// count - Returns true if this set contains an element identified by Key.
  211. ///
  212. bool count(const KeyT &Key) const {
  213. return find(Key) != end();
  214. }
  215. /// insert - Attempts to insert a new element.
  216. ///
  217. /// If Val is successfully inserted, return (I, true), where I is an iterator
  218. /// pointing to the newly inserted element.
  219. ///
  220. /// If the set already contains an element with the same key as Val, return
  221. /// (I, false), where I is an iterator pointing to the existing element.
  222. ///
  223. /// Insertion invalidates all iterators.
  224. ///
  225. std::pair<iterator, bool> insert(const ValueT &Val) {
  226. unsigned Idx = ValIndexOf(Val);
  227. iterator I = findIndex(Idx);
  228. if (I != end())
  229. return std::make_pair(I, false);
  230. Sparse[Idx] = size();
  231. Dense.push_back(Val);
  232. return std::make_pair(end() - 1, true);
  233. }
  234. /// array subscript - If an element already exists with this key, return it.
  235. /// Otherwise, automatically construct a new value from Key, insert it,
  236. /// and return the newly inserted element.
  237. ValueT &operator[](const KeyT &Key) {
  238. return *insert(ValueT(Key)).first;
  239. }
  240. /// erase - Erases an existing element identified by a valid iterator.
  241. ///
  242. /// This invalidates all iterators, but erase() returns an iterator pointing
  243. /// to the next element. This makes it possible to erase selected elements
  244. /// while iterating over the set:
  245. ///
  246. /// for (SparseSet::iterator I = Set.begin(); I != Set.end();)
  247. /// if (test(*I))
  248. /// I = Set.erase(I);
  249. /// else
  250. /// ++I;
  251. ///
  252. /// Note that end() changes when elements are erased, unlike std::list.
  253. ///
  254. iterator erase(iterator I) {
  255. assert(unsigned(I - begin()) < size() && "Invalid iterator");
  256. if (I != end() - 1) {
  257. *I = Dense.back();
  258. unsigned BackIdx = ValIndexOf(Dense.back());
  259. assert(BackIdx < Universe && "Invalid key in set. Did object mutate?");
  260. Sparse[BackIdx] = I - begin();
  261. }
  262. // This depends on SmallVector::pop_back() not invalidating iterators.
  263. // std::vector::pop_back() doesn't give that guarantee.
  264. Dense.pop_back();
  265. return I;
  266. }
  267. /// erase - Erases an element identified by Key, if it exists.
  268. ///
  269. /// @param Key The key identifying the element to erase.
  270. /// @returns True when an element was erased, false if no element was found.
  271. ///
  272. bool erase(const KeyT &Key) {
  273. iterator I = find(Key);
  274. if (I == end())
  275. return false;
  276. erase(I);
  277. return true;
  278. }
  279. };
  280. } // end namespace llvm
  281. #endif