raw_hashtable.h 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  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_RAW_HASHTABLE_H_
  5. #define CARBON_COMMON_RAW_HASHTABLE_H_
  6. #include <algorithm>
  7. #include <concepts>
  8. #include <cstddef>
  9. #include <cstring>
  10. #include <iterator>
  11. #include <new>
  12. #include <type_traits>
  13. #include <utility>
  14. #include "common/check.h"
  15. #include "common/hashing.h"
  16. #include "common/raw_hashtable_metadata_group.h"
  17. #include "llvm/Support/Compiler.h"
  18. #include "llvm/Support/MathExtras.h"
  19. // A namespace collecting a set of low-level utilities for building hashtable
  20. // data structures. These should only be used as implementation details of
  21. // higher-level data-structure APIs.
  22. //
  23. // The utilities here use the `hashtable_key_context.h` provided `KeyContext` to
  24. // support the necessary hashtable operations on keys: hashing and comparison.
  25. // This also serves as the customization point for hashtables built on this
  26. // infrastructure for those operations. See that header file for details.
  27. //
  28. // These utilities support hashtables following a *specific* API design pattern,
  29. // and using Small-Size Optimization, or "SSO", when desired. We expect there to
  30. // be three layers to any hashtable design:
  31. //
  32. // - A *view* type: a read-only view of the hashtable contents. This type should
  33. // be a value type and is expected to be passed by-value in APIs. However, it
  34. // will have `const`-reference semantics, much like a `std::string_view`. Note
  35. // that the *entries* will continue to be mutable, it is only the *table* that
  36. // is read-only.
  37. //
  38. // - A *base* type: a base class type of the actual hashtable, which allows
  39. // almost all mutable operations but erases any specific SSO buffer size.
  40. // Because this is a base of the actual hash table, it is designed to be
  41. // passed as a non-`const` reference or pointer.
  42. //
  43. // - A *table* type: the actual hashtable which derives from the base type and
  44. // adds any desired SSO storage buffer. Beyond the physical storage, it also
  45. // allows resetting the table to its initial state & allocated size, as well
  46. // as copying and moving the table.
  47. //
  48. // For complete examples of the API design, see `set.h` for a hashtable-based
  49. // set data structure, and `map.h` for a hashtable-based map data structure.
  50. //
  51. // The hashtable design implemented here has several key invariants and design
  52. // elements that are essential to all three of the types above and the
  53. // functionality they provide.
  54. //
  55. // - The underlying hashtable uses [open addressing], a power-of-two table size,
  56. // and quadratic probing rather than closed addressing and chaining.
  57. //
  58. // [open addressing]: https://en.wikipedia.org/wiki/Open_addressing
  59. //
  60. // - Each _slot_ in the table corresponds to a key, a value, and one byte of
  61. // metadata. Each _entry_ is a key and value. The key and value for an entry
  62. // are stored together.
  63. //
  64. // - The allocated storage is organized into an array of metadata bytes followed
  65. // by an array of entry storage.
  66. //
  67. // - The metadata byte corresponding to each entry marks that entry is either
  68. // empty, deleted, or present. When present, a 7-bit tag is also stored using
  69. // another 7 bits from the hash of the entry key.
  70. //
  71. // - The storage for an entry is an internal type that should not be exposed to
  72. // users, and instead only the underlying keys and values.
  73. //
  74. // - The hash addressing and probing occurs over *groups* of slots rather than
  75. // individual entries. When inserting a new entry, it can be added to the
  76. // group it hashes to as long it is not full, and can even replace a slot with
  77. // a tombstone indicating a previously deleted entry. Only when the group is
  78. // full will it look at the next group in the probe sequence. As a result,
  79. // there may be entries in a group where a different group is the start of
  80. // that entry's probe sequence. Also, when performing a lookup, every group in
  81. // the probe sequence must be inspected for the lookup key until it is found
  82. // or the group has an empty slot.
  83. //
  84. // - Groups are scanned rapidly using the one-byte metadata for each entry in
  85. // the group and CPU instructions that allow comparing all of the metadata for
  86. // a group in parallel. For more details on the metadata group encoding and
  87. // scanning, see `raw_hashtable_metadata_group.h`.
  88. //
  89. // - `GroupSize` is a platform-specific relatively small power of two that fits
  90. // in some hardware register. However, `MaxGroupSize` is provided as a
  91. // portable max that is also a power of two. The table storage, whether
  92. // provided by an SSO buffer or allocated, is required to be a multiple of
  93. // `MaxGroupSize` to keep the requirement portable but sufficient for all
  94. // platforms.
  95. //
  96. // - There is *always* an allocated table of some multiple of `MaxGroupSize`.
  97. // This allows accesses to be branchless. When heap allocated, we pro-actively
  98. // allocate at least a minimum heap size table. When there is a small-size
  99. // optimization (SSO) buffer, that provides the initial allocation.
  100. //
  101. // - The table performs a minimal amount of bookkeeping that limits the APIs it
  102. // can support:
  103. // - `alloc_size` is the size of the table *allocated* (not *used*), and is
  104. // always a power of 2 at least as big as `MinAllocatedSize`.
  105. // - `storage` is a pointer to the storage for the `alloc_size` slots of the
  106. // table, and never null.
  107. // - `small_alloc_size` is the maximum `alloc_size` where the table is stored
  108. // in the object itself instead of separately on the heap. In this case,
  109. // `storage` points to `small_storage_`.
  110. // - `growth_budget` is the number of entries that may be added before the
  111. // table allocation is doubled. It is always
  112. // `GrowthThresholdForAllocSize(alloc_size)` minus the number of
  113. // non-empty (filled or deleted) slots. If it ever falls to 0, the table
  114. // is grown to keep it greater than 0.
  115. // There is also the "moved-from" state where the table may only be
  116. // reinitialized or destroyed where the `alloc_size` is 0 and `storage` is
  117. // null. Since it doesn't track the exact number of filled entries in a table,
  118. // it doesn't support a container-style `size` API.
  119. //
  120. // - There is no direct iterator support because of the complexity of embedding
  121. // the group-based metadata scanning into an iterator model. Instead, there is
  122. // just a for-each method that is passed a lambda to observe all entries. The
  123. // order of this observation is also not guaranteed.
  124. namespace Carbon::RawHashtable {
  125. // If allocating storage, allocate a minimum of one cacheline of group metadata
  126. // or a minimum of one group, whichever is larger.
  127. constexpr ssize_t MinAllocatedSize = std::max<ssize_t>(64, MaxGroupSize);
  128. // An entry in the hashtable storage of a `KeyT` and `ValueT` object.
  129. //
  130. // Allows manual construction, destruction, and access to these values so we can
  131. // create arrays af the entries prior to populating them with actual keys and
  132. // values.
  133. template <typename KeyT, typename ValueT>
  134. struct StorageEntry {
  135. static constexpr bool IsTriviallyDestructible =
  136. std::is_trivially_destructible_v<KeyT> &&
  137. std::is_trivially_destructible_v<ValueT>;
  138. static constexpr bool IsTriviallyRelocatable =
  139. IsTriviallyDestructible && std::is_trivially_move_constructible_v<KeyT> &&
  140. std::is_trivially_move_constructible_v<ValueT>;
  141. auto key() const -> const KeyT& {
  142. // Ensure we don't need more alignment than available. Inside a method body
  143. // to apply to the complete type.
  144. static_assert(
  145. alignof(StorageEntry) <= MinAllocatedSize,
  146. "The minimum allocated size turns into the alignment of our array of "
  147. "storage entries as they follow the metadata byte array.");
  148. return *std::launder(reinterpret_cast<const KeyT*>(&key_storage));
  149. }
  150. auto key() -> KeyT& {
  151. return const_cast<KeyT&>(const_cast<const StorageEntry*>(this)->key());
  152. }
  153. auto value() const -> const ValueT& {
  154. return *std::launder(reinterpret_cast<const ValueT*>(&value_storage));
  155. }
  156. auto value() -> ValueT& {
  157. return const_cast<ValueT&>(const_cast<const StorageEntry*>(this)->value());
  158. }
  159. // We handle destruction and move manually as we only want to expose distinct
  160. // `KeyT` and `ValueT` subobjects to user code that may need to do in-place
  161. // construction. As a consequence, this struct only provides the storage and
  162. // we have to manually manage the construction, move, and destruction of the
  163. // objects.
  164. auto Destroy() -> void {
  165. static_assert(!IsTriviallyDestructible,
  166. "Should never instantiate when trivial!");
  167. key().~KeyT();
  168. value().~ValueT();
  169. }
  170. auto CopyFrom(const StorageEntry& entry) -> void {
  171. if constexpr (IsTriviallyRelocatable) {
  172. memcpy(this, &entry, sizeof(StorageEntry));
  173. } else {
  174. new (&key_storage) KeyT(entry.key());
  175. new (&value_storage) ValueT(entry.value());
  176. }
  177. }
  178. // Move from an expiring entry and destroy that entry's key and value.
  179. // Optimizes to directly use `memcpy` when correct.
  180. auto MoveFrom(StorageEntry&& entry) -> void {
  181. if constexpr (IsTriviallyRelocatable) {
  182. memcpy(this, &entry, sizeof(StorageEntry));
  183. } else {
  184. new (&key_storage) KeyT(std::move(entry.key()));
  185. entry.key().~KeyT();
  186. new (&value_storage) ValueT(std::move(entry.value()));
  187. entry.value().~ValueT();
  188. }
  189. }
  190. alignas(KeyT) std::byte key_storage[sizeof(KeyT)];
  191. alignas(ValueT) std::byte value_storage[sizeof(ValueT)];
  192. };
  193. // A specialization of the storage entry for sets without a distinct value type.
  194. // Somewhat duplicative with the key-value version, but C++ specialization makes
  195. // doing better difficult.
  196. template <typename KeyT>
  197. struct StorageEntry<KeyT, void> {
  198. static constexpr bool IsTriviallyDestructible =
  199. std::is_trivially_destructible_v<KeyT>;
  200. static constexpr bool IsTriviallyRelocatable =
  201. IsTriviallyDestructible && std::is_trivially_move_constructible_v<KeyT>;
  202. auto key() const -> const KeyT& {
  203. // Ensure we don't need more alignment than available.
  204. static_assert(
  205. alignof(StorageEntry) <= MinAllocatedSize,
  206. "The minimum allocated size turns into the alignment of our array of "
  207. "storage entries as they follow the metadata byte array.");
  208. return *std::launder(reinterpret_cast<const KeyT*>(&key_storage));
  209. }
  210. auto key() -> KeyT& {
  211. return const_cast<KeyT&>(const_cast<const StorageEntry*>(this)->key());
  212. }
  213. auto Destroy() -> void {
  214. static_assert(!IsTriviallyDestructible,
  215. "Should never instantiate when trivial!");
  216. key().~KeyT();
  217. }
  218. auto CopyFrom(const StorageEntry& entry) -> void {
  219. if constexpr (IsTriviallyRelocatable) {
  220. memcpy(this, &entry, sizeof(StorageEntry));
  221. } else {
  222. new (&key_storage) KeyT(entry.key());
  223. }
  224. }
  225. auto MoveFrom(StorageEntry&& entry) -> void {
  226. if constexpr (IsTriviallyRelocatable) {
  227. memcpy(this, &entry, sizeof(StorageEntry));
  228. } else {
  229. new (&key_storage) KeyT(std::move(entry.key()));
  230. entry.key().~KeyT();
  231. }
  232. }
  233. alignas(KeyT) std::byte key_storage[sizeof(KeyT)];
  234. };
  235. struct Metrics {
  236. // How many keys are present in the table.
  237. ssize_t key_count = 0;
  238. // How many slots of the table are reserved due to deleted markers required to
  239. // preserve probe sequences.
  240. ssize_t deleted_count = 0;
  241. // How many bytes of allocated storage are used by the table. Note, does not
  242. // include the table object or any small-size buffer.
  243. ssize_t storage_bytes = 0;
  244. // How many keys have required probing beyond the initial group. These are the
  245. // keys with a probe distance > 0.
  246. ssize_t probed_key_count = 0;
  247. // The probe distance averaged over every key. If every key is in its initial
  248. // group, this will be zero as no keys will have a larger probe distance. In
  249. // general, we want this to be as close to zero as possible.
  250. double probe_avg_distance = 0.0;
  251. // The maximum probe distance found for a single key in the table.
  252. ssize_t probe_max_distance = 0;
  253. // The average number of probing comparisons required to locate a specific key
  254. // in the table. This is how many comparisons are required *before* the key is
  255. // located, or the *failed* comparisons. We always have to do one successful
  256. // comparison at the end. This successful comparison isn't counted because
  257. // that focuses this metric on the overhead the table is introducing, and
  258. // keeps a "perfect" table with an average of `0.0` here similar to the
  259. // perfect average of `0.0` average probe distance.
  260. double probe_avg_compares = 0.0;
  261. // The maximum number of probing comparisons required to locate a specific
  262. // key in the table.
  263. ssize_t probe_max_compares = 0;
  264. };
  265. // A placeholder empty type used to model pointers to the allocated buffer of
  266. // storage.
  267. //
  268. // The allocated storage doesn't have a meaningful static layout -- it consists
  269. // of an array of metadata groups followed by an array of storage entries.
  270. // However, we want to be able to mark pointers to this and so use pointers to
  271. // this placeholder type as that signifier.
  272. //
  273. // This is a complete, empty type so that it can be used as a base class of a
  274. // specific concrete storage type for compile-time sized storage.
  275. struct Storage {};
  276. // Forward declaration to support friending, see the definition below.
  277. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  278. class BaseImpl;
  279. // Implementation helper for defining a read-only view type for a hashtable.
  280. //
  281. // A specific user-facing hashtable view type should derive privately from this
  282. // type, and forward the implementation of its interface to functions in this
  283. // type.
  284. //
  285. // The methods available to user-facing hashtable types are `protected`, and
  286. // where they are expected to directly map to a public API, named with an
  287. // `Impl`. The suffix naming ensures types don't `using` in these low-level APIs
  288. // but declare their own and implement them by forwarding to these APIs. We
  289. // don't want users to have to read these implementation details to understand
  290. // their container's API, so none of these methods should be `using`-ed into the
  291. // user facing types.
  292. //
  293. // Some of the types are just convenience aliases and aren't important to
  294. // surface as part of the user-facing type API for readers and so those are
  295. // reasonable to add via a `using`.
  296. //
  297. // Some methods are used by other parts of the raw hashtable implementation.
  298. // Those are kept `private` and where necessary the other components of the raw
  299. // hashtable implementation are friended to give access to them.
  300. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  301. class ViewImpl {
  302. protected:
  303. using KeyT = InputKeyT;
  304. using ValueT = InputValueT;
  305. using KeyContextT = InputKeyContextT;
  306. using EntryT = StorageEntry<KeyT, ValueT>;
  307. using MetricsT = Metrics;
  308. friend class BaseImpl<KeyT, ValueT, KeyContextT>;
  309. template <typename InputBaseT, ssize_t SmallSize>
  310. friend class TableImpl;
  311. // Make more-`const` types friends to enable conversions that add `const`.
  312. friend class ViewImpl<const KeyT, ValueT, KeyContextT>;
  313. friend class ViewImpl<KeyT, const ValueT, KeyContextT>;
  314. friend class ViewImpl<const KeyT, const ValueT, KeyContextT>;
  315. ViewImpl() = default;
  316. // Support adding `const` to either key or value type of some other view.
  317. template <typename OtherKeyT, typename OtherValueT>
  318. // NOLINTNEXTLINE(google-explicit-constructor)
  319. ViewImpl(ViewImpl<OtherKeyT, OtherValueT, KeyContextT> other_view)
  320. requires(std::same_as<KeyT, OtherKeyT> ||
  321. std::same_as<KeyT, const OtherKeyT>) &&
  322. (std::same_as<ValueT, OtherValueT> ||
  323. std::same_as<ValueT, const OtherValueT>)
  324. : alloc_size_(other_view.alloc_size_), storage_(other_view.storage_) {}
  325. // Looks up an entry in the hashtable and returns its address or null if not
  326. // present.
  327. template <typename LookupKeyT>
  328. auto LookupEntry(LookupKeyT lookup_key, KeyContextT key_context) const
  329. -> EntryT*;
  330. // Calls `entry_callback` for each entry in the hashtable. All the entries
  331. // within a specific group are visited first, and then `group_callback` is
  332. // called on the group itself. The `group_callback` is typically only used by
  333. // the internals of the hashtable.
  334. template <typename EntryCallbackT, typename GroupCallbackT>
  335. auto ForEachEntry(EntryCallbackT entry_callback,
  336. GroupCallbackT group_callback) const -> void;
  337. // Returns a collection of informative metrics on the the current state of the
  338. // table, useful for performance analysis. These include relatively slow to
  339. // compute metrics requiring deep inspection of the table's state.
  340. auto ComputeMetricsImpl(KeyContextT key_context) const -> MetricsT;
  341. private:
  342. ViewImpl(ssize_t alloc_size, Storage* storage)
  343. : alloc_size_(alloc_size), storage_(storage) {}
  344. // Computes the offset from the metadata array to the entries array for a
  345. // given size. This is trivial, but we use this routine to enforce invariants
  346. // on the sizes.
  347. static constexpr auto EntriesOffset(ssize_t alloc_size) -> ssize_t {
  348. CARBON_DCHECK(llvm::isPowerOf2_64(alloc_size),
  349. "Size must be a power of two for a hashed buffer!");
  350. // The size is always a power of two. We prevent any too-small sizes so it
  351. // being a power of two provides the needed alignment. As a result, the
  352. // offset is exactly the size. We validate this here to catch alignment bugs
  353. // early.
  354. CARBON_DCHECK(static_cast<uint64_t>(alloc_size) ==
  355. llvm::alignTo<alignof(EntryT)>(alloc_size));
  356. return alloc_size;
  357. }
  358. // Compute the allocated table's byte size.
  359. static constexpr auto AllocByteSize(ssize_t alloc_size) -> ssize_t {
  360. return EntriesOffset(alloc_size) + sizeof(EntryT) * alloc_size;
  361. }
  362. auto metadata() const -> uint8_t* {
  363. return reinterpret_cast<uint8_t*>(storage_);
  364. }
  365. auto entries() const -> EntryT* {
  366. return reinterpret_cast<EntryT*>(reinterpret_cast<std::byte*>(storage_) +
  367. EntriesOffset(alloc_size_));
  368. }
  369. ssize_t alloc_size_;
  370. Storage* storage_;
  371. };
  372. // Implementation helper for defining a read-write base type for a hashtable
  373. // that type-erases any SSO buffer.
  374. //
  375. // A specific user-facing hashtable base type should derive using *`protected`*
  376. // inheritance from this type, and forward the implementation of its interface
  377. // to functions in this type.
  378. //
  379. // Other than the use of `protected` inheritance, the patterns for this type,
  380. // and how to build user-facing hashtable base types from it, mirror those of
  381. // `ViewImpl`. See its documentation for more details.
  382. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  383. class BaseImpl {
  384. protected:
  385. using KeyT = InputKeyT;
  386. using ValueT = InputValueT;
  387. using KeyContextT = InputKeyContextT;
  388. using ViewImplT = ViewImpl<KeyT, ValueT, KeyContextT>;
  389. using EntryT = typename ViewImplT::EntryT;
  390. using MetricsT = typename ViewImplT::MetricsT;
  391. BaseImpl(int small_alloc_size, Storage* small_storage)
  392. : small_alloc_size_(small_alloc_size) {
  393. CARBON_CHECK(small_alloc_size >= 0);
  394. Construct(small_storage);
  395. }
  396. // Only used for copying and moving, and leaves storage uninitialized.
  397. BaseImpl(ssize_t alloc_size, int growth_budget, int small_alloc_size)
  398. : view_impl_(alloc_size, nullptr),
  399. growth_budget_(growth_budget),
  400. small_alloc_size_(small_alloc_size) {}
  401. // Destruction must be handled by the table where it can destroy entries in
  402. // any small buffer, so make the base destructor protected but defaulted here.
  403. ~BaseImpl() = default;
  404. // NOLINTNEXTLINE(google-explicit-constructor): Designed to implicitly decay.
  405. operator ViewImplT() const { return view_impl(); }
  406. auto view_impl() const -> ViewImplT { return view_impl_; }
  407. // Looks up the provided key in the hashtable. If found, returns a pointer to
  408. // that entry and `false`.
  409. //
  410. // If not found, will locate an empty entry for inserting into, set the
  411. // metadata for that entry, and return a pointer to the entry and `true`. When
  412. // necessary, this will grow the hashtable to cause there to be sufficient
  413. // empty entries.
  414. template <typename LookupKeyT>
  415. auto InsertImpl(LookupKeyT lookup_key, KeyContextT key_context)
  416. -> std::pair<EntryT*, bool>;
  417. // Grow the table to specific allocation size.
  418. //
  419. // This will grow the the table if necessary for it to have an allocation size
  420. // of `target_alloc_size` which must be a power of two. Note that this will
  421. // not allow that many keys to be inserted into the hashtable, but a smaller
  422. // number based on the load factor. If a specific number of insertions need to
  423. // be achieved without triggering growth, use the `GrowForInsertCountImpl`
  424. // method.
  425. auto GrowToAllocSizeImpl(ssize_t target_alloc_size, KeyContextT key_context)
  426. -> void;
  427. // Grow the table to allow inserting the specified number of keys.
  428. auto GrowForInsertCountImpl(ssize_t count, KeyContextT key_context) -> void;
  429. // Looks up the entry in the hashtable, and if found destroys the entry and
  430. // returns `true`. If not found, returns `false`.
  431. //
  432. // Does not release any memory, just leaves a tombstone behind so this entry
  433. // cannot be found and the slot can in theory be re-used.
  434. template <typename LookupKeyT>
  435. auto EraseImpl(LookupKeyT lookup_key, KeyContextT key_context) -> bool;
  436. // Erases all entries in the hashtable but leaves the allocated storage.
  437. auto ClearImpl() -> void;
  438. private:
  439. template <typename InputBaseT, ssize_t SmallSize>
  440. friend class TableImpl;
  441. static constexpr ssize_t Alignment = std::max<ssize_t>(
  442. {alignof(MetadataGroup), alignof(StorageEntry<KeyT, ValueT>)});
  443. // Implementation of inline small storage for the provided key type, value
  444. // type, and small size. Specialized for a zero small size to be an empty
  445. // struct.
  446. template <ssize_t SmallSize>
  447. struct SmallStorage : Storage {
  448. alignas(Alignment) uint8_t metadata[SmallSize];
  449. mutable StorageEntry<KeyT, ValueT> entries[SmallSize];
  450. };
  451. // Specialized storage with no inline buffer to avoid any extra alignment.
  452. template <>
  453. struct SmallStorage<0> {};
  454. static auto Allocate(ssize_t alloc_size) -> Storage*;
  455. static auto Deallocate(Storage* storage, ssize_t alloc_size) -> void;
  456. auto growth_budget() const -> ssize_t { return growth_budget_; }
  457. auto alloc_size() const -> ssize_t { return view_impl_.alloc_size_; }
  458. auto alloc_size() -> ssize_t& { return view_impl_.alloc_size_; }
  459. auto storage() const -> Storage* { return view_impl_.storage_; }
  460. auto storage() -> Storage*& { return view_impl_.storage_; }
  461. auto metadata() const -> uint8_t* { return view_impl_.metadata(); }
  462. auto entries() const -> EntryT* { return view_impl_.entries(); }
  463. auto small_alloc_size() const -> ssize_t {
  464. return static_cast<unsigned>(small_alloc_size_);
  465. }
  466. auto is_small() const -> bool {
  467. CARBON_DCHECK(alloc_size() >= small_alloc_size());
  468. return alloc_size() == small_alloc_size();
  469. }
  470. auto Construct(Storage* small_storage) -> void;
  471. auto Destroy() -> void;
  472. auto CopySlotsFrom(const BaseImpl& arg) -> void;
  473. auto MoveFrom(BaseImpl&& arg, Storage* small_storage) -> void;
  474. template <typename LookupKeyT>
  475. auto InsertIntoEmpty(LookupKeyT lookup_key, KeyContextT key_context)
  476. -> EntryT*;
  477. static auto ComputeNextAllocSize(ssize_t old_alloc_size) -> ssize_t;
  478. static auto GrowthThresholdForAllocSize(ssize_t alloc_size) -> ssize_t;
  479. auto GrowToNextAllocSize(KeyContextT key_context) -> void;
  480. template <typename LookupKeyT>
  481. auto GrowAndInsert(LookupKeyT lookup_key, KeyContextT key_context) -> EntryT*;
  482. ViewImplT view_impl_;
  483. int growth_budget_;
  484. int small_alloc_size_;
  485. };
  486. // Implementation helper for defining a hashtable type with an SSO buffer.
  487. //
  488. // A specific user-facing hashtable should derive privately from this
  489. // type, and forward the implementation of its interface to functions in this
  490. // type. It should provide the corresponding user-facing hashtable base type as
  491. // the `InputBaseT` type parameter (rather than a key/value pair), and this type
  492. // will in turn derive from that provided base type. This allows derived-to-base
  493. // conversion from the user-facing hashtable type to the user-facing hashtable
  494. // base type. And it does so keeping the inheritance linear. The resulting
  495. // linear inheritance hierarchy for a `Map<K, T>` type will look like:
  496. //
  497. // Map<K, T>
  498. // ↓
  499. // TableImpl<MapBase<K, T>>
  500. // ↓
  501. // MapBase<K, T>
  502. // ↓
  503. // BaseImpl<K, T>
  504. //
  505. // Other than this inheritance technique, the patterns for this type, and how to
  506. // build user-facing hashtable types from it, mirror those of `ViewImpl`. See
  507. // its documentation for more details.
  508. template <typename InputBaseT, ssize_t SmallSize>
  509. class TableImpl : public InputBaseT {
  510. protected:
  511. using BaseT = InputBaseT;
  512. TableImpl() : BaseT(SmallSize, small_storage()) {}
  513. TableImpl(const TableImpl& arg);
  514. TableImpl(TableImpl&& arg) noexcept;
  515. auto operator=(const TableImpl& arg) -> TableImpl&;
  516. auto operator=(TableImpl&& arg) noexcept -> TableImpl&;
  517. ~TableImpl();
  518. // Resets the hashtable to its initial state, clearing all entries and
  519. // releasing all memory. If the hashtable had an SSO buffer, that is restored
  520. // as the storage. Otherwise, a minimum sized table storage is allocated.
  521. auto ResetImpl() -> void;
  522. private:
  523. using KeyT = BaseT::KeyT;
  524. using ValueT = BaseT::ValueT;
  525. using EntryT = BaseT::EntryT;
  526. using SmallStorage = BaseT::template SmallStorage<SmallSize>;
  527. auto small_storage() const -> Storage*;
  528. auto SetUpStorage() -> void;
  529. [[no_unique_address]] mutable SmallStorage small_storage_;
  530. };
  531. ////////////////////////////////////////////////////////////////////////////////
  532. //
  533. // Only implementation details below this point.
  534. //
  535. ////////////////////////////////////////////////////////////////////////////////
  536. // Computes a seed that provides a small amount of entropy from ASLR where
  537. // available with minimal cost. The priority is speed, and this computes the
  538. // entropy in a way that doesn't require loading from memory, merely accessing
  539. // entropy already available without accessing memory.
  540. inline auto ComputeSeed() -> uint64_t {
  541. // A global variable whose address is used as a seed. This allows ASLR to
  542. // introduce some variation in hashtable ordering when enabled via the code
  543. // model for globals.
  544. extern volatile std::byte global_addr_seed;
  545. return reinterpret_cast<uint64_t>(&global_addr_seed);
  546. }
  547. inline auto ComputeProbeMaskFromSize(ssize_t size) -> size_t {
  548. CARBON_DCHECK(llvm::isPowerOf2_64(size),
  549. "Size must be a power of two for a hashed buffer!");
  550. // Since `size` is a power of two, we can make sure the probes are less
  551. // than `size` by making the mask `size - 1`. We also mask off the low
  552. // bits so the probes are a multiple of the size of the groups of entries.
  553. return (size - 1) & ~GroupMask;
  554. }
  555. // This class handles building a sequence of probe indices from a given
  556. // starting point, including both the quadratic growth and masking the index
  557. // to stay within the bucket array size. The starting point doesn't need to be
  558. // clamped to the size ahead of time (or even be positive), we will do it
  559. // internally.
  560. //
  561. // For reference on quadratic probing:
  562. // https://en.wikipedia.org/wiki/Quadratic_probing
  563. //
  564. // We compute the quadratic probe index incrementally, but we can also compute
  565. // it mathematically and will check that the incremental result matches our
  566. // mathematical expectation. We use the quadratic probing formula of:
  567. //
  568. // p(start, step) = (start + (step + step^2) / 2) (mod size / GroupSize)
  569. //
  570. // However, we compute it incrementally and scale all the variables by the group
  571. // size so it can be used as an index without an additional multiplication.
  572. class ProbeSequence {
  573. public:
  574. ProbeSequence(ssize_t start, ssize_t size) {
  575. mask_ = ComputeProbeMaskFromSize(size);
  576. p_ = start & mask_;
  577. #ifndef NDEBUG
  578. start_ = start & mask_;
  579. size_ = size;
  580. #endif
  581. }
  582. void Next() {
  583. step_ += GroupSize;
  584. p_ = (p_ + step_) & mask_;
  585. #ifndef NDEBUG
  586. // Verify against the quadratic formula we expect to be following by scaling
  587. // everything down by `GroupSize`.
  588. CARBON_DCHECK(
  589. (p_ / GroupSize) ==
  590. ((start_ / GroupSize +
  591. (step_ / GroupSize + (step_ / GroupSize) * (step_ / GroupSize)) /
  592. 2) %
  593. (size_ / GroupSize)),
  594. "Index in probe sequence does not match the expected formula.");
  595. CARBON_DCHECK(step_ < size_,
  596. "We necessarily visit all groups, so we can't have more "
  597. "probe steps than groups.");
  598. #endif
  599. }
  600. auto index() const -> ssize_t { return p_; }
  601. private:
  602. ssize_t step_ = 0;
  603. size_t mask_;
  604. ssize_t p_;
  605. #ifndef NDEBUG
  606. ssize_t start_;
  607. ssize_t size_;
  608. #endif
  609. };
  610. // TODO: Evaluate keeping this outlined to see if macro benchmarks observe the
  611. // same perf hit as micro benchmarks.
  612. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  613. template <typename LookupKeyT>
  614. auto ViewImpl<InputKeyT, InputValueT, InputKeyContextT>::LookupEntry(
  615. LookupKeyT lookup_key, KeyContextT key_context) const -> EntryT* {
  616. // Prefetch with a "low" temporal locality as we're primarily expecting a
  617. // brief use of the storage and then to return to application code.
  618. __builtin_prefetch(storage_, /*read*/ 0, /*low-locality*/ 1);
  619. ssize_t local_size = alloc_size_;
  620. CARBON_DCHECK(local_size > 0);
  621. uint8_t* local_metadata = metadata();
  622. HashCode hash = key_context.HashKey(lookup_key, ComputeSeed());
  623. auto [hash_index, tag] = hash.ExtractIndexAndTag<7>();
  624. EntryT* local_entries = entries();
  625. // Walk through groups of entries using a quadratic probe starting from
  626. // `hash_index`.
  627. ProbeSequence s(hash_index, local_size);
  628. do {
  629. ssize_t group_index = s.index();
  630. // For each group, match the tag against the metadata to extract the
  631. // potentially matching entries within the group.
  632. MetadataGroup g = MetadataGroup::Load(local_metadata, group_index);
  633. auto metadata_matched_range = g.Match(tag);
  634. if (LLVM_LIKELY(metadata_matched_range)) {
  635. // If any entries in this group potentially match based on their metadata,
  636. // walk each candidate and compare its key to see if we have definitively
  637. // found a match.
  638. EntryT* group_entries = &local_entries[group_index];
  639. auto byte_it = metadata_matched_range.begin();
  640. auto byte_end = metadata_matched_range.end();
  641. do {
  642. EntryT* entry = byte_it.index_ptr(group_entries);
  643. if (LLVM_LIKELY(key_context.KeyEq(lookup_key, entry->key()))) {
  644. __builtin_assume(entry != nullptr);
  645. return entry;
  646. }
  647. ++byte_it;
  648. } while (LLVM_UNLIKELY(byte_it != byte_end));
  649. }
  650. // We failed to find a matching entry in this bucket, so check if there are
  651. // empty slots as that indicates we're done probing -- no later probed index
  652. // could have a match.
  653. auto empty_byte_matched_range = g.MatchEmpty();
  654. if (LLVM_LIKELY(empty_byte_matched_range)) {
  655. return nullptr;
  656. }
  657. s.Next();
  658. // We use a weird construct of an "unlikely" condition of `true`. The goal
  659. // is to get the compiler to not prioritize the back edge of the loop for
  660. // code layout, and in at least some tests this seems to be an effective
  661. // construct for achieving this.
  662. } while (LLVM_UNLIKELY(true));
  663. }
  664. // Note that we force inlining here because we expect to be called with lambdas
  665. // that will in turn be inlined to form the loop body. We don't want function
  666. // boundaries within the loop for performance, and recognizing the degree of
  667. // simplification from inlining these callbacks may be difficult to
  668. // automatically recognize.
  669. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  670. template <typename EntryCallbackT, typename GroupCallbackT>
  671. [[clang::always_inline]] auto
  672. ViewImpl<InputKeyT, InputValueT, InputKeyContextT>::ForEachEntry(
  673. EntryCallbackT entry_callback, GroupCallbackT group_callback) const
  674. -> void {
  675. uint8_t* local_metadata = metadata();
  676. EntryT* local_entries = entries();
  677. ssize_t local_size = alloc_size_;
  678. for (ssize_t group_index = 0; group_index < local_size;
  679. group_index += GroupSize) {
  680. auto g = MetadataGroup::Load(local_metadata, group_index);
  681. auto present_matched_range = g.MatchPresent();
  682. if (!present_matched_range) {
  683. continue;
  684. }
  685. for (ssize_t byte_index : present_matched_range) {
  686. entry_callback(local_entries[group_index + byte_index]);
  687. }
  688. group_callback(&local_metadata[group_index]);
  689. }
  690. }
  691. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  692. auto ViewImpl<InputKeyT, InputValueT, InputKeyContextT>::ComputeMetricsImpl(
  693. KeyContextT key_context) const -> Metrics {
  694. uint8_t* local_metadata = metadata();
  695. EntryT* local_entries = entries();
  696. ssize_t local_size = alloc_size_;
  697. Metrics metrics;
  698. // Compute the ones we can directly.
  699. metrics.deleted_count = llvm::count(
  700. llvm::ArrayRef(local_metadata, local_size), MetadataGroup::Deleted);
  701. metrics.storage_bytes = AllocByteSize(local_size);
  702. // We want to process present slots specially to collect metrics on their
  703. // probing behavior.
  704. for (ssize_t group_index = 0; group_index < local_size;
  705. group_index += GroupSize) {
  706. auto g = MetadataGroup::Load(local_metadata, group_index);
  707. auto present_matched_range = g.MatchPresent();
  708. for (ssize_t byte_index : present_matched_range) {
  709. ++metrics.key_count;
  710. ssize_t index = group_index + byte_index;
  711. HashCode hash =
  712. key_context.HashKey(local_entries[index].key(), ComputeSeed());
  713. auto [hash_index, tag] = hash.ExtractIndexAndTag<7>();
  714. ProbeSequence s(hash_index, local_size);
  715. metrics.probed_key_count +=
  716. static_cast<ssize_t>(s.index() != group_index);
  717. // For each probed key, go through the probe sequence to find both the
  718. // probe distance and how many comparisons are required.
  719. ssize_t distance = 0;
  720. ssize_t compares = 0;
  721. for (; s.index() != group_index; s.Next()) {
  722. auto probe_g = MetadataGroup::Load(local_metadata, s.index());
  723. auto probe_matched_range = probe_g.Match(tag);
  724. compares += std::distance(probe_matched_range.begin(),
  725. probe_matched_range.end());
  726. distance += 1;
  727. }
  728. auto probe_g = MetadataGroup::Load(local_metadata, s.index());
  729. auto probe_matched_range = probe_g.Match(tag);
  730. CARBON_CHECK(!probe_matched_range.empty());
  731. for (ssize_t match_index : probe_matched_range) {
  732. if (match_index >= byte_index) {
  733. // Note we only count the compares that will *fail* as part of
  734. // probing. The last successful compare isn't interesting, it is
  735. // always needed.
  736. break;
  737. }
  738. compares += 1;
  739. }
  740. metrics.probe_avg_distance += distance;
  741. metrics.probe_max_distance =
  742. std::max(metrics.probe_max_distance, distance);
  743. metrics.probe_avg_compares += compares;
  744. metrics.probe_max_compares =
  745. std::max(metrics.probe_max_compares, compares);
  746. }
  747. }
  748. if (metrics.key_count > 0) {
  749. metrics.probe_avg_compares /= metrics.key_count;
  750. metrics.probe_avg_distance /= metrics.key_count;
  751. }
  752. return metrics;
  753. }
  754. // TODO: Evaluate whether it is worth forcing this out-of-line given the
  755. // reasonable ABI boundary it forms and large volume of code necessary to
  756. // implement it.
  757. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  758. template <typename LookupKeyT>
  759. auto BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::InsertImpl(
  760. LookupKeyT lookup_key, KeyContextT key_context)
  761. -> std::pair<EntryT*, bool> {
  762. CARBON_DCHECK(alloc_size() > 0);
  763. uint8_t* local_metadata = metadata();
  764. HashCode hash = key_context.HashKey(lookup_key, ComputeSeed());
  765. auto [hash_index, tag] = hash.ExtractIndexAndTag<7>();
  766. // We re-purpose the empty control byte to signal no insert is needed to the
  767. // caller. This is guaranteed to not be a control byte we're inserting.
  768. // constexpr uint8_t NoInsertNeeded = Group::Empty;
  769. ssize_t group_with_deleted_index;
  770. MetadataGroup::MatchIndex deleted_match = {};
  771. EntryT* local_entries = entries();
  772. auto return_insert_at_index = [&](ssize_t index) -> std::pair<EntryT*, bool> {
  773. // We'll need to insert at this index so set the control group byte to the
  774. // proper value.
  775. local_metadata[index] = tag | MetadataGroup::PresentMask;
  776. return {&local_entries[index], true};
  777. };
  778. for (ProbeSequence s(hash_index, alloc_size());; s.Next()) {
  779. ssize_t group_index = s.index();
  780. auto g = MetadataGroup::Load(local_metadata, group_index);
  781. auto control_byte_matched_range = g.Match(tag);
  782. if (control_byte_matched_range) {
  783. EntryT* group_entries = &local_entries[group_index];
  784. auto byte_it = control_byte_matched_range.begin();
  785. auto byte_end = control_byte_matched_range.end();
  786. do {
  787. EntryT* entry = byte_it.index_ptr(group_entries);
  788. if (LLVM_LIKELY(key_context.KeyEq(lookup_key, entry->key()))) {
  789. return {entry, false};
  790. }
  791. ++byte_it;
  792. } while (LLVM_UNLIKELY(byte_it != byte_end));
  793. }
  794. // Track the first group with a deleted entry that we could insert over.
  795. if (!deleted_match) {
  796. deleted_match = g.MatchDeleted();
  797. group_with_deleted_index = group_index;
  798. }
  799. // We failed to find a matching entry in this bucket, so check if there are
  800. // no empty slots. In that case, we'll continue probing.
  801. auto empty_match = g.MatchEmpty();
  802. if (!empty_match) {
  803. continue;
  804. }
  805. // Ok, we've finished probing without finding anything and need to insert
  806. // instead.
  807. // If we found a deleted slot, we don't need the probe sequence to insert
  808. // so just bail. We want to ensure building up a table is fast so we
  809. // de-prioritize this a bit. In practice this doesn't have too much of an
  810. // effect.
  811. if (LLVM_UNLIKELY(deleted_match)) {
  812. return return_insert_at_index(group_with_deleted_index +
  813. deleted_match.index());
  814. }
  815. // We're going to need to grow by inserting into an empty slot. Check that
  816. // we have the budget for that before we compute the exact index of the
  817. // empty slot. Without the growth budget we'll have to completely rehash and
  818. // so we can just bail here.
  819. if (LLVM_UNLIKELY(growth_budget_ == 0)) {
  820. return {GrowAndInsert(lookup_key, key_context), true};
  821. }
  822. --growth_budget_;
  823. CARBON_DCHECK(growth_budget() >= 0,
  824. "Growth budget shouldn't have gone negative!");
  825. return return_insert_at_index(group_index + empty_match.index());
  826. }
  827. CARBON_FATAL(
  828. "We should never finish probing without finding the entry or an empty "
  829. "slot.");
  830. }
  831. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  832. [[clang::noinline]] auto
  833. BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::GrowToAllocSizeImpl(
  834. ssize_t target_alloc_size, KeyContextT key_context) -> void {
  835. CARBON_CHECK(llvm::isPowerOf2_64(target_alloc_size));
  836. if (target_alloc_size <= alloc_size()) {
  837. return;
  838. }
  839. // If this is the next alloc size, we can used our optimized growth strategy.
  840. if (target_alloc_size == ComputeNextAllocSize(alloc_size())) {
  841. GrowToNextAllocSize(key_context);
  842. return;
  843. }
  844. // Create locals for the old state of the table.
  845. ssize_t old_size = alloc_size();
  846. CARBON_DCHECK(old_size > 0);
  847. bool old_small = is_small();
  848. Storage* old_storage = storage();
  849. uint8_t* old_metadata = metadata();
  850. EntryT* old_entries = entries();
  851. // Configure for the new size and allocate the new storage.
  852. alloc_size() = target_alloc_size;
  853. storage() = Allocate(target_alloc_size);
  854. std::memset(metadata(), 0, target_alloc_size);
  855. growth_budget_ = GrowthThresholdForAllocSize(target_alloc_size);
  856. // Just re-insert all the entries. As we're more than doubling the table size,
  857. // we don't bother with fancy optimizations here. Even using `memcpy` for the
  858. // entries seems unlikely to be a significant win given how sparse the
  859. // insertions will end up being.
  860. ssize_t count = 0;
  861. for (ssize_t group_index = 0; group_index < old_size;
  862. group_index += GroupSize) {
  863. auto g = MetadataGroup::Load(old_metadata, group_index);
  864. auto present_matched_range = g.MatchPresent();
  865. for (ssize_t byte_index : present_matched_range) {
  866. ++count;
  867. ssize_t index = group_index + byte_index;
  868. EntryT* new_entry =
  869. InsertIntoEmpty(old_entries[index].key(), key_context);
  870. new_entry->MoveFrom(std::move(old_entries[index]));
  871. }
  872. }
  873. growth_budget_ -= count;
  874. if (!old_small) {
  875. // Old isn't a small buffer, so we need to deallocate it.
  876. Deallocate(old_storage, old_size);
  877. }
  878. }
  879. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  880. auto BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::GrowForInsertCountImpl(
  881. ssize_t count, KeyContextT key_context) -> void {
  882. if (count < growth_budget_) {
  883. // Already space for the needed growth.
  884. return;
  885. }
  886. // Currently, we don't account for any tombstones marking deleted elements,
  887. // and just conservatively ensure the growth will create adequate growth
  888. // budget for insertions. We could make this more precise by instead walking
  889. // the table and only counting present slots, as once we grow we'll be able to
  890. // reclaim all of the deleted slots. But this adds complexity and it isn't
  891. // clear this is necessary so we do the simpler conservative thing.
  892. ssize_t used_budget =
  893. GrowthThresholdForAllocSize(alloc_size()) - growth_budget_;
  894. ssize_t budget_needed = used_budget + count;
  895. ssize_t space_needed = budget_needed + (budget_needed / 7);
  896. ssize_t target_alloc_size = llvm::NextPowerOf2(space_needed);
  897. CARBON_CHECK(GrowthThresholdForAllocSize(target_alloc_size) >
  898. (budget_needed));
  899. GrowToAllocSizeImpl(target_alloc_size, key_context);
  900. }
  901. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  902. template <typename LookupKeyT>
  903. auto BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::EraseImpl(
  904. LookupKeyT lookup_key, KeyContextT key_context) -> bool {
  905. EntryT* entry = view_impl_.LookupEntry(lookup_key, key_context);
  906. if (!entry) {
  907. return false;
  908. }
  909. // If there are empty slots in this group then nothing will probe past this
  910. // group looking for an entry so we can simply set this slot to empty as
  911. // well. However, if every slot in this group is full, it might be part of
  912. // a long probe chain that we can't disrupt. In that case we mark the slot's
  913. // metadata as deleted to keep probes continuing past it.
  914. //
  915. // If we mark the slot as empty, we'll also need to increase the growth
  916. // budget.
  917. uint8_t* local_metadata = metadata();
  918. EntryT* local_entries = entries();
  919. ssize_t index = entry - local_entries;
  920. ssize_t group_index = index & ~GroupMask;
  921. auto g = MetadataGroup::Load(local_metadata, group_index);
  922. auto empty_matched_range = g.MatchEmpty();
  923. if (empty_matched_range) {
  924. local_metadata[index] = MetadataGroup::Empty;
  925. ++growth_budget_;
  926. } else {
  927. local_metadata[index] = MetadataGroup::Deleted;
  928. }
  929. if constexpr (!EntryT::IsTriviallyDestructible) {
  930. entry->Destroy();
  931. }
  932. return true;
  933. }
  934. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  935. auto BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::ClearImpl() -> void {
  936. view_impl_.ForEachEntry(
  937. [](EntryT& entry) {
  938. if constexpr (!EntryT::IsTriviallyDestructible) {
  939. entry.Destroy();
  940. }
  941. },
  942. [](uint8_t* metadata_group) {
  943. // Clear the group.
  944. std::memset(metadata_group, 0, GroupSize);
  945. });
  946. growth_budget_ = GrowthThresholdForAllocSize(alloc_size());
  947. }
  948. // Allocates the appropriate memory layout for a table of the given
  949. // `alloc_size`, with space both for the metadata array and entries.
  950. //
  951. // The returned pointer *must* be deallocated by calling the below `Deallocate`
  952. // function with the same `alloc_size` as used here.
  953. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  954. auto BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::Allocate(
  955. ssize_t alloc_size) -> Storage* {
  956. return reinterpret_cast<Storage*>(__builtin_operator_new(
  957. ViewImplT::AllocByteSize(alloc_size),
  958. static_cast<std::align_val_t>(Alignment), std::nothrow_t()));
  959. }
  960. // Deallocates a table's storage that was allocated with the `Allocate`
  961. // function.
  962. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  963. auto BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::Deallocate(
  964. Storage* storage, ssize_t alloc_size) -> void {
  965. ssize_t allocated_size = ViewImplT::AllocByteSize(alloc_size);
  966. // We don't need the size, but make sure it always compiles.
  967. static_cast<void>(allocated_size);
  968. __builtin_operator_delete(storage,
  969. #if __cpp_sized_deallocation
  970. allocated_size,
  971. #endif
  972. static_cast<std::align_val_t>(Alignment));
  973. }
  974. // Construct a table using the provided small storage if `small_alloc_size_` is
  975. // non-zero. If `small_alloc_size_` is zero, then `small_storage` won't be used
  976. // and can be null. Regardless, after this the storage pointer is non-null and
  977. // the size is non-zero so that we can directly begin inserting or querying the
  978. // table.
  979. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  980. auto BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::Construct(
  981. Storage* small_storage) -> void {
  982. if (small_alloc_size_ > 0) {
  983. alloc_size() = small_alloc_size_;
  984. storage() = small_storage;
  985. } else {
  986. // Directly allocate the initial buffer so that the hashtable is never in
  987. // an empty state.
  988. alloc_size() = MinAllocatedSize;
  989. storage() = Allocate(MinAllocatedSize);
  990. }
  991. std::memset(metadata(), 0, alloc_size());
  992. growth_budget_ = GrowthThresholdForAllocSize(alloc_size());
  993. }
  994. // Destroy the current table, releasing any memory used.
  995. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  996. auto BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::Destroy() -> void {
  997. // Check for a moved-from state and don't do anything. Only a moved-from table
  998. // has a zero size.
  999. if (alloc_size() == 0) {
  1000. return;
  1001. }
  1002. // Destroy all the entries.
  1003. if constexpr (!EntryT::IsTriviallyDestructible) {
  1004. view_impl_.ForEachEntry([](EntryT& entry) { entry.Destroy(); },
  1005. [](auto...) {});
  1006. }
  1007. // If small, nothing to deallocate.
  1008. if (is_small()) {
  1009. return;
  1010. }
  1011. // Just deallocate the storage without updating anything when destroying the
  1012. // object.
  1013. Deallocate(storage(), alloc_size());
  1014. }
  1015. // Copy all of the slots over from another table that is exactly the same
  1016. // allocation size.
  1017. //
  1018. // This requires the current table to already have storage allocated and set up
  1019. // but not initialized (or already cleared). It directly overwrites the storage
  1020. // allocation of the table to match the incoming argument.
  1021. //
  1022. // Despite being used in construction, this shouldn't be called for a moved-from
  1023. // `arg` -- in practice it is better for callers to handle this when setting up
  1024. // storage.
  1025. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  1026. auto BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::CopySlotsFrom(
  1027. const BaseImpl& arg) -> void {
  1028. CARBON_DCHECK(alloc_size() == arg.alloc_size());
  1029. ssize_t local_size = alloc_size();
  1030. // Preserve which slot every entry is in, including tombstones in the
  1031. // metadata, in order to copy into the new table's storage without rehashing
  1032. // all of the keys. This is especially important as we don't have an easy way
  1033. // to access the key context needed for rehashing here.
  1034. uint8_t* local_metadata = metadata();
  1035. EntryT* local_entries = entries();
  1036. const uint8_t* local_arg_metadata = arg.metadata();
  1037. const EntryT* local_arg_entries = arg.entries();
  1038. memcpy(local_metadata, local_arg_metadata, local_size);
  1039. for (ssize_t group_index = 0; group_index < local_size;
  1040. group_index += GroupSize) {
  1041. auto g = MetadataGroup::Load(local_arg_metadata, group_index);
  1042. for (ssize_t byte_index : g.MatchPresent()) {
  1043. local_entries[group_index + byte_index].CopyFrom(
  1044. local_arg_entries[group_index + byte_index]);
  1045. }
  1046. }
  1047. }
  1048. // Move from another table to this one.
  1049. //
  1050. // Note that the `small_storage` is *this* table's small storage pointer,
  1051. // provided from the `TableImpl` to this `BaseImpl` method as an argument.
  1052. //
  1053. // Requires the table to have size and growth already set up but otherwise the
  1054. // the table has not yet been initialized. Notably, storage should either not
  1055. // yet be constructed or already destroyed. It both sets up the storage and
  1056. // handles any moving slots needed.
  1057. //
  1058. // Note that because this is used in construction it needs to handle a
  1059. // moved-from `arg`.
  1060. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  1061. auto BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::MoveFrom(
  1062. BaseImpl&& arg, Storage* small_storage) -> void {
  1063. ssize_t local_size = alloc_size();
  1064. CARBON_DCHECK(local_size == arg.alloc_size());
  1065. // If `arg` is moved-from, skip the rest as the local size is all we need.
  1066. if (local_size == 0) {
  1067. return;
  1068. }
  1069. if (arg.is_small()) {
  1070. CARBON_DCHECK(local_size == small_alloc_size_);
  1071. this->storage() = small_storage;
  1072. // For small tables, we have to move the entries as we can't move the tables
  1073. // themselves. We do this preserving their slots and even tombstones to
  1074. // avoid rehashing.
  1075. uint8_t* local_metadata = this->metadata();
  1076. EntryT* local_entries = this->entries();
  1077. uint8_t* local_arg_metadata = arg.metadata();
  1078. EntryT* local_arg_entries = arg.entries();
  1079. memcpy(local_metadata, local_arg_metadata, local_size);
  1080. if (EntryT::IsTriviallyRelocatable) {
  1081. memcpy(local_entries, local_arg_entries, local_size * sizeof(EntryT));
  1082. } else {
  1083. for (ssize_t group_index = 0; group_index < local_size;
  1084. group_index += GroupSize) {
  1085. auto g = MetadataGroup::Load(local_arg_metadata, group_index);
  1086. for (ssize_t byte_index : g.MatchPresent()) {
  1087. local_entries[group_index + byte_index].MoveFrom(
  1088. std::move(local_arg_entries[group_index + byte_index]));
  1089. }
  1090. }
  1091. }
  1092. } else {
  1093. // Just point to the allocated storage.
  1094. storage() = arg.storage();
  1095. }
  1096. // Finally, put the incoming table into a moved-from state.
  1097. arg.alloc_size() = 0;
  1098. // Replace the pointer with null to ease debugging.
  1099. arg.storage() = nullptr;
  1100. }
  1101. // Optimized routine to insert a key into a table when that key *definitely*
  1102. // isn't present in the table and the table *definitely* has a viable empty slot
  1103. // (and growth space) to insert into before any deleted slots. When both of
  1104. // these are true, typically just after growth, we can dramatically simplify the
  1105. // insert position search.
  1106. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  1107. template <typename LookupKeyT>
  1108. [[clang::noinline]] auto
  1109. BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::InsertIntoEmpty(
  1110. LookupKeyT lookup_key, KeyContextT key_context) -> EntryT* {
  1111. HashCode hash = key_context.HashKey(lookup_key, ComputeSeed());
  1112. auto [hash_index, tag] = hash.ExtractIndexAndTag<7>();
  1113. uint8_t* local_metadata = metadata();
  1114. EntryT* local_entries = entries();
  1115. for (ProbeSequence s(hash_index, alloc_size());; s.Next()) {
  1116. ssize_t group_index = s.index();
  1117. auto g = MetadataGroup::Load(local_metadata, group_index);
  1118. if (auto empty_match = g.MatchEmpty()) {
  1119. ssize_t index = group_index + empty_match.index();
  1120. local_metadata[index] = tag | MetadataGroup::PresentMask;
  1121. return &local_entries[index];
  1122. }
  1123. // Otherwise we continue probing.
  1124. }
  1125. }
  1126. // Apply our doubling growth strategy and (re-)check invariants around table
  1127. // size.
  1128. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  1129. auto BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::ComputeNextAllocSize(
  1130. ssize_t old_alloc_size) -> ssize_t {
  1131. CARBON_DCHECK(llvm::isPowerOf2_64(old_alloc_size),
  1132. "Expected a power of two!");
  1133. ssize_t new_alloc_size;
  1134. bool overflow = __builtin_mul_overflow(old_alloc_size, 2, &new_alloc_size);
  1135. CARBON_CHECK(!overflow, "Computing the new size overflowed `ssize_t`!");
  1136. return new_alloc_size;
  1137. }
  1138. // Compute the growth threshold for a given size.
  1139. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  1140. auto BaseImpl<InputKeyT, InputValueT,
  1141. InputKeyContextT>::GrowthThresholdForAllocSize(ssize_t alloc_size)
  1142. -> ssize_t {
  1143. // We use a 7/8ths load factor to trigger growth.
  1144. return alloc_size - alloc_size / 8;
  1145. }
  1146. // Optimized routine for growing to the next alloc size.
  1147. //
  1148. // A particularly common and important-to-optimize path is growing to the next
  1149. // alloc size, which will always be a doubling of the allocated size. This
  1150. // allows an important optimization -- we're adding exactly one more high bit to
  1151. // the hash-computed index for each entry. This in turn means we can classify
  1152. // every entry in the table into three cases:
  1153. //
  1154. // 1) The new high bit is zero, the entry is at the same index in the new
  1155. // table as the old.
  1156. //
  1157. // 2) The new high bit is one, the entry is at the old index plus the old
  1158. // size.
  1159. //
  1160. // 3) The entry's current index doesn't match the initial hash index because
  1161. // it required some amount of probing to find an empty slot.
  1162. //
  1163. // The design of the hash table tries to minimize how many entries fall into
  1164. // case (3), so we expect the vast majority of entries to be in (1) or (2). This
  1165. // lets us model growth notionally as copying the hashtable twice into the lower
  1166. // and higher halves of the new allocation, clearing out the now-empty slots
  1167. // (from both deleted entries and entries in the other half of the table after
  1168. // growth), and inserting any probed elements. That model in turn is much more
  1169. // efficient than re-inserting all of the elements as it avoids the unnecessary
  1170. // parts of insertion and avoids interleaving random accesses for the probed
  1171. // elements. But most importantly, for trivially relocatable types it allows us
  1172. // to use `memcpy` rather than moving the elements individually.
  1173. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  1174. auto BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::GrowToNextAllocSize(
  1175. KeyContextT key_context) -> void {
  1176. // We collect the probed elements in a small vector for re-insertion. It is
  1177. // tempting to reuse the already allocated storage, but doing so appears to
  1178. // be a (very slight) performance regression. These are relatively rare and
  1179. // storing them into the existing storage creates stores to the same regions
  1180. // of memory we're reading. Moreover, it requires moving both the key and the
  1181. // value twice, and doing the `memcpy` widening for relocatable types before
  1182. // the group walk rather than after the group walk. In practice, between the
  1183. // statistical rareness and using a large small size buffer here on the stack,
  1184. // we can handle this most efficiently with temporary, additional storage.
  1185. llvm::SmallVector<ssize_t, 128> probed_indices;
  1186. // Create locals for the old state of the table.
  1187. ssize_t old_size = alloc_size();
  1188. CARBON_DCHECK(old_size > 0);
  1189. bool old_small = is_small();
  1190. Storage* old_storage = storage();
  1191. uint8_t* old_metadata = metadata();
  1192. EntryT* old_entries = entries();
  1193. #ifndef NDEBUG
  1194. // Count how many of the old table slots will end up being empty after we grow
  1195. // the table. This is both the currently empty slots, but also the deleted
  1196. // slots because we clear them to empty and re-insert everything that had any
  1197. // probing.
  1198. ssize_t debug_empty_count =
  1199. llvm::count(llvm::ArrayRef(old_metadata, old_size), MetadataGroup::Empty);
  1200. ssize_t debug_deleted_count = llvm::count(
  1201. llvm::ArrayRef(old_metadata, old_size), MetadataGroup::Deleted);
  1202. CARBON_DCHECK(
  1203. debug_empty_count >= (old_size - GrowthThresholdForAllocSize(old_size)),
  1204. "debug_empty_count: {0}, debug_deleted_count: {1}, size: {2}",
  1205. debug_empty_count, debug_deleted_count, old_size);
  1206. #endif
  1207. // Configure for the new size and allocate the new storage.
  1208. ssize_t new_size = ComputeNextAllocSize(old_size);
  1209. alloc_size() = new_size;
  1210. storage() = Allocate(new_size);
  1211. growth_budget_ = GrowthThresholdForAllocSize(new_size);
  1212. // Now extract the new components of the table.
  1213. uint8_t* new_metadata = metadata();
  1214. EntryT* new_entries = entries();
  1215. // Walk the metadata groups, clearing deleted to empty, duplicating the
  1216. // metadata for the low and high halves, and updating it based on where each
  1217. // entry will go in the new table. The updated metadata group is written to
  1218. // the new table, and for non-trivially relocatable entry types, the entry is
  1219. // also moved to its new location.
  1220. ssize_t count = 0;
  1221. for (ssize_t group_index = 0; group_index < old_size;
  1222. group_index += GroupSize) {
  1223. auto low_g = MetadataGroup::Load(old_metadata, group_index);
  1224. // Make sure to match present elements first to enable pipelining with
  1225. // clearing.
  1226. auto present_matched_range = low_g.MatchPresent();
  1227. low_g.ClearDeleted();
  1228. MetadataGroup high_g;
  1229. if constexpr (MetadataGroup::FastByteClear) {
  1230. // When we have a fast byte clear, we can update the metadata for the
  1231. // growth in-register and store at the end.
  1232. high_g = low_g;
  1233. } else {
  1234. // If we don't have a fast byte clear, we can store the metadata group
  1235. // eagerly here and overwrite bytes with a byte store below instead of
  1236. // clearing the byte in-register.
  1237. low_g.Store(new_metadata, group_index);
  1238. low_g.Store(new_metadata, group_index | old_size);
  1239. }
  1240. for (ssize_t byte_index : present_matched_range) {
  1241. ++count;
  1242. ssize_t old_index = group_index + byte_index;
  1243. if constexpr (!MetadataGroup::FastByteClear) {
  1244. CARBON_DCHECK(new_metadata[old_index] == old_metadata[old_index]);
  1245. CARBON_DCHECK(new_metadata[old_index | old_size] ==
  1246. old_metadata[old_index]);
  1247. }
  1248. HashCode hash =
  1249. key_context.HashKey(old_entries[old_index].key(), ComputeSeed());
  1250. ssize_t old_hash_index = hash.ExtractIndexAndTag<7>().first &
  1251. ComputeProbeMaskFromSize(old_size);
  1252. if (LLVM_UNLIKELY(old_hash_index != group_index)) {
  1253. probed_indices.push_back(old_index);
  1254. if constexpr (MetadataGroup::FastByteClear) {
  1255. low_g.ClearByte(byte_index);
  1256. high_g.ClearByte(byte_index);
  1257. } else {
  1258. new_metadata[old_index] = MetadataGroup::Empty;
  1259. new_metadata[old_index | old_size] = MetadataGroup::Empty;
  1260. }
  1261. continue;
  1262. }
  1263. ssize_t new_index = hash.ExtractIndexAndTag<7>().first &
  1264. ComputeProbeMaskFromSize(new_size);
  1265. CARBON_DCHECK(new_index == old_hash_index ||
  1266. new_index == (old_hash_index | old_size));
  1267. // Toggle the newly added bit of the index to get to the other possible
  1268. // target index.
  1269. if constexpr (MetadataGroup::FastByteClear) {
  1270. (new_index == old_hash_index ? high_g : low_g).ClearByte(byte_index);
  1271. new_index += byte_index;
  1272. } else {
  1273. new_index += byte_index;
  1274. new_metadata[new_index ^ old_size] = MetadataGroup::Empty;
  1275. }
  1276. // If we need to explicitly move (and destroy) the key or value, do so
  1277. // here where we already know its target.
  1278. if constexpr (!EntryT::IsTriviallyRelocatable) {
  1279. new_entries[new_index].MoveFrom(std::move(old_entries[old_index]));
  1280. }
  1281. }
  1282. if constexpr (MetadataGroup::FastByteClear) {
  1283. low_g.Store(new_metadata, group_index);
  1284. high_g.Store(new_metadata, (group_index | old_size));
  1285. }
  1286. }
  1287. CARBON_DCHECK((count - static_cast<ssize_t>(probed_indices.size())) ==
  1288. (new_size - llvm::count(llvm::ArrayRef(new_metadata, new_size),
  1289. MetadataGroup::Empty)));
  1290. #ifndef NDEBUG
  1291. CARBON_DCHECK((debug_empty_count + debug_deleted_count) ==
  1292. (old_size - count));
  1293. CARBON_DCHECK(llvm::count(llvm::ArrayRef(new_metadata, new_size),
  1294. MetadataGroup::Empty) ==
  1295. debug_empty_count + debug_deleted_count +
  1296. static_cast<ssize_t>(probed_indices.size()) + old_size);
  1297. #endif
  1298. // If the keys or values are trivially relocatable, we do a bulk memcpy of
  1299. // them into place. This will copy them into both possible locations, which is
  1300. // fine. One will be empty and clobbered if reused or ignored. The other will
  1301. // be the one used. This might seem like it needs it to be valid for us to
  1302. // create two copies, but it doesn't. This produces the exact same storage as
  1303. // copying the storage into the wrong location first, and then again into the
  1304. // correct location. Only one is live and only one is destroyed.
  1305. if constexpr (EntryT::IsTriviallyRelocatable) {
  1306. memcpy(new_entries, old_entries, old_size * sizeof(EntryT));
  1307. memcpy(new_entries + old_size, old_entries, old_size * sizeof(EntryT));
  1308. }
  1309. // We then need to do a normal insertion for anything that was probed before
  1310. // growth, but we know we'll find an empty slot, so leverage that.
  1311. for (ssize_t old_index : probed_indices) {
  1312. EntryT* new_entry =
  1313. InsertIntoEmpty(old_entries[old_index].key(), key_context);
  1314. new_entry->MoveFrom(std::move(old_entries[old_index]));
  1315. }
  1316. CARBON_DCHECK(count ==
  1317. (new_size - llvm::count(llvm::ArrayRef(new_metadata, new_size),
  1318. MetadataGroup::Empty)));
  1319. growth_budget_ -= count;
  1320. CARBON_DCHECK(growth_budget_ ==
  1321. (GrowthThresholdForAllocSize(new_size) -
  1322. (new_size - llvm::count(llvm::ArrayRef(new_metadata, new_size),
  1323. MetadataGroup::Empty))));
  1324. CARBON_DCHECK(growth_budget_ > 0 &&
  1325. "Must still have a growth budget after rehash!");
  1326. if (!old_small) {
  1327. // Old isn't a small buffer, so we need to deallocate it.
  1328. Deallocate(old_storage, old_size);
  1329. }
  1330. }
  1331. // Grow the hashtable to create space and then insert into it. Returns the
  1332. // selected insertion entry. Never returns null. In addition to growing and
  1333. // selecting the insertion entry, this routine updates the metadata array so
  1334. // that this function can be directly called and the result returned from
  1335. // `InsertImpl`.
  1336. template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
  1337. template <typename LookupKeyT>
  1338. [[clang::noinline]] auto
  1339. BaseImpl<InputKeyT, InputValueT, InputKeyContextT>::GrowAndInsert(
  1340. LookupKeyT lookup_key, KeyContextT key_context) -> EntryT* {
  1341. GrowToNextAllocSize(key_context);
  1342. // And insert the lookup_key into an index in the newly grown map and return
  1343. // that index for use.
  1344. --growth_budget_;
  1345. return InsertIntoEmpty(lookup_key, key_context);
  1346. }
  1347. template <typename InputBaseT, ssize_t SmallSize>
  1348. TableImpl<InputBaseT, SmallSize>::TableImpl(const TableImpl& arg)
  1349. : BaseT(arg.alloc_size(), arg.growth_budget_, SmallSize) {
  1350. // Check for completely broken objects. These invariants should be true even
  1351. // in a moved-from state.
  1352. CARBON_DCHECK(arg.alloc_size() == 0 || !arg.is_small() ||
  1353. arg.alloc_size() == SmallSize);
  1354. CARBON_DCHECK(arg.small_alloc_size_ == SmallSize);
  1355. CARBON_DCHECK(this->small_alloc_size_ == SmallSize);
  1356. if (this->alloc_size() != 0) {
  1357. SetUpStorage();
  1358. this->CopySlotsFrom(arg);
  1359. }
  1360. }
  1361. template <typename InputBaseT, ssize_t SmallSize>
  1362. auto TableImpl<InputBaseT, SmallSize>::operator=(const TableImpl& arg)
  1363. -> TableImpl& {
  1364. // Check for completely broken objects. These invariants should be true even
  1365. // in a moved-from state.
  1366. CARBON_DCHECK(arg.alloc_size() == 0 || !arg.is_small() ||
  1367. arg.alloc_size() == SmallSize);
  1368. CARBON_DCHECK(arg.small_alloc_size_ == SmallSize);
  1369. CARBON_DCHECK(this->small_alloc_size_ == SmallSize);
  1370. // We have to end up with an allocation size exactly equivalent to the
  1371. // incoming argument to avoid re-hashing every entry in the table, which isn't
  1372. // possible without key context.
  1373. if (arg.alloc_size() == this->alloc_size()) {
  1374. // No effective way for self-assignment to fall out of an efficient
  1375. // implementation so detect and bypass here. Similarly, if both are in a
  1376. // moved-from state, there is nothing to do.
  1377. if (&arg == this || this->alloc_size() == 0) {
  1378. return *this;
  1379. }
  1380. CARBON_DCHECK(arg.storage() != this->storage());
  1381. if constexpr (!EntryT::IsTriviallyDestructible) {
  1382. this->view_impl_.ForEachEntry([](EntryT& entry) { entry.Destroy(); },
  1383. [](auto...) {});
  1384. }
  1385. } else {
  1386. // The sizes don't match so destroy everything and re-setup the table
  1387. // storage.
  1388. this->Destroy();
  1389. this->alloc_size() = arg.alloc_size();
  1390. // If `arg` is moved-from, we've clear out our elements and put ourselves
  1391. // into a moved-from state. We're done.
  1392. if (this->alloc_size() == 0) {
  1393. return *this;
  1394. }
  1395. SetUpStorage();
  1396. }
  1397. this->growth_budget_ = arg.growth_budget_;
  1398. this->CopySlotsFrom(arg);
  1399. return *this;
  1400. }
  1401. // Puts the incoming table into a moved-from state that can be destroyed or
  1402. // re-initialized but must not be used otherwise.
  1403. template <typename InputBaseT, ssize_t SmallSize>
  1404. TableImpl<InputBaseT, SmallSize>::TableImpl(TableImpl&& arg) noexcept
  1405. : BaseT(arg.alloc_size(), arg.growth_budget_, SmallSize) {
  1406. // Check for completely broken objects. These invariants should be true even
  1407. // in a moved-from state.
  1408. CARBON_DCHECK(arg.alloc_size() == 0 || !arg.is_small() ||
  1409. arg.alloc_size() == SmallSize);
  1410. CARBON_DCHECK(arg.small_alloc_size_ == SmallSize);
  1411. CARBON_DCHECK(this->small_alloc_size_ == SmallSize);
  1412. this->MoveFrom(std::move(arg), small_storage());
  1413. }
  1414. template <typename InputBaseT, ssize_t SmallSize>
  1415. auto TableImpl<InputBaseT, SmallSize>::operator=(TableImpl&& arg) noexcept
  1416. -> TableImpl& {
  1417. // Check for completely broken objects. These invariants should be true even
  1418. // in a moved-from state.
  1419. CARBON_DCHECK(arg.alloc_size() == 0 || !arg.is_small() ||
  1420. arg.alloc_size() == SmallSize);
  1421. CARBON_DCHECK(arg.small_alloc_size_ == SmallSize);
  1422. CARBON_DCHECK(this->small_alloc_size_ == SmallSize);
  1423. // Destroy and deallocate our table.
  1424. this->Destroy();
  1425. // Defend against self-move by zeroing the size here before we start moving
  1426. // out of `arg`.
  1427. this->alloc_size() = 0;
  1428. // Setup to match argument and then finish the move.
  1429. this->alloc_size() = arg.alloc_size();
  1430. this->growth_budget_ = arg.growth_budget_;
  1431. this->MoveFrom(std::move(arg), small_storage());
  1432. return *this;
  1433. }
  1434. template <typename InputBaseT, ssize_t SmallSize>
  1435. TableImpl<InputBaseT, SmallSize>::~TableImpl() {
  1436. this->Destroy();
  1437. }
  1438. // Reset a table to its original state, including releasing any allocated
  1439. // memory.
  1440. template <typename InputBaseT, ssize_t SmallSize>
  1441. auto TableImpl<InputBaseT, SmallSize>::ResetImpl() -> void {
  1442. this->Destroy();
  1443. // Re-initialize the whole thing.
  1444. CARBON_DCHECK(this->small_alloc_size() == SmallSize);
  1445. this->Construct(small_storage());
  1446. }
  1447. template <typename InputBaseT, ssize_t SmallSize>
  1448. auto TableImpl<InputBaseT, SmallSize>::small_storage() const -> Storage* {
  1449. if constexpr (SmallSize > 0) {
  1450. // Do a bunch of validation of the small size to establish our invariants
  1451. // when we know we have a non-zero small size.
  1452. static_assert(llvm::isPowerOf2_64(SmallSize),
  1453. "SmallSize must be a power of two for a hashed buffer!");
  1454. static_assert(
  1455. SmallSize >= MaxGroupSize,
  1456. "We require all small sizes to multiples of the largest group "
  1457. "size supported to ensure it can be used portably. ");
  1458. static_assert(
  1459. (SmallSize % MaxGroupSize) == 0,
  1460. "Small size must be a multiple of the max group size supported "
  1461. "so that we can allocate a whole number of groups.");
  1462. // Implied by the max asserts above.
  1463. static_assert(SmallSize >= GroupSize);
  1464. static_assert((SmallSize % GroupSize) == 0);
  1465. static_assert(SmallSize >= alignof(StorageEntry<KeyT, ValueT>),
  1466. "Requested a small size that would require padding between "
  1467. "metadata bytes and correctly aligned key and value types. "
  1468. "Either a larger small size or a zero small size and heap "
  1469. "allocation are required for this key and value type.");
  1470. static_assert(offsetof(SmallStorage, entries) == SmallSize,
  1471. "Offset to entries in small size storage doesn't match "
  1472. "computed offset!");
  1473. return &small_storage_;
  1474. } else {
  1475. static_assert(
  1476. sizeof(TableImpl) == sizeof(BaseT),
  1477. "Empty small storage caused a size difference and wasted space!");
  1478. return nullptr;
  1479. }
  1480. }
  1481. // Helper to set up the storage of a table when a specific size has already been
  1482. // set up. If possible, uses any small storage, otherwise allocates.
  1483. template <typename InputBaseT, ssize_t SmallSize>
  1484. auto TableImpl<InputBaseT, SmallSize>::SetUpStorage() -> void {
  1485. CARBON_DCHECK(this->small_alloc_size() == SmallSize);
  1486. ssize_t local_size = this->alloc_size();
  1487. CARBON_DCHECK(local_size != 0);
  1488. if (local_size == SmallSize) {
  1489. this->storage() = small_storage();
  1490. } else {
  1491. this->storage() = BaseT::Allocate(local_size);
  1492. }
  1493. }
  1494. } // namespace Carbon::RawHashtable
  1495. #endif // CARBON_COMMON_RAW_HASHTABLE_H_