eval_inst.cpp 35 KB

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