value_store.h 11 KB

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