set.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_COMMON_SET_H_
  5. #define CARBON_COMMON_SET_H_
  6. #include <concepts>
  7. #include <type_traits>
  8. #include "common/check.h"
  9. #include "common/hashtable_key_context.h"
  10. #include "common/raw_hashtable.h"
  11. #include "llvm/Support/Compiler.h"
  12. namespace Carbon {
  13. // Forward declarations to resolve cyclic references.
  14. template <typename KeyT, typename KeyContextT>
  15. class SetView;
  16. template <typename KeyT, typename KeyContextT>
  17. class SetBase;
  18. template <typename KeyT, ssize_t SmallSize, typename KeyContextT>
  19. class Set;
  20. // A read-only view type for a set of keys.
  21. //
  22. // This view is a cheap-to-copy type that should be passed by value, but
  23. // provides view or read-only reference semantics to the underlying set data
  24. // structure.
  25. //
  26. // This should always be preferred to a `const`-ref parameter for the `SetBase`
  27. // or `Set` type as it provides more flexibility and a cleaner API.
  28. //
  29. // Note that while this type is a read-only view, that applies to the underlying
  30. // *set* data structure, not the individual entries stored within it. Those can
  31. // be mutated freely as long as both the hashes and equality of the keys are
  32. // preserved. If we applied a deep-`const` design here, it would prevent using
  33. // this type in situations where the keys carry state (unhashed and not part of
  34. // equality) that is mutated while the associative container is not. A view of
  35. // immutable data can always be obtained by using `SetView<const T>`, and we
  36. // enable conversions to more-const views. This mirrors the semantics of views
  37. // like `std::span`.
  38. //
  39. // A specific `KeyContextT` type can optionally be provided to configure how
  40. // keys will be hashed and compared. The default is `DefaultKeyContext` which is
  41. // stateless and will hash using `Carbon::HashValue` and compare using
  42. // `operator==`. Every method accepting a lookup key or operating on the keys in
  43. // the table will also accept an instance of this type. For stateless context
  44. // types, including the default, an instance will be default constructed if not
  45. // provided to these methods. However, stateful contexts should be constructed
  46. // and passed in explicitly. The context type should be small and reasonable to
  47. // pass by value, often a wrapper or pointer to the relevant context needed for
  48. // hashing and comparing keys. For more details about the key context, see
  49. // `hashtable_key_context.h`.
  50. template <typename InputKeyT, typename InputKeyContextT = DefaultKeyContext>
  51. class SetView : RawHashtable::ViewImpl<InputKeyT, void, InputKeyContextT> {
  52. using ImplT = RawHashtable::ViewImpl<InputKeyT, void, InputKeyContextT>;
  53. public:
  54. using KeyT = typename ImplT::KeyT;
  55. using KeyContextT = typename ImplT::KeyContextT;
  56. using MetricsT = typename ImplT::MetricsT;
  57. // This type represents the result of lookup operations. It encodes whether
  58. // the lookup was a success as well as accessors for the key.
  59. class LookupResult {
  60. public:
  61. LookupResult() = default;
  62. explicit LookupResult(KeyT& key) : key_(&key) {}
  63. explicit operator bool() const { return key_ != nullptr; }
  64. auto key() const -> KeyT& { return *key_; }
  65. private:
  66. KeyT* key_ = nullptr;
  67. };
  68. // Enable implicit conversions that add `const`-ness to the key type.
  69. // NOLINTNEXTLINE(google-explicit-constructor)
  70. SetView(const SetView<std::remove_const_t<KeyT>, KeyContextT>& other_view)
  71. requires(!std::same_as<KeyT, std::remove_const_t<KeyT>>)
  72. : ImplT(other_view) {}
  73. // Tests whether a key is present in the set.
  74. template <typename LookupKeyT>
  75. auto Contains(LookupKeyT lookup_key,
  76. KeyContextT key_context = KeyContextT()) const -> bool;
  77. // Lookup a key in the set.
  78. template <typename LookupKeyT>
  79. auto Lookup(LookupKeyT lookup_key,
  80. KeyContextT key_context = KeyContextT()) const -> LookupResult;
  81. // Run the provided callback for every key in the set.
  82. template <typename CallbackT>
  83. auto ForEach(CallbackT callback) -> void
  84. requires(std::invocable<CallbackT, KeyT&>);
  85. // This routine is relatively inefficient and only intended for use in
  86. // benchmarking or logging of performance anomalies. The specific metrics
  87. // returned have no specific guarantees beyond being informative in
  88. // benchmarks.
  89. auto ComputeMetrics(KeyContextT key_context = KeyContextT()) -> MetricsT {
  90. return ImplT::ComputeMetricsImpl(key_context);
  91. }
  92. private:
  93. template <typename SetKeyT, ssize_t SmallSize, typename KeyContextT>
  94. friend class Set;
  95. friend class SetBase<KeyT, KeyContextT>;
  96. friend class SetView<const KeyT, KeyContextT>;
  97. using EntryT = typename ImplT::EntryT;
  98. SetView() = default;
  99. // NOLINTNEXTLINE(google-explicit-constructor): Implicit by design.
  100. SetView(ImplT base) : ImplT(base) {}
  101. SetView(ssize_t size, RawHashtable::Storage* storage)
  102. : ImplT(size, storage) {}
  103. };
  104. // A base class for a `Set` type that remains mutable while type-erasing the
  105. // `SmallSize` (SSO) template parameter.
  106. //
  107. // A pointer or reference to this type is the preferred way to pass a mutable
  108. // handle to a `Set` type across API boundaries as it avoids encoding specific
  109. // SSO sizing information while providing a near-complete mutable API.
  110. template <typename InputKeyT, typename InputKeyContextT>
  111. class SetBase
  112. : protected RawHashtable::BaseImpl<InputKeyT, void, InputKeyContextT> {
  113. protected:
  114. using ImplT = RawHashtable::BaseImpl<InputKeyT, void, InputKeyContextT>;
  115. public:
  116. using KeyT = typename ImplT::KeyT;
  117. using KeyContextT = typename ImplT::KeyContextT;
  118. using ViewT = SetView<KeyT, KeyContextT>;
  119. using LookupResult = typename ViewT::LookupResult;
  120. using MetricsT = typename ImplT::MetricsT;
  121. // The result type for insertion operations both indicates whether an insert
  122. // was needed (as opposed to the key already being in the set), and provides
  123. // access to the key.
  124. class InsertResult {
  125. public:
  126. InsertResult() = default;
  127. explicit InsertResult(bool inserted, KeyT& key)
  128. : key_(&key), inserted_(inserted) {}
  129. auto is_inserted() const -> bool { return inserted_; }
  130. auto key() const -> KeyT& { return *key_; }
  131. private:
  132. KeyT* key_;
  133. bool inserted_;
  134. };
  135. // Implicitly convertible to the relevant view type.
  136. //
  137. // NOLINTNEXTLINE(google-explicit-constructor): Designed to implicitly decay.
  138. operator ViewT() const { return this->view_impl(); }
  139. // We can't chain the above conversion with the conversions on `ViewT` to add
  140. // const, so explicitly support adding const to produce a view here.
  141. //
  142. // NOLINTNEXTLINE(google-explicit-constructor): Designed to implicitly decay.
  143. operator SetView<const KeyT, KeyContextT>() const { return ViewT(*this); }
  144. // Convenience forwarder to the view type.
  145. template <typename LookupKeyT>
  146. auto Contains(LookupKeyT lookup_key,
  147. KeyContextT key_context = KeyContextT()) const -> bool {
  148. return ViewT(*this).Contains(lookup_key, key_context);
  149. }
  150. // Convenience forwarder to the view type.
  151. template <typename LookupKeyT>
  152. auto Lookup(LookupKeyT lookup_key,
  153. KeyContextT key_context = KeyContextT()) const -> LookupResult {
  154. return ViewT(*this).Lookup(lookup_key, key_context);
  155. }
  156. // Convenience forwarder to the view type.
  157. template <typename CallbackT>
  158. auto ForEach(CallbackT callback) -> void
  159. requires(std::invocable<CallbackT, KeyT&>)
  160. {
  161. return ViewT(*this).ForEach(callback);
  162. }
  163. // Convenience forwarder to the view type.
  164. auto ComputeMetrics(KeyContextT key_context = KeyContextT()) const
  165. -> MetricsT {
  166. return ViewT(*this).ComputeMetrics(key_context);
  167. }
  168. // Insert a key into the set. If the key is already present, no insertion is
  169. // performed and that present key is available in the result. Otherwise a new
  170. // key is inserted and constructed from the argument and available in the
  171. // result.
  172. template <typename LookupKeyT>
  173. auto Insert(LookupKeyT lookup_key, KeyContextT key_context = KeyContextT())
  174. -> InsertResult;
  175. // Insert a key into the map and call the provided callback if necessary to
  176. // produce a new key when no existing value is found.
  177. //
  178. // Example: `m.Insert(key_equivalent, [] { return real_key; });`
  179. //
  180. // The point of this function is when the lookup key is _different_from the
  181. // stored key. However, we don't restrict it in case that blocks generic
  182. // usage.
  183. template <typename LookupKeyT, typename KeyCallbackT>
  184. auto Insert(LookupKeyT lookup_key, KeyCallbackT key_cb,
  185. KeyContextT key_context = KeyContextT()) -> InsertResult
  186. requires(
  187. !std::same_as<KeyT, KeyCallbackT> &&
  188. std::convertible_to<decltype(std::declval<KeyCallbackT>()()), KeyT>);
  189. // Insert a key into the set and call the provided callback to allow in-place
  190. // construction of the key if not already present. The lookup key is passed
  191. // through to the callback so it needn't be captured and can be kept in a
  192. // register argument throughout.
  193. //
  194. // Example:
  195. // ```cpp
  196. // m.Insert("widget", [](MyStringViewType lookup_key, void* key_storage) {
  197. // new (key_storage) MyStringType(lookup_key);
  198. // });
  199. // ```
  200. template <typename LookupKeyT, typename InsertCallbackT>
  201. auto Insert(LookupKeyT lookup_key, InsertCallbackT insert_cb,
  202. KeyContextT key_context = KeyContextT()) -> InsertResult
  203. requires std::invocable<InsertCallbackT, LookupKeyT, void*>;
  204. // Grow the set to a specific allocation size.
  205. //
  206. // This will grow the set's hashtable if necessary for it to have an
  207. // allocation size of `target_alloc_size` which must be a power of two. Note
  208. // that this will not allow that many keys to be inserted, but a smaller
  209. // number based on the maximum load factor. If a specific number of insertions
  210. // need to be achieved without triggering growth, use the `GrowForInsertCount`
  211. // method.
  212. auto GrowToAllocSize(ssize_t target_alloc_size,
  213. KeyContextT key_context = KeyContextT()) -> void;
  214. // Grow the set sufficiently to allow inserting the specified number of keys.
  215. auto GrowForInsertCount(ssize_t count,
  216. KeyContextT key_context = KeyContextT()) -> void;
  217. // Erase a key from the set.
  218. template <typename LookupKeyT>
  219. auto Erase(LookupKeyT lookup_key, KeyContextT key_context = KeyContextT())
  220. -> bool;
  221. // Clear all key/value pairs from the set but leave the underlying hashtable
  222. // allocated and in place.
  223. auto Clear() -> void;
  224. protected:
  225. using ImplT::ImplT;
  226. };
  227. // A data structure for a set of keys.
  228. //
  229. // This set supports small size optimization (or "SSO"). The provided
  230. // `SmallSize` type parameter indicates the size of an embedded buffer for
  231. // storing sets small enough to fit. The default is zero, which always allocates
  232. // a heap buffer on construction. When non-zero, must be a multiple of the
  233. // `MaxGroupSize` which is currently 16. The library will check that the size is
  234. // valid and provide an error at compile time if not. We don't automatically
  235. // select the next multiple or otherwise fit the size to the constraints to make
  236. // it clear in the code how much memory is used by the SSO buffer.
  237. //
  238. // This data structure optimizes heavily for small key types that are cheap to
  239. // move and even copy. Using types with large keys or expensive to copy keys may
  240. // create surprising performance bottlenecks. A `std::string` key should be fine
  241. // with generally small strings, but if some or many strings are large heap
  242. // allocations the performance of hashtable routines may be unacceptably bad and
  243. // another data structure or key design is likely preferable.
  244. //
  245. // Note that this type should typically not appear on API boundaries; either
  246. // `SetBase` or `SetView` should be used instead.
  247. template <typename InputKeyT, ssize_t SmallSize = 0,
  248. typename InputKeyContextT = DefaultKeyContext>
  249. class Set : public RawHashtable::TableImpl<SetBase<InputKeyT, InputKeyContextT>,
  250. SmallSize> {
  251. using BaseT = SetBase<InputKeyT, InputKeyContextT>;
  252. using ImplT = RawHashtable::TableImpl<BaseT, SmallSize>;
  253. public:
  254. using KeyT = typename BaseT::KeyT;
  255. Set() = default;
  256. Set(const Set& arg) = default;
  257. Set(Set&& arg) noexcept = default;
  258. auto operator=(const Set& arg) -> Set& = default;
  259. auto operator=(Set&& arg) noexcept -> Set& = default;
  260. // Reset the entire state of the hashtable to as it was when constructed,
  261. // throwing away any intervening allocations.
  262. auto Reset() -> void;
  263. };
  264. template <typename InputKeyT, typename InputKeyContextT>
  265. template <typename LookupKeyT>
  266. auto SetView<InputKeyT, InputKeyContextT>::Contains(
  267. LookupKeyT lookup_key, KeyContextT key_context) const -> bool {
  268. return this->LookupEntry(lookup_key, key_context) != nullptr;
  269. }
  270. template <typename InputKeyT, typename InputKeyContextT>
  271. template <typename LookupKeyT>
  272. auto SetView<InputKeyT, InputKeyContextT>::Lookup(LookupKeyT lookup_key,
  273. KeyContextT key_context) const
  274. -> LookupResult {
  275. EntryT* entry = this->LookupEntry(lookup_key, key_context);
  276. if (!entry) {
  277. return LookupResult();
  278. }
  279. return LookupResult(entry->key());
  280. }
  281. template <typename InputKeyT, typename InputKeyContextT>
  282. template <typename CallbackT>
  283. auto SetView<InputKeyT, InputKeyContextT>::ForEach(CallbackT callback) -> void
  284. requires(std::invocable<CallbackT, KeyT&>)
  285. {
  286. this->ForEachEntry([callback](EntryT& entry) { callback(entry.key()); },
  287. [](auto...) {});
  288. }
  289. template <typename InputKeyT, typename InputKeyContextT>
  290. template <typename LookupKeyT>
  291. auto SetBase<InputKeyT, InputKeyContextT>::Insert(LookupKeyT lookup_key,
  292. KeyContextT key_context)
  293. -> InsertResult {
  294. return Insert(
  295. lookup_key,
  296. [](LookupKeyT lookup_key, void* key_storage) {
  297. new (key_storage) KeyT(std::move(lookup_key));
  298. },
  299. key_context);
  300. }
  301. template <typename InputKeyT, typename InputKeyContextT>
  302. template <typename LookupKeyT, typename KeyCallbackT>
  303. auto SetBase<InputKeyT, InputKeyContextT>::Insert(LookupKeyT lookup_key,
  304. KeyCallbackT key_cb,
  305. KeyContextT key_context)
  306. -> InsertResult
  307. requires(!std::same_as<KeyT, KeyCallbackT> &&
  308. std::convertible_to<decltype(std::declval<KeyCallbackT>()()), KeyT>)
  309. {
  310. return Insert(
  311. lookup_key,
  312. [&key_cb](LookupKeyT /*lookup_key*/, void* key_storage) {
  313. new (key_storage) KeyT(key_cb());
  314. },
  315. key_context);
  316. }
  317. template <typename InputKeyT, typename InputKeyContextT>
  318. template <typename LookupKeyT, typename InsertCallbackT>
  319. auto SetBase<InputKeyT, InputKeyContextT>::Insert(LookupKeyT lookup_key,
  320. InsertCallbackT insert_cb,
  321. KeyContextT key_context)
  322. -> InsertResult
  323. requires std::invocable<InsertCallbackT, LookupKeyT, void*>
  324. {
  325. auto [entry, inserted] = this->InsertImpl(lookup_key, key_context);
  326. CARBON_DCHECK(entry, "Should always result in a valid index.");
  327. if (LLVM_LIKELY(!inserted)) {
  328. return InsertResult(false, entry->key());
  329. }
  330. insert_cb(lookup_key, static_cast<void*>(&entry->key_storage));
  331. return InsertResult(true, entry->key());
  332. }
  333. template <typename InputKeyT, typename InputKeyContextT>
  334. auto SetBase<InputKeyT, InputKeyContextT>::GrowToAllocSize(
  335. ssize_t target_alloc_size, KeyContextT key_context) -> void {
  336. this->GrowToAllocSizeImpl(target_alloc_size, key_context);
  337. }
  338. template <typename InputKeyT, typename InputKeyContextT>
  339. auto SetBase<InputKeyT, InputKeyContextT>::GrowForInsertCount(
  340. ssize_t count, KeyContextT key_context) -> void {
  341. this->GrowForInsertCountImpl(count, key_context);
  342. }
  343. template <typename InputKeyT, typename InputKeyContextT>
  344. template <typename LookupKeyT>
  345. auto SetBase<InputKeyT, InputKeyContextT>::Erase(LookupKeyT lookup_key,
  346. KeyContextT key_context)
  347. -> bool {
  348. return this->EraseImpl(lookup_key, key_context);
  349. }
  350. template <typename InputKeyT, typename InputKeyContextT>
  351. auto SetBase<InputKeyT, InputKeyContextT>::Clear() -> void {
  352. this->ClearImpl();
  353. }
  354. template <typename InputKeyT, ssize_t SmallSize, typename InputKeyContextT>
  355. auto Set<InputKeyT, SmallSize, InputKeyContextT>::Reset() -> void {
  356. this->ResetImpl();
  357. }
  358. } // namespace Carbon
  359. #endif // CARBON_COMMON_SET_H_