eval_inst.cpp 34 KB

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