value_store.h 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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_TOOLCHAIN_BASE_VALUE_STORE_H_
  5. #define CARBON_TOOLCHAIN_BASE_VALUE_STORE_H_
  6. #include <memory>
  7. #include <type_traits>
  8. #include "common/check.h"
  9. #include "common/hashtable_key_context.h"
  10. #include "common/ostream.h"
  11. #include "common/set.h"
  12. #include "llvm/ADT/STLExtras.h"
  13. #include "llvm/ADT/Sequence.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/ADT/iterator_range.h"
  16. #include "toolchain/base/mem_usage.h"
  17. #include "toolchain/base/yaml.h"
  18. namespace Carbon {
  19. namespace Internal {
  20. // Used as a parent class for non-printable types. This is just for
  21. // std::conditional, not as an API.
  22. class ValueStoreNotPrintable {};
  23. } // namespace Internal
  24. // A simple wrapper for accumulating values, providing IDs to later retrieve the
  25. // value. This does not do deduplication.
  26. //
  27. // IdT::ValueType must represent the type being indexed.
  28. template <typename IdT>
  29. class ValueStore
  30. : public std::conditional<
  31. std::is_base_of_v<Printable<typename IdT::ValueType>,
  32. typename IdT::ValueType>,
  33. Yaml::Printable<ValueStore<IdT>>, Internal::ValueStoreNotPrintable> {
  34. public:
  35. using ValueType = typename IdT::ValueType;
  36. // Typically we want to use `ValueType&` and `const ValueType& to avoid
  37. // copies, but when the value type is a `StringRef`, we assume external
  38. // storage for the string data and both our value type and ref type will be
  39. // `StringRef`. This will preclude mutation of the string data.
  40. using RefType = std::conditional_t<std::same_as<llvm::StringRef, ValueType>,
  41. llvm::StringRef, ValueType&>;
  42. using ConstRefType =
  43. std::conditional_t<std::same_as<llvm::StringRef, ValueType>,
  44. llvm::StringRef, const ValueType&>;
  45. // Stores the value and returns an ID to reference it.
  46. auto Add(ValueType value) -> IdT {
  47. IdT id(values_.size());
  48. // This routine is especially hot and the check here relatively expensive
  49. // for the value provided, so only do this in debug builds to make tracking
  50. // down issues easier.
  51. CARBON_DCHECK(id.index >= 0, "Id overflow");
  52. values_.push_back(std::move(value));
  53. return id;
  54. }
  55. // Returns a mutable value for an ID.
  56. auto Get(IdT id) -> RefType {
  57. CARBON_DCHECK(id.index >= 0, "{0}", id);
  58. return values_[id.index];
  59. }
  60. // Returns the value for an ID.
  61. auto Get(IdT id) const -> ConstRefType {
  62. CARBON_DCHECK(id.index >= 0, "{0}", id);
  63. return values_[id.index];
  64. }
  65. // Reserves space.
  66. auto Reserve(size_t size) -> void { values_.reserve(size); }
  67. // These are to support printable structures, and are not guaranteed.
  68. auto OutputYaml() const -> Yaml::OutputMapping {
  69. return Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  70. for (auto [id, value] : enumerate()) {
  71. map.Add(PrintToString(id), Yaml::OutputScalar(value));
  72. }
  73. });
  74. }
  75. // Collects memory usage of the values.
  76. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  77. -> void {
  78. mem_usage.Collect(label.str(), values_);
  79. }
  80. auto array_ref() const -> llvm::ArrayRef<ValueType> { return values_; }
  81. auto size() const -> size_t { return values_.size(); }
  82. // Makes an iterable range over pairs of the index and a reference to the
  83. // value for each value in the store.
  84. //
  85. // The range is over references to the values in the store, even if used with
  86. // `auto` to destructure the pair. In this example, the `value` is a
  87. // `ConstRefType`:
  88. // ```
  89. // for (auto [id, value] : store.enumerate()) { ... }
  90. // ```
  91. auto enumerate() const -> auto {
  92. auto index_to_id = [](auto pair) -> std::pair<IdT, ConstRefType> {
  93. auto [index, value] = pair;
  94. return std::pair<IdT, ConstRefType>(IdT(index), value);
  95. };
  96. return llvm::map_range(llvm::enumerate(values_), index_to_id);
  97. }
  98. private:
  99. // Set inline size to 0 because these will typically be too large for the
  100. // stack, while this does make File smaller.
  101. llvm::SmallVector<std::decay_t<ValueType>, 0> values_;
  102. };
  103. // A wrapper for accumulating immutable values with deduplication, providing IDs
  104. // to later retrieve the value.
  105. //
  106. // IdT::ValueType must represent the type being indexed.
  107. template <typename IdT>
  108. class CanonicalValueStore {
  109. public:
  110. using ValueType = typename IdT::ValueType;
  111. using RefType = typename ValueStore<IdT>::RefType;
  112. using ConstRefType = typename ValueStore<IdT>::ConstRefType;
  113. // Stores a canonical copy of the value and returns an ID to reference it.
  114. auto Add(ValueType value) -> IdT;
  115. // Returns the value for an ID.
  116. auto Get(IdT id) const -> ConstRefType { return values_.Get(id); }
  117. // Looks up the canonical ID for a value, or returns `None` if not in the
  118. // store.
  119. auto Lookup(ValueType value) const -> IdT;
  120. // Reserves space.
  121. auto Reserve(size_t size) -> void;
  122. // These are to support printable structures, and are not guaranteed.
  123. auto OutputYaml() const -> Yaml::OutputMapping {
  124. return values_.OutputYaml();
  125. }
  126. auto array_ref() const -> llvm::ArrayRef<ValueType> {
  127. return values_.array_ref();
  128. }
  129. auto size() const -> size_t { return values_.size(); }
  130. // Collects memory usage of the values and deduplication set.
  131. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  132. -> void {
  133. mem_usage.Collect(MemUsage::ConcatLabel(label, "values_"), values_);
  134. auto bytes =
  135. set_.ComputeMetrics(KeyContext(values_.array_ref())).storage_bytes;
  136. mem_usage.Add(MemUsage::ConcatLabel(label, "set_"), bytes, bytes);
  137. }
  138. private:
  139. class KeyContext;
  140. ValueStore<IdT> values_;
  141. Set<IdT, /*SmallSize=*/0, KeyContext> set_;
  142. };
  143. template <typename IdT>
  144. class CanonicalValueStore<IdT>::KeyContext
  145. : public TranslatingKeyContext<KeyContext> {
  146. public:
  147. explicit KeyContext(llvm::ArrayRef<ValueType> values) : values_(values) {}
  148. // Note that it is safe to return a `const` reference here as the underlying
  149. // object's lifetime is provided by the `store_`.
  150. auto TranslateKey(IdT id) const -> const ValueType& {
  151. return values_[id.index];
  152. }
  153. private:
  154. llvm::ArrayRef<ValueType> values_;
  155. };
  156. template <typename IdT>
  157. auto CanonicalValueStore<IdT>::Add(ValueType value) -> IdT {
  158. auto make_key = [&] { return IdT(values_.Add(std::move(value))); };
  159. return set_.Insert(value, make_key, KeyContext(values_.array_ref())).key();
  160. }
  161. template <typename IdT>
  162. auto CanonicalValueStore<IdT>::Lookup(ValueType value) const -> IdT {
  163. if (auto result = set_.Lookup(value, KeyContext(values_.array_ref()))) {
  164. return result.key();
  165. }
  166. return IdT::None;
  167. }
  168. template <typename IdT>
  169. auto CanonicalValueStore<IdT>::Reserve(size_t size) -> void {
  170. // Compute the resulting new insert count using the size of values -- the
  171. // set doesn't have a fast to compute current size.
  172. if (size > values_.size()) {
  173. set_.GrowForInsertCount(size - values_.size(),
  174. KeyContext(values_.array_ref()));
  175. }
  176. values_.Reserve(size);
  177. }
  178. // A ValueStore that builds a 1:1 relationship between two IDs.
  179. // * `RelatedIdT` represents a related ID that can be used to find values in the
  180. // store.
  181. // * `IdT` is the actual ID of values in this store, and `IdT::ValueType` is the
  182. // value type being stored.
  183. //
  184. // The value store builds a mapping so that either ID can be used later to find
  185. // a value. And the user can query if a related `RelatedIdT` has been used to
  186. // add a value to the store or not.
  187. //
  188. // When adding to the store, the user provides the related `RelatedIdT` along
  189. // with the value being stored, and gets back the ID of the value in the store.
  190. //
  191. // This store requires more storage space than normal ValueStore does, as it
  192. // requires storing a bit for presence of each `RelatedIdT`. And it allocates
  193. // memory for values for all IDs up largest ID present in the store, even if
  194. // they are not yet used.
  195. template <typename RelatedIdT, typename IdT>
  196. class RelationalValueStore {
  197. public:
  198. using ValueType = IdT::ValueType;
  199. using ConstRefType = ValueStore<IdT>::ConstRefType;
  200. // Given the related ID and a value, stores the value and returns a mapped ID
  201. // to reference it in the store.
  202. auto Add(RelatedIdT related_id, ValueType value) -> IdT {
  203. CARBON_DCHECK(related_id.index >= 0, "{0}", related_id);
  204. IdT id(related_id.index);
  205. if (static_cast<size_t>(id.index) >= values_.size()) {
  206. values_.resize(id.index + 1);
  207. }
  208. auto& opt = values_[id.index];
  209. CARBON_CHECK(!opt.has_value(),
  210. "Add with `related_id` that was already added to the store");
  211. opt.emplace(std::move(value));
  212. return id;
  213. }
  214. // Returns the ID of a value in the store if the `related_id` was previously
  215. // used to add a value to the store, or None.
  216. auto TryGetId(RelatedIdT related_id) const -> IdT {
  217. CARBON_DCHECK(related_id.index >= 0, "{0}", related_id);
  218. if (static_cast<size_t>(related_id.index) >= values_.size()) {
  219. return IdT::None;
  220. }
  221. auto& opt = values_[related_id.index];
  222. if (!opt.has_value()) {
  223. return IdT::None;
  224. }
  225. return IdT(related_id.index);
  226. }
  227. // Returns a value for an ID.
  228. auto Get(IdT id) const -> ConstRefType {
  229. CARBON_DCHECK(id.index >= 0, "{0}", id);
  230. return *values_[id.index];
  231. }
  232. private:
  233. // Set inline size to 0 because these will typically be too large for the
  234. // stack, while this does make File smaller.
  235. llvm::SmallVector<std::optional<std::decay_t<ValueType>>, 0> values_;
  236. };
  237. } // namespace Carbon
  238. #endif // CARBON_TOOLCHAIN_BASE_VALUE_STORE_H_