constant.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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_SEM_IR_CONSTANT_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_CONSTANT_H_
  6. #include "common/map.h"
  7. #include "toolchain/base/yaml.h"
  8. #include "toolchain/sem_ir/ids.h"
  9. #include "toolchain/sem_ir/inst.h"
  10. namespace Carbon::SemIR {
  11. // The kinds of symbolic bindings that a constant might depend on. These are
  12. // ordered from least to most dependent, so that the dependence of an operation
  13. // can typically be computed by taking the maximum of the dependences of its
  14. // operands.
  15. enum class ConstantDependence : uint8_t {
  16. // This constant's value is known concretely, and does not depend on any
  17. // symbolic binding.
  18. None,
  19. // The only symbolic binding that this constant depends on is `.Self`.
  20. PeriodSelf,
  21. // The only symbolic bindings that this constant depends on are checked
  22. // generic bindings.
  23. Checked,
  24. // This symbolic binding depends on a template-dependent value, such as a
  25. // template parameter.
  26. Template,
  27. };
  28. // Information about a symbolic constant value. These are indexed by
  29. // `ConstantId`s for which `is_symbolic` is true.
  30. //
  31. // A constant value is defined by the canonical ID of a fully-evaluated inst,
  32. // called a "constant inst", which may depend on the canonical IDs of other
  33. // constant insts. "Canonical" here means that it is chosen such that equal
  34. // constants will have equal canonical IDs. This is typically achieved by
  35. // deduplication in `ConstantStore`, but certain kinds of constant insts are
  36. // canonicalized in other ways.
  37. //
  38. // That constant inst ID fully defines the constant value in itself, but for
  39. // symbolic constant values we sometimes need efficient access to metadata about
  40. // the mapping between the constant and corresponding constants in specifics of
  41. // its enclosing generic. As a result, the ID of a concrete constant directly
  42. // encodes the ID of the constant inst, but the ID of a symbolic constant is an
  43. // index into a table of `SymbolicConstant` entries containing that metadata, as
  44. // well as the constant inst ID.
  45. //
  46. // The price of this optimization is that the constant value's ID depends on the
  47. // enclosing generic, which isn't semantically relevant unless we're
  48. // specifically operating on the generic -> specific mapping. As a result, every
  49. // symbolic constant is represented by two `SymbolicConstant`s, with separate
  50. // IDs: one with that additional metadata, and one without it. The form with
  51. // additional metadata is called an "attached constant", and the form without it
  52. // is an "unattached constant". Note that constants in separate generics may be
  53. // represented by the same unattached constant. In general, only one of these
  54. // IDs is correct to use in a given situation; `ConstantValueStore` can be used
  55. // to map between them if necessary.
  56. //
  57. // Equivalently, you can think of an unattached constant as being implicitly
  58. // parameterized by the `bind_symbolic_name` constant insts that it depends on,
  59. // whereas an attached constant explicitly binds them to parameters of the
  60. // enclosing generic. It's the difference between "`Vector(T)` where `T` is some
  61. // value of type `type`" and "`Vector(T)` where `T` is the `T:! type` parameter
  62. // of this particular enclosing generic".
  63. //
  64. // TODO: consider instead keeping this metadata in a separate hash map keyed by
  65. // a `GenericId`/`ConstantId` pair, so that each constant has a single
  66. // `ConstantId`, rather than separate attached and unattached IDs.
  67. struct SymbolicConstant : Printable<SymbolicConstant> {
  68. // The canonical ID of the inst that defines this constant.
  69. InstId inst_id;
  70. // The generic that this constant is attached to, or `None` if this is an
  71. // unattached constant.
  72. GenericId generic_id;
  73. // The index of this constant within the generic's eval block, if this is an
  74. // attached constant. For a given specific of that generic, this is also the
  75. // index of this constant's value in the value block of that specific. If
  76. // this constant is unattached, `index` will be `None`.
  77. GenericInstIndex index;
  78. // The kind of dependence this symbolic constant exhibits. Should never be
  79. // `None`.
  80. ConstantDependence dependence;
  81. auto Print(llvm::raw_ostream& out) const -> void {
  82. out << "{inst: " << inst_id << ", generic: " << generic_id
  83. << ", index: " << index << ", kind: ";
  84. switch (dependence) {
  85. case ConstantDependence::None:
  86. out << "<error: concrete>";
  87. break;
  88. case ConstantDependence::PeriodSelf:
  89. out << "self";
  90. break;
  91. case ConstantDependence::Checked:
  92. out << "checked";
  93. break;
  94. case ConstantDependence::Template:
  95. out << "template";
  96. break;
  97. }
  98. out << "}";
  99. }
  100. };
  101. // Provides a ValueStore wrapper for tracking the constant values of
  102. // instructions.
  103. class ConstantValueStore {
  104. struct UnusableType {};
  105. public:
  106. inline static const auto Unusable = UnusableType();
  107. // Constructs an unusable ConstantValueStore, only good as a placeholder (eg:
  108. // in C++ interop, where there's no foreign SemIR to reference)
  109. explicit ConstantValueStore(UnusableType /* tag */)
  110. : default_(ConstantId::None), insts_(nullptr) {}
  111. explicit ConstantValueStore(ConstantId default_value, const InstStore* insts)
  112. : default_(default_value),
  113. values_((CARBON_CHECK(insts), insts->GetIdTag())),
  114. symbolic_constants_(insts->GetIdTag()),
  115. insts_(insts) {}
  116. // Returns the constant value of the requested instruction, which is default_
  117. // if unallocated. Always returns an unattached constant.
  118. auto Get(InstId inst_id) const -> ConstantId {
  119. auto const_id = GetAttached(inst_id);
  120. return const_id.has_value() ? GetUnattachedConstant(const_id) : const_id;
  121. }
  122. // Returns the constant value of the requested instruction, which is default_
  123. // if unallocated. This may be an attached constant.
  124. auto GetAttached(InstId inst_id) const -> ConstantId {
  125. CARBON_CHECK(insts_,
  126. "Used ConstantValueStores must have an associated InstStore.");
  127. return values_.GetWithDefault(inst_id, default_);
  128. }
  129. // Sets the constant value of the given instruction, or sets that it is known
  130. // to not be a constant.
  131. auto Set(InstId inst_id, ConstantId const_id) -> void {
  132. CARBON_CHECK(insts_,
  133. "Used ConstantValueStores must have an associated InstStore.");
  134. auto index = insts_->GetRawIndex(inst_id);
  135. if (static_cast<size_t>(index) >= values_.size()) {
  136. values_.Resize(index + 1, default_);
  137. }
  138. values_.Get(inst_id) = const_id;
  139. }
  140. // Gets the ID of the underlying constant inst for the given constant. Returns
  141. // `None` if the constant ID is non-constant. Requires `const_id.has_value()`.
  142. auto GetInstId(ConstantId const_id) const -> InstId {
  143. if (const_id.is_concrete()) {
  144. return const_id.concrete_inst_id();
  145. }
  146. if (const_id.is_symbolic()) {
  147. return GetSymbolicConstant(const_id).inst_id;
  148. }
  149. return InstId::None;
  150. }
  151. // Gets the ID of the underlying constant inst for the given constant. Returns
  152. // `None` if the constant ID is non-constant or `None`.
  153. auto GetInstIdIfValid(ConstantId const_id) const -> InstId {
  154. return const_id.has_value() ? GetInstId(const_id) : InstId::None;
  155. }
  156. // Given an instruction, returns the unique constant instruction that is
  157. // equivalent to it. Returns `None` for a non-constant instruction.
  158. auto GetConstantInstId(InstId inst_id) const -> InstId {
  159. return GetInstId(GetAttached(inst_id));
  160. }
  161. // Given a type instruction, returns the unique constant instruction that is
  162. // equivalent to it. Returns `None` for a non-constant instruction.
  163. auto GetConstantTypeInstId(TypeInstId inst_id) const -> TypeInstId {
  164. // If the source instruction has type `type`, its constant value will too,
  165. // since the constant value of `type` is itself.
  166. return TypeInstId::UnsafeMake(GetInstId(GetAttached(inst_id)));
  167. }
  168. // Given a symbolic constant, returns the unattached form of that constant.
  169. // For any other constant ID, returns the ID unchanged.
  170. auto GetUnattachedConstant(ConstantId const_id) const -> ConstantId {
  171. if (const_id.is_symbolic()) {
  172. return values_.Get(GetSymbolicConstant(const_id).inst_id);
  173. }
  174. return const_id;
  175. }
  176. auto AddSymbolicConstant(SymbolicConstant constant) -> ConstantId {
  177. return ConstantId::ForSymbolicConstantId(symbolic_constants_.Add(constant));
  178. }
  179. auto GetSymbolicConstant(ConstantId const_id) -> SymbolicConstant& {
  180. return symbolic_constants_.Get(const_id.symbolic_id());
  181. }
  182. auto GetSymbolicConstant(ConstantId const_id) const
  183. -> const SymbolicConstant& {
  184. return symbolic_constants_.Get(const_id.symbolic_id());
  185. }
  186. // Get the dependence of the given constant.
  187. auto GetDependence(ConstantId const_id) const -> ConstantDependence {
  188. return const_id.is_symbolic() ? GetSymbolicConstant(const_id).dependence
  189. : ConstantDependence::None;
  190. }
  191. // Returns true for symbolic constants other than those that are only symbolic
  192. // because they depend on `.Self`.
  193. auto DependsOnGenericParameter(ConstantId const_id) const -> bool {
  194. return GetDependence(const_id) > ConstantDependence::PeriodSelf;
  195. }
  196. // Collects memory usage of members.
  197. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  198. -> void {
  199. mem_usage.Collect(MemUsage::ConcatLabel(label, "values_"), values_);
  200. mem_usage.Collect(MemUsage::ConcatLabel(label, "symbolic_constants_"),
  201. symbolic_constants_);
  202. }
  203. // Makes an iterable range over pairs of the instruction id and constant value
  204. // id for each value in the store.
  205. auto enumerate() const -> auto { return values_.enumerate(); }
  206. // Outputs assigned constant values, and all symbolic constants.
  207. auto OutputYaml(bool include_singletons) const -> Yaml::OutputMapping {
  208. return Yaml::OutputMapping([&, include_singletons](
  209. Yaml::OutputMapping::Map map) {
  210. map.Add("values", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  211. for (auto [id, value] : values_.enumerate()) {
  212. if (!include_singletons && IsSingletonInstId(id)) {
  213. continue;
  214. }
  215. if (!value.has_value() || value.is_constant()) {
  216. map.Add(PrintToString(id), Yaml::OutputScalar(value));
  217. }
  218. }
  219. }));
  220. map.Add("symbolic_constants", symbolic_constants_.OutputYaml());
  221. });
  222. }
  223. private:
  224. const ConstantId default_;
  225. // A mapping from `InstId::index` to the corresponding constant value. This is
  226. // expected to be sparse, and may be smaller than the list of instructions if
  227. // there are trailing non-constant instructions.
  228. //
  229. // Set inline size to 0 because these will typically be too large for the
  230. // stack, while this does make File smaller.
  231. ValueStore<InstId, ConstantId> values_;
  232. // A mapping from a symbolic constant ID index to information about the
  233. // symbolic constant. For a concrete constant, the only information that we
  234. // track is the instruction ID, which is stored directly within the
  235. // `ConstantId`. For a symbolic constant, we also track information about
  236. // where the constant was used, which is stored here.
  237. ValueStore<ConstantId::SymbolicId, SymbolicConstant> symbolic_constants_;
  238. const InstStore* insts_;
  239. };
  240. // Given a constant ID, returns an instruction that has that constant value.
  241. // For an unattached constant, the returned instruction is the instruction that
  242. // defines the constant; for an attached constant, this is the instruction in
  243. // the eval block that computes the constant value in each specific.
  244. //
  245. // Returns InstId::None if the ConstantId is None or NotConstant.
  246. auto GetInstWithConstantValue(const File& file, ConstantId const_id) -> InstId;
  247. // Provides storage for instructions representing deduplicated global constants.
  248. class ConstantStore {
  249. public:
  250. explicit ConstantStore(File* sem_ir) : sem_ir_(sem_ir) {}
  251. // Adds a new constant instruction, or gets the existing constant with this
  252. // value. Returns the ID of the constant.
  253. //
  254. // This updates `sem_ir->insts()` and `sem_ir->constant_values()` if the
  255. // constant is new.
  256. auto GetOrAdd(Inst inst, ConstantDependence dependence) -> ConstantId;
  257. // Collects memory usage of members.
  258. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  259. -> void {
  260. mem_usage.Collect(MemUsage::ConcatLabel(label, "map_"), map_);
  261. mem_usage.Collect(MemUsage::ConcatLabel(label, "constants_"), constants_);
  262. }
  263. // Returns a copy of the constant IDs as a vector, in an arbitrary but
  264. // stable order. This should not be used anywhere performance-sensitive.
  265. auto array_ref() const -> llvm::ArrayRef<InstId> { return constants_; }
  266. auto size() const -> int { return constants_.size(); }
  267. private:
  268. File* const sem_ir_;
  269. Map<Inst, ConstantId> map_;
  270. llvm::SmallVector<InstId, 0> constants_;
  271. };
  272. } // namespace Carbon::SemIR
  273. #endif // CARBON_TOOLCHAIN_SEM_IR_CONSTANT_H_