eval_inst.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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. #include "toolchain/check/eval_inst.h"
  5. #include <variant>
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/action.h"
  8. #include "toolchain/check/cpp/constant.h"
  9. #include "toolchain/check/cpp/import.h"
  10. #include "toolchain/check/cpp/type_mapping.h"
  11. #include "toolchain/check/diagnostic_helpers.h"
  12. #include "toolchain/check/facet_type.h"
  13. #include "toolchain/check/generic.h"
  14. #include "toolchain/check/impl_lookup.h"
  15. #include "toolchain/check/import_ref.h"
  16. #include "toolchain/check/inst.h"
  17. #include "toolchain/check/type.h"
  18. #include "toolchain/check/type_completion.h"
  19. #include "toolchain/diagnostics/diagnostic.h"
  20. #include "toolchain/parse/typed_nodes.h"
  21. #include "toolchain/sem_ir/builtin_function_kind.h"
  22. #include "toolchain/sem_ir/expr_info.h"
  23. #include "toolchain/sem_ir/ids.h"
  24. #include "toolchain/sem_ir/pattern.h"
  25. #include "toolchain/sem_ir/typed_insts.h"
  26. namespace Carbon::Check {
  27. // Performs an access into an aggregate, retrieving the specified element.
  28. static auto PerformAggregateAccess(Context& context, SemIR::Inst inst)
  29. -> ConstantEvalResult {
  30. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  31. if (auto aggregate = context.insts().TryGetAs<SemIR::AnyAggregateValue>(
  32. access_inst.aggregate_id)) {
  33. auto elements = context.inst_blocks().Get(aggregate->elements_id);
  34. auto index = static_cast<size_t>(access_inst.index.index);
  35. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  36. // `Phase` is not used here. If this element is a concrete constant, then
  37. // so is the result of indexing, even if the aggregate also contains a
  38. // symbolic context.
  39. return ConstantEvalResult::Existing(
  40. context.constant_values().Get(elements[index]));
  41. }
  42. return ConstantEvalResult::NewSamePhase(inst);
  43. }
  44. auto EvalConstantInst(Context& /*context*/, SemIR::ArrayInit inst)
  45. -> ConstantEvalResult {
  46. // TODO: Add an `ArrayValue` to represent a constant array object
  47. // representation instead of using a `TupleValue`.
  48. return ConstantEvalResult::NewSamePhase(
  49. SemIR::TupleValue{.type_id = inst.type_id, .elements_id = inst.inits_id});
  50. }
  51. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  52. SemIR::ArrayType inst) -> ConstantEvalResult {
  53. auto bound_inst = context.insts().Get(inst.bound_id);
  54. auto int_bound = bound_inst.TryAs<SemIR::IntValue>();
  55. if (!int_bound) {
  56. CARBON_CHECK(context.constant_values().Get(inst.bound_id).is_symbolic(),
  57. "Unexpected inst {0} for template constant int", bound_inst);
  58. return ConstantEvalResult::NewSamePhase(inst);
  59. }
  60. // TODO: We should check that the size of the resulting array type
  61. // fits in 64 bits, not just that the bound does. Should we use a
  62. // 32-bit limit for 32-bit targets?
  63. const auto& bound_val = context.ints().Get(int_bound->int_id);
  64. if (context.types().IsSignedInt(int_bound->type_id) &&
  65. bound_val.isNegative()) {
  66. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  67. "array bound of {0} is negative", TypedInt);
  68. context.emitter().Emit(
  69. context.insts().GetAs<SemIR::ArrayType>(inst_id).bound_id,
  70. ArrayBoundNegative, {.type = int_bound->type_id, .value = bound_val});
  71. return ConstantEvalResult::Error;
  72. }
  73. if (bound_val.getActiveBits() > 64) {
  74. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  75. "array bound of {0} is too large", TypedInt);
  76. context.emitter().Emit(
  77. context.insts().GetAs<SemIR::ArrayType>(inst_id).bound_id,
  78. ArrayBoundTooLarge, {.type = int_bound->type_id, .value = bound_val});
  79. return ConstantEvalResult::Error;
  80. }
  81. return ConstantEvalResult::NewSamePhase(inst);
  82. }
  83. auto EvalConstantInst(Context& context, SemIR::AsCompatible inst)
  84. -> ConstantEvalResult {
  85. // AsCompatible changes the type of the source instruction; its constant
  86. // value, if there is one, needs to be modified to be of the same type.
  87. auto value_id = context.constant_values().Get(inst.source_id);
  88. CARBON_CHECK(value_id.is_constant());
  89. auto value_inst =
  90. context.insts().Get(context.constant_values().GetInstId(value_id));
  91. value_inst.SetType(inst.type_id);
  92. return ConstantEvalResult::NewAnyPhase(value_inst);
  93. }
  94. auto EvalConstantInst(Context& context, SemIR::AliasBinding inst)
  95. -> ConstantEvalResult {
  96. // An alias evaluates to the value it's bound to.
  97. return ConstantEvalResult::Existing(
  98. context.constant_values().Get(inst.value_id));
  99. }
  100. auto EvalConstantInst(Context& context, SemIR::RefBinding inst)
  101. -> ConstantEvalResult {
  102. // A reference binding evaluates to the value it's bound to.
  103. if (inst.value_id.has_value()) {
  104. return ConstantEvalResult::Existing(
  105. context.constant_values().Get(inst.value_id));
  106. }
  107. return ConstantEvalResult::NotConstant;
  108. }
  109. auto EvalConstantInst(Context& /*context*/, SemIR::ValueBinding /*inst*/)
  110. -> ConstantEvalResult {
  111. // Non-`:!` value bindings are not constant.
  112. return ConstantEvalResult::NotConstant;
  113. }
  114. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  115. SemIR::AcquireValue inst) -> ConstantEvalResult {
  116. if (const auto* var_decl = GetAsClangVarDecl(context, inst.value_id)) {
  117. auto const_id =
  118. EvalCppVarDecl(context, SemIR::LocId(inst_id), var_decl, inst.type_id);
  119. if (const_id.has_value() && const_id.is_constant()) {
  120. return ConstantEvalResult::Existing(const_id);
  121. }
  122. return ConstantEvalResult::NotConstant;
  123. }
  124. return ConstantEvalResult::TODO;
  125. }
  126. auto EvalConstantInst(Context& context, SemIR::ClassElementAccess inst)
  127. -> ConstantEvalResult {
  128. return PerformAggregateAccess(context, inst);
  129. }
  130. auto EvalConstantInst(Context& context, SemIR::ClassDecl inst)
  131. -> ConstantEvalResult {
  132. const auto& class_info = context.classes().Get(inst.class_id);
  133. // If the class has generic parameters, we don't produce a class type, but a
  134. // callable whose return value is a class type.
  135. if (class_info.has_parameters()) {
  136. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  137. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  138. }
  139. // A non-generic class declaration evaluates to the class type.
  140. return ConstantEvalResult::NewAnyPhase(SemIR::ClassType{
  141. .type_id = SemIR::TypeType::TypeId,
  142. .class_id = inst.class_id,
  143. .specific_id =
  144. context.generics().GetSelfSpecific(class_info.generic_id)});
  145. }
  146. auto EvalConstantInst(Context& /*context*/, SemIR::ClassInit inst)
  147. -> ConstantEvalResult {
  148. // TODO: Add a `ClassValue` to represent a constant class object
  149. // representation instead of using a `StructValue`.
  150. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  151. .type_id = inst.type_id, .elements_id = inst.elements_id});
  152. }
  153. auto EvalConstantInst(Context& context, SemIR::ConstType inst)
  154. -> ConstantEvalResult {
  155. // `const (const T)` evaluates to `const T`.
  156. if (context.insts().Is<SemIR::ConstType>(inst.inner_id)) {
  157. return ConstantEvalResult::Existing(
  158. context.constant_values().Get(inst.inner_id));
  159. }
  160. // Otherwise, `const T` evaluates to itself.
  161. return ConstantEvalResult::NewSamePhase(inst);
  162. }
  163. auto EvalConstantInst(Context& /*context*/, SemIR::PartialType inst)
  164. -> ConstantEvalResult {
  165. return ConstantEvalResult::NewSamePhase(inst);
  166. }
  167. auto EvalConstantInst(Context& context, SemIR::Converted inst)
  168. -> ConstantEvalResult {
  169. // A conversion evaluates to the result of the conversion.
  170. return ConstantEvalResult::Existing(
  171. context.constant_values().Get(inst.result_id));
  172. }
  173. auto EvalConstantInst(Context& /*context*/, SemIR::Deref /*inst*/)
  174. -> ConstantEvalResult {
  175. // TODO: Handle this.
  176. return ConstantEvalResult::TODO;
  177. }
  178. auto EvalConstantInst(Context& context, SemIR::ExportDecl inst)
  179. -> ConstantEvalResult {
  180. // An export instruction evaluates to the exported declaration.
  181. return ConstantEvalResult::Existing(
  182. context.constant_values().Get(inst.value_id));
  183. }
  184. auto EvalConstantInst(Context& context, SemIR::FacetAccessType inst)
  185. -> ConstantEvalResult {
  186. if (auto facet_value = context.insts().TryGetAs<SemIR::FacetValue>(
  187. inst.facet_value_inst_id)) {
  188. return ConstantEvalResult::Existing(
  189. context.constant_values().Get(facet_value->type_inst_id));
  190. }
  191. if (auto bind_name = context.insts().TryGetAs<SemIR::SymbolicBinding>(
  192. inst.facet_value_inst_id)) {
  193. return ConstantEvalResult::NewSamePhase(SemIR::SymbolicBindingType{
  194. .type_id = SemIR::TypeType::TypeId,
  195. .entity_name_id = bind_name->entity_name_id,
  196. // TODO: This is to be removed, at which point explore if we should
  197. // replace NewSamePhase with NewAnyPhase (to make the constant value
  198. // concrete). This is still a symbolic type though even if the inst
  199. // doesn't contain a symbolic constant. Previously we crashed in CHECKs
  200. // when we had a symbolic instruction with only an EntityNameId, due to
  201. // it not changing in a generic eval block. Maybe that has improved in
  202. // the latest version of this instruction. If it's not symbolic, then
  203. // SubstConstantCallbacks and other Subst callers may need to handle
  204. // looking through concrete instructions which would be unfortunate.
  205. .facet_value_inst_id = inst.facet_value_inst_id});
  206. }
  207. // The `facet_value_inst_id` is always a facet value (has type facet type).
  208. CARBON_CHECK(context.types().Is<SemIR::FacetType>(
  209. context.insts().Get(inst.facet_value_inst_id).type_id()));
  210. // Other instructions (e.g. ImplWitnessAccess) of type FacetType can appear
  211. // here, in which case the constant inst is a FacetAccessType until those
  212. // instructions resolve to one of the above.
  213. return ConstantEvalResult::NewSamePhase(inst);
  214. }
  215. auto EvalConstantInst(Context& context, SemIR::FacetValue inst)
  216. -> ConstantEvalResult {
  217. // A FacetValue that just wraps a SymbolicBinding without adding/removing any
  218. // witnesses is evaluated back to the SymbolicBinding itself.
  219. if (auto bind_as_type = context.insts().TryGetAs<SemIR::SymbolicBindingType>(
  220. inst.type_inst_id)) {
  221. // TODO: Look in ScopeStack with the entity_name_id to find the facet value.
  222. auto bind_id = bind_as_type->facet_value_inst_id;
  223. auto bind = context.insts().GetAs<SemIR::SymbolicBinding>(bind_id);
  224. // If the FacetTypes are the same, then the FacetValue didn't add/remove
  225. // any witnesses.
  226. if (bind.type_id == inst.type_id) {
  227. return ConstantEvalResult::Existing(
  228. context.constant_values().Get(bind_id));
  229. }
  230. }
  231. return ConstantEvalResult::NewSamePhase(inst);
  232. }
  233. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  234. SemIR::FloatType inst) -> ConstantEvalResult {
  235. return ValidateFloatTypeAndSetKind(context, SemIR::LocId(inst_id), inst)
  236. ? ConstantEvalResult::NewSamePhase(inst)
  237. : ConstantEvalResult::Error;
  238. }
  239. auto EvalConstantInst(Context& /*context*/, SemIR::FunctionDecl inst)
  240. -> ConstantEvalResult {
  241. // A function declaration evaluates to a function object, which is an empty
  242. // object of function type.
  243. // TODO: Eventually we may need to handle captures here.
  244. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  245. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  246. }
  247. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  248. SemIR::LookupImplWitness inst) -> ConstantEvalResult {
  249. // The self value is canonicalized in order to produce a canonical
  250. // LookupImplWitness instruction, avoiding multiple constant values for
  251. // `<facet value>` and `<facet value>` as type, which always have the same
  252. // lookup result.
  253. auto self_facet_value_inst_id =
  254. GetCanonicalFacetOrTypeValue(context, inst.query_self_inst_id);
  255. // When we look for a witness in the (facet) type of self, we may get a
  256. // concrete witness from a `FacetValue` (which is `self_facet_value_inst_id`)
  257. // in which case this instruction evaluates to that witness.
  258. //
  259. // If we only get a symbolic witness result though, then this instruction
  260. // evaluates to a `LookupImplWitness`. Since there was no concrete result in
  261. // the `FacetValue`, we don't need to preserve it. By looking through the
  262. // `FacetValue` at the type value it wraps to generate a more canonical value
  263. // for a symbolic `LookupImplWitness`. This makes us produce the same constant
  264. // value for symbolic lookups in `FacetValue(T)` and `T`, since they will
  265. // always have the same lookup result later, when `T` is replaced in a
  266. // specific by something that can provide a concrete witness.
  267. if (auto facet_value = context.insts().TryGetAs<SemIR::FacetValue>(
  268. self_facet_value_inst_id)) {
  269. inst.query_self_inst_id =
  270. GetCanonicalFacetOrTypeValue(context, facet_value->type_inst_id);
  271. } else {
  272. inst.query_self_inst_id = self_facet_value_inst_id;
  273. }
  274. auto result = EvalLookupSingleImplWitness(context, SemIR::LocId(inst_id),
  275. inst, self_facet_value_inst_id,
  276. EvalImplLookupMode::Normal);
  277. if (!result.has_value()) {
  278. // We use NotConstant to communicate back to impl lookup that the lookup
  279. // failed. This can not happen for a deferred symbolic lookup in a generic
  280. // eval block, since we only add the deferred lookup instruction (being
  281. // evaluated here) to the SemIR if the lookup succeeds.
  282. return ConstantEvalResult::NotConstant;
  283. }
  284. if (result.has_final_value()) {
  285. return ConstantEvalResult::Existing(
  286. context.constant_values().Get(result.final_witness()));
  287. }
  288. return ConstantEvalResult::NewSamePhase(inst);
  289. }
  290. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  291. SemIR::ImplWitnessAccess inst) -> ConstantEvalResult {
  292. CARBON_DIAGNOSTIC(ImplAccessMemberBeforeSet, Error,
  293. "accessing member from impl before it has a defined value");
  294. CARBON_KIND_SWITCH(context.insts().Get(inst.witness_id)) {
  295. case CARBON_KIND(SemIR::ImplWitness witness): {
  296. // This is PerformAggregateAccess followed by GetConstantValueInSpecific.
  297. auto witness_table = context.insts().GetAs<SemIR::ImplWitnessTable>(
  298. witness.witness_table_id);
  299. auto elements = context.inst_blocks().Get(witness_table.elements_id);
  300. // `elements` can be empty if there is only a forward declaration of the
  301. // impl.
  302. if (!elements.empty()) {
  303. auto index = static_cast<size_t>(inst.index.index);
  304. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  305. auto element = elements[index];
  306. if (element.has_value()) {
  307. LoadImportRef(context, element);
  308. return ConstantEvalResult::Existing(GetConstantValueInSpecific(
  309. context.sem_ir(), witness.specific_id, element));
  310. }
  311. }
  312. // If we get here, this impl witness table entry has not been populated
  313. // yet, because the impl was referenced within its own definition.
  314. // TODO: Add note pointing to the impl declaration.
  315. context.emitter().Emit(inst_id, ImplAccessMemberBeforeSet);
  316. return ConstantEvalResult::Error;
  317. }
  318. case CARBON_KIND(SemIR::CustomWitness custom_witness): {
  319. auto elements = context.inst_blocks().Get(custom_witness.elements_id);
  320. auto index = static_cast<size_t>(inst.index.index);
  321. // `elements` can be shorter than the number of associated entities while
  322. // we're building the synthetic witness.
  323. if (index < elements.size()) {
  324. return ConstantEvalResult::Existing(
  325. context.constant_values().Get(elements[index]));
  326. }
  327. // If we get here, this synthesized witness table entry has not been
  328. // populated yet.
  329. // TODO: Is this reachable? We have no test coverage for this diagnostic.
  330. context.emitter().Emit(inst_id, ImplAccessMemberBeforeSet);
  331. return ConstantEvalResult::Error;
  332. }
  333. case CARBON_KIND(SemIR::LookupImplWitness witness): {
  334. // If the witness is symbolic but has a self type that is a FacetType, it
  335. // can pull rewrite values from the self type. If the access is for one of
  336. // those rewrites, evaluate to the RHS of the rewrite.
  337. auto witness_self_type_id =
  338. context.insts().Get(witness.query_self_inst_id).type_id();
  339. if (!context.types().Is<SemIR::FacetType>(witness_self_type_id)) {
  340. return ConstantEvalResult::NewSamePhase(inst);
  341. }
  342. // The `ImplWitnessAccess` is accessing a value, by index, for this
  343. // interface.
  344. auto access_interface_id = witness.query_specific_interface_id;
  345. auto witness_self_facet_type_id =
  346. context.types()
  347. .GetAs<SemIR::FacetType>(witness_self_type_id)
  348. .facet_type_id;
  349. // TODO: We could consider something better than linear search here, such
  350. // as a map. However that would probably require heap allocations which
  351. // may be worse overall since the number of rewrite constraints is
  352. // generally low. If the `rewrite_constraints` were sorted so that
  353. // associated constants are grouped together, as in
  354. // ResolveFacetTypeRewriteConstraints(), and limited to just the
  355. // `ImplWitnessAccess` entries, then a binary search may work here.
  356. for (auto witness_rewrite : context.facet_types()
  357. .Get(witness_self_facet_type_id)
  358. .rewrite_constraints) {
  359. // Look at each rewrite constraint in the self facet value's type. If
  360. // the LHS is an `ImplWitnessAccess` into the same interface that `inst`
  361. // is indexing into, then we can use its RHS as the value.
  362. auto witness_rewrite_lhs_access =
  363. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(
  364. witness_rewrite.lhs_id);
  365. if (!witness_rewrite_lhs_access) {
  366. continue;
  367. }
  368. if (witness_rewrite_lhs_access->index != inst.index) {
  369. continue;
  370. }
  371. auto witness_rewrite_lhs_interface_id =
  372. context.insts()
  373. .GetAs<SemIR::LookupImplWitness>(
  374. witness_rewrite_lhs_access->witness_id)
  375. .query_specific_interface_id;
  376. if (witness_rewrite_lhs_interface_id != access_interface_id) {
  377. continue;
  378. }
  379. // The `ImplWitnessAccess` evaluates to the RHS from the witness self
  380. // facet value's type.
  381. return ConstantEvalResult::Existing(
  382. context.constant_values().Get(witness_rewrite.rhs_id));
  383. }
  384. break;
  385. }
  386. default:
  387. break;
  388. }
  389. return ConstantEvalResult::NewSamePhase(inst);
  390. }
  391. auto EvalConstantInst(Context& context,
  392. SemIR::ImplWitnessAccessSubstituted inst)
  393. -> ConstantEvalResult {
  394. return ConstantEvalResult::Existing(
  395. context.constant_values().Get(inst.value_id));
  396. }
  397. auto EvalConstantInst(Context& context,
  398. SemIR::ImplWitnessAssociatedConstant inst)
  399. -> ConstantEvalResult {
  400. return ConstantEvalResult::Existing(
  401. context.constant_values().Get(inst.inst_id));
  402. }
  403. auto EvalConstantInst(Context& /*context*/, SemIR::ImportRefUnloaded inst)
  404. -> ConstantEvalResult {
  405. CARBON_FATAL("ImportRefUnloaded should be loaded before TryEvalInst: {0}",
  406. inst);
  407. }
  408. auto EvalConstantInst(Context& context, SemIR::InPlaceInit inst)
  409. -> ConstantEvalResult {
  410. // Initialization is not performed in-place during constant evaluation, so
  411. // just return the value of the initializer.
  412. return ConstantEvalResult::Existing(
  413. context.constant_values().Get(inst.src_id));
  414. }
  415. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  416. SemIR::IntType inst) -> ConstantEvalResult {
  417. return ValidateIntType(context, SemIR::LocId(inst_id), inst)
  418. ? ConstantEvalResult::NewSamePhase(inst)
  419. : ConstantEvalResult::Error;
  420. }
  421. auto EvalConstantInst(Context& context, SemIR::InterfaceDecl inst)
  422. -> ConstantEvalResult {
  423. const auto& interface_info = context.interfaces().Get(inst.interface_id);
  424. // If the interface has generic parameters, we don't produce an interface
  425. // type, but a callable whose return value is an interface type.
  426. if (interface_info.has_parameters()) {
  427. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  428. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  429. }
  430. // A non-parameterized interface declaration evaluates to a declared facet
  431. // type containing just the interface.
  432. return ConstantEvalResult::NewAnyPhase(FacetTypeFromInterface(
  433. context, inst.interface_id,
  434. context.generics().GetSelfSpecific(interface_info.generic_id)));
  435. }
  436. auto EvalConstantInst(Context& context, SemIR::NamedConstraintDecl inst)
  437. -> ConstantEvalResult {
  438. const auto& named_constraint_info =
  439. context.named_constraints().Get(inst.named_constraint_id);
  440. // If the named constraint has generic parameters, we don't produce a named
  441. // constraint type, but a callable whose return value is a named constraint
  442. // type.
  443. if (named_constraint_info.has_parameters()) {
  444. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  445. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  446. }
  447. // A non-parameterized named constraint declaration evaluates to a declared
  448. // facet type containing just the named constraint.
  449. return ConstantEvalResult::NewAnyPhase(FacetTypeFromNamedConstraint(
  450. context, inst.named_constraint_id,
  451. context.generics().GetSelfSpecific(named_constraint_info.generic_id)));
  452. }
  453. auto EvalConstantInst(Context& context, SemIR::NameRef inst)
  454. -> ConstantEvalResult {
  455. // A name reference evaluates to the value the name resolves to.
  456. return ConstantEvalResult::Existing(
  457. context.constant_values().Get(inst.value_id));
  458. }
  459. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  460. SemIR::RequireCompleteType inst) -> ConstantEvalResult {
  461. auto witness_type_id =
  462. GetSingletonType(context, SemIR::WitnessType::TypeInstId);
  463. // If the type is a concrete constant, require it to be complete now.
  464. auto complete_type_id =
  465. context.types().GetTypeIdForTypeInstId(inst.complete_type_inst_id);
  466. if (complete_type_id.is_concrete()) {
  467. Diagnostics::ContextScope diagnostic_context(
  468. &context.emitter(), [&](auto& builder) {
  469. CARBON_DIAGNOSTIC(IncompleteTypeInMonomorphization, Context,
  470. "{0} evaluates to incomplete type {1}",
  471. InstIdAsType, InstIdAsType);
  472. builder.Context(inst_id, IncompleteTypeInMonomorphization,
  473. context.insts()
  474. .GetAs<SemIR::RequireCompleteType>(inst_id)
  475. .complete_type_inst_id,
  476. inst.complete_type_inst_id);
  477. });
  478. // We use TryToCompleteType() instead of RequireCompleteType() because we
  479. // are currently evaluating a RequireCompleteType instruction, and calling
  480. // RequireCompleteType() would insert another copy of the same instruction.
  481. if (!TryToCompleteType(context, complete_type_id, SemIR::LocId(inst_id),
  482. true)) {
  483. return ConstantEvalResult::Error;
  484. }
  485. return ConstantEvalResult::NewSamePhase(SemIR::CompleteTypeWitness{
  486. .type_id = witness_type_id,
  487. .object_repr_type_inst_id = context.types().GetTypeInstId(
  488. context.types().GetObjectRepr(complete_type_id))});
  489. }
  490. // If it's not a concrete constant, require it to be complete once it
  491. // becomes one.
  492. return ConstantEvalResult::NewSamePhase(inst);
  493. }
  494. auto EvalConstantInst(Context& context, SemIR::RequireSpecificDefinition inst)
  495. -> ConstantEvalResult {
  496. // This can return false, we just need to try it.
  497. ResolveSpecificDefinition(context, SemIR::LocId::None, inst.specific_id);
  498. return ConstantEvalResult::NewSamePhase(inst);
  499. }
  500. auto EvalConstantInst(Context& context, SemIR::SpecificConstant inst)
  501. -> ConstantEvalResult {
  502. // Pull the constant value out of the specific.
  503. return ConstantEvalResult::Existing(SemIR::GetConstantValueInSpecific(
  504. context.sem_ir(), inst.specific_id, inst.inst_id));
  505. }
  506. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  507. SemIR::SpecificImplFunction inst) -> ConstantEvalResult {
  508. auto callee_inst = context.insts().Get(inst.callee_id);
  509. // If the callee is not a function value, we're not ready to evaluate this
  510. // yet. Build a symbolic `SpecificImplFunction` constant.
  511. if (!callee_inst.Is<SemIR::StructValue>()) {
  512. return ConstantEvalResult::NewSamePhase(inst);
  513. }
  514. auto callee_type_id = callee_inst.type_id();
  515. auto callee_fn_type =
  516. context.types().TryGetAs<SemIR::FunctionType>(callee_type_id);
  517. if (!callee_fn_type) {
  518. return ConstantEvalResult::NewSamePhase(inst);
  519. }
  520. // If the callee function found in the impl witness is not generic, the result
  521. // is simply that function.
  522. // TODO: We could do this even before the callee is concrete.
  523. auto generic_id =
  524. context.functions().Get(callee_fn_type->function_id).generic_id;
  525. if (!generic_id.has_value()) {
  526. return ConstantEvalResult::Existing(
  527. context.constant_values().Get(inst.callee_id));
  528. }
  529. // Find the arguments to use.
  530. auto enclosing_specific_id = callee_fn_type->specific_id;
  531. auto enclosing_args = context.inst_blocks().Get(
  532. context.specifics().GetArgsOrEmpty(enclosing_specific_id));
  533. auto interface_fn_args = context.inst_blocks().Get(
  534. context.specifics().GetArgsOrEmpty(inst.specific_id));
  535. // Form new specific for the generic callee function. The arguments for this
  536. // specific are the enclosing arguments of the callee followed by the
  537. // remaining arguments from the interface function. Impl checking has ensured
  538. // that these arguments can also be used for the function in the impl witness.
  539. auto num_params = context.inst_blocks()
  540. .Get(context.generics().Get(generic_id).bindings_id)
  541. .size();
  542. llvm::SmallVector<SemIR::InstId> args;
  543. args.reserve(num_params);
  544. args.append(enclosing_args.begin(), enclosing_args.end());
  545. int remaining_params = num_params - args.size();
  546. CARBON_CHECK(static_cast<int>(interface_fn_args.size()) >= remaining_params);
  547. args.append(interface_fn_args.end() - remaining_params,
  548. interface_fn_args.end());
  549. auto specific_id =
  550. MakeSpecific(context, SemIR::LocId(inst_id), generic_id, args);
  551. context.definitions_required_by_use().push_back(
  552. {SemIR::LocId(inst_id), specific_id});
  553. return ConstantEvalResult::NewSamePhase(
  554. SemIR::SpecificFunction{.type_id = inst.type_id,
  555. .callee_id = inst.callee_id,
  556. .specific_id = specific_id});
  557. }
  558. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  559. SemIR::SpecificFunction inst) -> ConstantEvalResult {
  560. auto callee_function =
  561. SemIR::GetCalleeAsFunction(context.sem_ir(), inst.callee_id);
  562. const auto& fn = context.functions().Get(callee_function.function_id);
  563. if (!callee_function.self_type_id.has_value() &&
  564. fn.builtin_function_kind() != SemIR::BuiltinFunctionKind::NoOp &&
  565. fn.virtual_modifier != SemIR::Function::VirtualModifier::Abstract) {
  566. // This is not an associated function. Those will be required to be defined
  567. // as part of checking that the impl is complete.
  568. context.definitions_required_by_use().push_back(
  569. {SemIR::LocId(inst_id), inst.specific_id});
  570. }
  571. // Create new constant for a specific function.
  572. return ConstantEvalResult::NewSamePhase(inst);
  573. }
  574. auto EvalConstantInst(Context& context, SemIR::SpliceBlock inst)
  575. -> ConstantEvalResult {
  576. // SpliceBlock evaluates to the result value that is (typically) within the
  577. // block. This can be constant even if the block contains other non-constant
  578. // instructions.
  579. return ConstantEvalResult::Existing(
  580. context.constant_values().Get(inst.result_id));
  581. }
  582. auto EvalConstantInst(Context& context, SemIR::SpliceInst inst)
  583. -> ConstantEvalResult {
  584. // The constant value of a SpliceInst is the constant value of the instruction
  585. // being spliced. Note that `inst.inst_id` is the instruction being spliced,
  586. // so we need to go through another round of obtaining the constant value in
  587. // addition to the one performed by the eval infrastructure.
  588. if (auto inst_value =
  589. context.insts().TryGetAs<SemIR::InstValue>(inst.inst_id)) {
  590. return ConstantEvalResult::Existing(
  591. context.constant_values().Get(inst_value->inst_id));
  592. }
  593. // TODO: Consider creating a new `ValueOfInst` instruction analogous to
  594. // `TypeOfInst` to defer determining the constant value until we know the
  595. // instruction. Alternatively, produce a symbolic `SpliceInst` constant.
  596. return ConstantEvalResult::NotConstant;
  597. }
  598. auto EvalConstantInst(Context& context, SemIR::StructAccess inst)
  599. -> ConstantEvalResult {
  600. return PerformAggregateAccess(context, inst);
  601. }
  602. auto EvalConstantInst(Context& /*context*/, SemIR::StructInit inst)
  603. -> ConstantEvalResult {
  604. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  605. .type_id = inst.type_id, .elements_id = inst.elements_id});
  606. }
  607. auto EvalConstantInst(Context& /*context*/, SemIR::StructLiteral inst)
  608. -> ConstantEvalResult {
  609. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  610. .type_id = inst.type_id, .elements_id = inst.elements_id});
  611. }
  612. auto EvalConstantInst(Context& /*context*/, SemIR::Temporary /*inst*/)
  613. -> ConstantEvalResult {
  614. // TODO: Handle this. Can we just return the value of `init_id`?
  615. return ConstantEvalResult::TODO;
  616. }
  617. auto EvalConstantInst(Context& context, SemIR::TupleAccess inst)
  618. -> ConstantEvalResult {
  619. return PerformAggregateAccess(context, inst);
  620. }
  621. auto EvalConstantInst(Context& /*context*/, SemIR::TupleInit inst)
  622. -> ConstantEvalResult {
  623. return ConstantEvalResult::NewSamePhase(SemIR::TupleValue{
  624. .type_id = inst.type_id, .elements_id = inst.elements_id});
  625. }
  626. auto EvalConstantInst(Context& /*context*/, SemIR::TupleLiteral inst)
  627. -> ConstantEvalResult {
  628. return ConstantEvalResult::NewSamePhase(SemIR::TupleValue{
  629. .type_id = inst.type_id, .elements_id = inst.elements_id});
  630. }
  631. auto EvalConstantInst(Context& context, SemIR::TypeComponentOf inst)
  632. -> ConstantEvalResult {
  633. auto form_constant_inst_id =
  634. context.constant_values().GetConstantInstId(inst.form_inst_id);
  635. if (auto primitive_form = context.insts().TryGetAs<SemIR::AnyPrimitiveForm>(
  636. form_constant_inst_id)) {
  637. return ConstantEvalResult::Existing(
  638. context.constant_values().Get(primitive_form->type_component_id));
  639. }
  640. return ConstantEvalResult::NewSamePhase(inst);
  641. }
  642. auto EvalConstantInst(Context& context, SemIR::TypeLiteral inst)
  643. -> ConstantEvalResult {
  644. return ConstantEvalResult::Existing(
  645. context.constant_values().Get(inst.value_id));
  646. }
  647. auto EvalConstantInst(Context& context, SemIR::TypeOfInst inst)
  648. -> ConstantEvalResult {
  649. // Grab the type from the instruction produced as our operand.
  650. if (auto inst_value =
  651. context.insts().TryGetAs<SemIR::InstValue>(inst.inst_id)) {
  652. return ConstantEvalResult::Existing(context.types().GetConstantId(
  653. context.insts().Get(inst_value->inst_id).type_id()));
  654. }
  655. return ConstantEvalResult::NewSamePhase(inst);
  656. }
  657. auto EvalConstantInst(Context& context, SemIR::UnaryOperatorNot inst)
  658. -> ConstantEvalResult {
  659. // `not true` -> `false`, `not false` -> `true`.
  660. // All other uses of unary `not` are non-constant.
  661. auto const_id = context.constant_values().Get(inst.operand_id);
  662. if (const_id.is_concrete()) {
  663. auto value = context.insts().GetAs<SemIR::BoolLiteral>(
  664. context.constant_values().GetInstId(const_id));
  665. value.value = SemIR::BoolValue::From(!value.value.ToBool());
  666. return ConstantEvalResult::NewSamePhase(value);
  667. }
  668. return ConstantEvalResult::NotConstant;
  669. }
  670. auto EvalConstantInst(Context& /*context*/, SemIR::UpdateInit /*inst*/)
  671. -> ConstantEvalResult {
  672. // TODO: Support folding together a ClassInit with an update that sets the
  673. // vptr.
  674. return ConstantEvalResult::TODO;
  675. }
  676. auto EvalConstantInst(Context& context, SemIR::ValueOfInitializer inst)
  677. -> ConstantEvalResult {
  678. // Values of value expressions and initializing expressions are represented in
  679. // the same way during constant evaluation, so just return the value of the
  680. // operand.
  681. return ConstantEvalResult::Existing(
  682. context.constant_values().Get(inst.init_id));
  683. }
  684. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  685. SemIR::VarStorage inst) -> ConstantEvalResult {
  686. if (!inst.pattern_id.has_value()) {
  687. // This variable was not created from a `var` pattern, so isn't a global
  688. // variable.
  689. return ConstantEvalResult::NotConstant;
  690. }
  691. // A variable is constant if it's global.
  692. auto entity_name_id = SemIR::GetFirstBindingNameFromPatternId(
  693. context.sem_ir(), inst.pattern_id);
  694. if (!entity_name_id.has_value()) {
  695. // Variable doesn't introduce any bindings, so can only be referenced by its
  696. // own initializer. We treat such a reference as not being constant.
  697. return ConstantEvalResult::NotConstant;
  698. }
  699. auto scope_id = context.entity_names().Get(entity_name_id).parent_scope_id;
  700. if (!scope_id.has_value()) {
  701. return ConstantEvalResult::NotConstant;
  702. }
  703. auto scope_inst =
  704. context.insts().Get(context.name_scopes().Get(scope_id).inst_id());
  705. if (!scope_inst.Is<SemIR::Namespace>() &&
  706. !scope_inst.Is<SemIR::ClassDecl>()) {
  707. // Only namespace-scope and class-scope variables are reference constants.
  708. // Class-scope variables cannot currently be declared directly, but can
  709. // occur when static data members are imported from C++.
  710. return ConstantEvalResult::NotConstant;
  711. }
  712. // This is a constant reference expression denoting this global variable.
  713. return ConstantEvalResult::Existing(
  714. SemIR::ConstantId::ForConcreteConstant(inst_id));
  715. }
  716. } // namespace Carbon::Check