eval_inst.cpp 34 KB

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