value_store.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 <type_traits>
  7. #include "common/check.h"
  8. #include "common/ostream.h"
  9. #include "llvm/ADT/APInt.h"
  10. #include "llvm/ADT/DenseMap.h"
  11. #include "llvm/ADT/Sequence.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/ADT/StringExtras.h"
  14. #include "llvm/Support/YAMLParser.h"
  15. #include "toolchain/base/index_base.h"
  16. #include "toolchain/base/yaml.h"
  17. namespace Carbon {
  18. // The value of a real literal.
  19. //
  20. // This is either a dyadic fraction (mantissa * 2^exponent) or a decadic
  21. // fraction (mantissa * 10^exponent).
  22. //
  23. // TODO: For SemIR, replace this with a Rational type, per the design:
  24. // docs/design/expressions/literals.md
  25. class Real : public Printable<Real> {
  26. public:
  27. auto Print(llvm::raw_ostream& output_stream) const -> void {
  28. mantissa.print(output_stream, /*isSigned=*/false);
  29. output_stream << "*" << (is_decimal ? "10" : "2") << "^" << exponent;
  30. }
  31. // The mantissa, represented as an unsigned integer.
  32. llvm::APInt mantissa;
  33. // The exponent, represented as a signed integer.
  34. llvm::APInt exponent;
  35. // If false, the value is mantissa * 2^exponent.
  36. // If true, the value is mantissa * 10^exponent.
  37. // TODO: This field increases Real from 32 bytes to 40 bytes. Consider
  38. // changing how it's tracked for space savings.
  39. bool is_decimal;
  40. };
  41. // Corresponds to an integer value represented by an APInt.
  42. struct IntId : public IdBase, public Printable<IntId> {
  43. using ValueType = const llvm::APInt;
  44. static const IntId Invalid;
  45. using IdBase::IdBase;
  46. auto Print(llvm::raw_ostream& out) const -> void {
  47. out << "int";
  48. IdBase::Print(out);
  49. }
  50. };
  51. constexpr IntId IntId::Invalid(IntId::InvalidIndex);
  52. // Corresponds to a Real value.
  53. struct RealId : public IdBase, public Printable<RealId> {
  54. using ValueType = const Real;
  55. static const RealId Invalid;
  56. using IdBase::IdBase;
  57. auto Print(llvm::raw_ostream& out) const -> void {
  58. out << "real";
  59. IdBase::Print(out);
  60. }
  61. };
  62. constexpr RealId RealId::Invalid(RealId::InvalidIndex);
  63. // Corresponds to a StringRef.
  64. struct StringId : public IdBase, public Printable<StringId> {
  65. using ValueType = const std::string;
  66. static const StringId Invalid;
  67. using IdBase::IdBase;
  68. auto Print(llvm::raw_ostream& out) const -> void {
  69. out << "str";
  70. IdBase::Print(out);
  71. }
  72. };
  73. constexpr StringId StringId::Invalid(StringId::InvalidIndex);
  74. // Adapts StringId for identifiers.
  75. //
  76. // `NameId` relies on the values of this type other than `Invalid` all being
  77. // non-negative.
  78. struct IdentifierId : public IdBase, public Printable<IdentifierId> {
  79. static const IdentifierId Invalid;
  80. using IdBase::IdBase;
  81. auto Print(llvm::raw_ostream& out) const -> void {
  82. out << "strId";
  83. IdBase::Print(out);
  84. }
  85. };
  86. constexpr IdentifierId IdentifierId::Invalid(IdentifierId::InvalidIndex);
  87. // Adapts StringId for values of string literals.
  88. struct StringLiteralValueId : public IdBase,
  89. public Printable<StringLiteralValueId> {
  90. static const StringLiteralValueId Invalid;
  91. using IdBase::IdBase;
  92. auto Print(llvm::raw_ostream& out) const -> void {
  93. out << "strLit";
  94. IdBase::Print(out);
  95. }
  96. };
  97. constexpr StringLiteralValueId StringLiteralValueId::Invalid(
  98. StringLiteralValueId::InvalidIndex);
  99. namespace Internal {
  100. // Used as a parent class for non-printable types. This is just for
  101. // std::conditional, not as an API.
  102. class ValueStoreNotPrintable {};
  103. } // namespace Internal
  104. // A simple wrapper for accumulating values, providing IDs to later retrieve the
  105. // value. This does not do deduplication.
  106. //
  107. // IdT::ValueType must represent the type being indexed.
  108. template <typename IdT>
  109. class ValueStore
  110. : public std::conditional<
  111. std::is_base_of_v<Printable<typename IdT::ValueType>,
  112. typename IdT::ValueType>,
  113. Yaml::Printable<ValueStore<IdT>>, Internal::ValueStoreNotPrintable> {
  114. public:
  115. using ValueType = typename IdT::ValueType;
  116. // Stores the value and returns an ID to reference it.
  117. auto Add(ValueType value) -> IdT {
  118. IdT id = IdT(values_.size());
  119. CARBON_CHECK(id.index >= 0) << "Id overflow";
  120. values_.push_back(std::move(value));
  121. return id;
  122. }
  123. // Adds a default constructed value and returns an ID to reference it.
  124. auto AddDefaultValue() -> IdT {
  125. auto id = IdT(values_.size());
  126. values_.resize(id.index + 1);
  127. return id;
  128. }
  129. // Returns a mutable value for an ID.
  130. auto Get(IdT id) -> ValueType& {
  131. CARBON_CHECK(id.index >= 0) << id;
  132. return values_[id.index];
  133. }
  134. // Returns the value for an ID.
  135. auto Get(IdT id) const -> const ValueType& {
  136. CARBON_CHECK(id.index >= 0) << id;
  137. return values_[id.index];
  138. }
  139. // Reserves space.
  140. auto Reserve(size_t size) -> void { values_.reserve(size); }
  141. // These are to support printable structures, and are not guaranteed.
  142. auto OutputYaml() const -> Yaml::OutputMapping {
  143. return Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  144. for (auto i : llvm::seq(values_.size())) {
  145. auto id = IdT(i);
  146. map.Add(PrintToString(id), Yaml::OutputScalar(Get(id)));
  147. }
  148. });
  149. }
  150. auto array_ref() const -> llvm::ArrayRef<ValueType> { return values_; }
  151. auto size() const -> size_t { return values_.size(); }
  152. private:
  153. // Set inline size to 0 because these will typically be too large for the
  154. // stack, while this does make File smaller.
  155. llvm::SmallVector<std::decay_t<ValueType>, 0> values_;
  156. };
  157. // Storage for StringRefs. The caller is responsible for ensuring storage is
  158. // allocated.
  159. template <>
  160. class ValueStore<StringId> : public Yaml::Printable<ValueStore<StringId>> {
  161. public:
  162. // Returns an ID to reference the value. May return an existing ID if the
  163. // string was previously added.
  164. auto Add(llvm::StringRef value) -> StringId {
  165. auto [it, inserted] = map_.insert({value, StringId(values_.size())});
  166. if (inserted) {
  167. CARBON_CHECK(it->second.index >= 0) << "Too many unique strings";
  168. values_.push_back(value);
  169. }
  170. return it->second;
  171. }
  172. // Returns the value for an ID.
  173. auto Get(StringId id) const -> llvm::StringRef {
  174. CARBON_CHECK(id.is_valid());
  175. return values_[id.index];
  176. }
  177. // Returns an ID for the value, or Invalid if not found.
  178. auto Lookup(llvm::StringRef value) const -> StringId {
  179. if (auto it = map_.find(value); it != map_.end()) {
  180. return it->second;
  181. }
  182. return StringId::Invalid;
  183. }
  184. auto OutputYaml() const -> Yaml::OutputMapping {
  185. return Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  186. for (auto [i, val] : llvm::enumerate(values_)) {
  187. map.Add(PrintToString(StringId(i)), val);
  188. }
  189. });
  190. }
  191. auto size() const -> size_t { return values_.size(); }
  192. private:
  193. llvm::DenseMap<llvm::StringRef, StringId> map_;
  194. // Set inline size to 0 because these will typically be too large for the
  195. // stack, while this does make File smaller.
  196. llvm::SmallVector<llvm::StringRef, 0> values_;
  197. };
  198. // A thin wrapper around a `ValueStore<StringId>` that provides a different IdT,
  199. // while using a unified storage for values. This avoids potentially
  200. // duplicative string hash maps, which are expensive.
  201. template <typename IdT>
  202. class StringStoreWrapper : public Printable<StringStoreWrapper<IdT>> {
  203. public:
  204. explicit StringStoreWrapper(ValueStore<StringId>* values) : values_(values) {}
  205. auto Add(llvm::StringRef value) -> IdT {
  206. return IdT(values_->Add(value).index);
  207. }
  208. auto Get(IdT id) const -> llvm::StringRef {
  209. return values_->Get(StringId(id.index));
  210. }
  211. auto Lookup(llvm::StringRef value) const -> IdT {
  212. return IdT(values_->Lookup(value).index);
  213. }
  214. auto Print(llvm::raw_ostream& out) const -> void { out << *values_; }
  215. auto size() const -> size_t { return values_->size(); }
  216. private:
  217. ValueStore<StringId>* values_;
  218. };
  219. // Stores that will be used across compiler phases for a given compilation unit.
  220. // This is provided mainly so that they don't need to be passed separately.
  221. class SharedValueStores : public Yaml::Printable<SharedValueStores> {
  222. public:
  223. explicit SharedValueStores()
  224. : identifiers_(&strings_), string_literal_values_(&strings_) {}
  225. // Not copyable or movable.
  226. SharedValueStores(const SharedValueStores&) = delete;
  227. auto operator=(const SharedValueStores&) -> SharedValueStores& = delete;
  228. auto identifiers() -> StringStoreWrapper<IdentifierId>& {
  229. return identifiers_;
  230. }
  231. auto identifiers() const -> const StringStoreWrapper<IdentifierId>& {
  232. return identifiers_;
  233. }
  234. auto ints() -> ValueStore<IntId>& { return ints_; }
  235. auto ints() const -> const ValueStore<IntId>& { return ints_; }
  236. auto reals() -> ValueStore<RealId>& { return reals_; }
  237. auto reals() const -> const ValueStore<RealId>& { return reals_; }
  238. auto string_literal_values() -> StringStoreWrapper<StringLiteralValueId>& {
  239. return string_literal_values_;
  240. }
  241. auto string_literal_values() const
  242. -> const StringStoreWrapper<StringLiteralValueId>& {
  243. return string_literal_values_;
  244. }
  245. auto OutputYaml(std::optional<llvm::StringRef> filename = std::nullopt) const
  246. -> Yaml::OutputMapping {
  247. return Yaml::OutputMapping([&, filename](Yaml::OutputMapping::Map map) {
  248. if (filename) {
  249. map.Add("filename", *filename);
  250. }
  251. map.Add("shared_values",
  252. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  253. map.Add("ints", ints_.OutputYaml());
  254. map.Add("reals", reals_.OutputYaml());
  255. map.Add("strings", strings_.OutputYaml());
  256. }));
  257. });
  258. }
  259. private:
  260. ValueStore<IntId> ints_;
  261. ValueStore<RealId> reals_;
  262. ValueStore<StringId> strings_;
  263. StringStoreWrapper<IdentifierId> identifiers_;
  264. StringStoreWrapper<StringLiteralValueId> string_literal_values_;
  265. };
  266. } // namespace Carbon
  267. // Support use of IdentifierId as DenseMap/DenseSet keys.
  268. // TODO: Remove once NameId is used in checking.
  269. template <>
  270. struct llvm::DenseMapInfo<Carbon::IdentifierId>
  271. : public Carbon::IndexMapInfo<Carbon::IdentifierId> {};
  272. // Support use of StringId as DenseMap/DenseSet keys.
  273. template <>
  274. struct llvm::DenseMapInfo<Carbon::StringId>
  275. : public Carbon::IndexMapInfo<Carbon::StringId> {};
  276. #endif // CARBON_TOOLCHAIN_BASE_VALUE_STORE_H_