eval_inst.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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/check/action.h"
  7. #include "toolchain/check/diagnostic_helpers.h"
  8. #include "toolchain/check/facet_type.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/check/impl_lookup.h"
  11. #include "toolchain/check/import_ref.h"
  12. #include "toolchain/check/inst.h"
  13. #include "toolchain/check/type.h"
  14. #include "toolchain/check/type_completion.h"
  15. #include "toolchain/diagnostics/diagnostic.h"
  16. #include "toolchain/sem_ir/expr_info.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/pattern.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::Check {
  21. // Performs an access into an aggregate, retrieving the specified element.
  22. static auto PerformAggregateAccess(Context& context, SemIR::Inst inst)
  23. -> ConstantEvalResult {
  24. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  25. if (auto aggregate = context.insts().TryGetAs<SemIR::AnyAggregateValue>(
  26. access_inst.aggregate_id)) {
  27. auto elements = context.inst_blocks().Get(aggregate->elements_id);
  28. auto index = static_cast<size_t>(access_inst.index.index);
  29. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  30. // `Phase` is not used here. If this element is a concrete constant, then
  31. // so is the result of indexing, even if the aggregate also contains a
  32. // symbolic context.
  33. return ConstantEvalResult::Existing(
  34. context.constant_values().Get(elements[index]));
  35. }
  36. return ConstantEvalResult::NewSamePhase(inst);
  37. }
  38. auto EvalConstantInst(Context& /*context*/, SemIR::ArrayInit inst)
  39. -> ConstantEvalResult {
  40. // TODO: Add an `ArrayValue` to represent a constant array object
  41. // representation instead of using a `TupleValue`.
  42. return ConstantEvalResult::NewSamePhase(
  43. SemIR::TupleValue{.type_id = inst.type_id, .elements_id = inst.inits_id});
  44. }
  45. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  46. SemIR::ArrayType inst) -> ConstantEvalResult {
  47. auto bound_inst = context.insts().Get(inst.bound_id);
  48. auto int_bound = bound_inst.TryAs<SemIR::IntValue>();
  49. if (!int_bound) {
  50. CARBON_CHECK(context.constant_values().Get(inst.bound_id).is_symbolic(),
  51. "Unexpected inst {0} for template constant int", bound_inst);
  52. return ConstantEvalResult::NewSamePhase(inst);
  53. }
  54. // TODO: We should check that the size of the resulting array type
  55. // fits in 64 bits, not just that the bound does. Should we use a
  56. // 32-bit limit for 32-bit targets?
  57. const auto& bound_val = context.ints().Get(int_bound->int_id);
  58. if (context.types().IsSignedInt(int_bound->type_id) &&
  59. bound_val.isNegative()) {
  60. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  61. "array bound of {0} is negative", TypedInt);
  62. context.emitter().Emit(
  63. context.insts().GetAs<SemIR::ArrayType>(inst_id).bound_id,
  64. ArrayBoundNegative, {.type = int_bound->type_id, .value = bound_val});
  65. return ConstantEvalResult::Error;
  66. }
  67. if (bound_val.getActiveBits() > 64) {
  68. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  69. "array bound of {0} is too large", TypedInt);
  70. context.emitter().Emit(
  71. context.insts().GetAs<SemIR::ArrayType>(inst_id).bound_id,
  72. ArrayBoundTooLarge, {.type = int_bound->type_id, .value = bound_val});
  73. return ConstantEvalResult::Error;
  74. }
  75. return ConstantEvalResult::NewSamePhase(inst);
  76. }
  77. auto EvalConstantInst(Context& context, SemIR::AsCompatible inst)
  78. -> ConstantEvalResult {
  79. // AsCompatible changes the type of the source instruction; its constant
  80. // value, if there is one, needs to be modified to be of the same type.
  81. auto value_id = context.constant_values().Get(inst.source_id);
  82. CARBON_CHECK(value_id.is_constant());
  83. auto value_inst =
  84. context.insts().Get(context.constant_values().GetInstId(value_id));
  85. value_inst.SetType(inst.type_id);
  86. return ConstantEvalResult::NewAnyPhase(value_inst);
  87. }
  88. auto EvalConstantInst(Context& context, SemIR::BindAlias inst)
  89. -> ConstantEvalResult {
  90. // An alias evaluates to the value it's bound to.
  91. return ConstantEvalResult::Existing(
  92. context.constant_values().Get(inst.value_id));
  93. }
  94. auto EvalConstantInst(Context& context, SemIR::BindName inst)
  95. -> ConstantEvalResult {
  96. // A reference binding evaluates to the value it's bound to.
  97. if (inst.value_id.has_value() && SemIR::IsRefCategory(SemIR::GetExprCategory(
  98. context.sem_ir(), inst.value_id))) {
  99. return ConstantEvalResult::Existing(
  100. context.constant_values().Get(inst.value_id));
  101. }
  102. // Non-`:!` value bindings are not constant.
  103. return ConstantEvalResult::NotConstant;
  104. }
  105. auto EvalConstantInst(Context& /*context*/, SemIR::BindValue /*inst*/)
  106. -> ConstantEvalResult {
  107. // TODO: Handle this once we've decided how to represent constant values of
  108. // reference expressions.
  109. return ConstantEvalResult::TODO;
  110. }
  111. auto EvalConstantInst(Context& context, SemIR::ClassElementAccess inst)
  112. -> ConstantEvalResult {
  113. return PerformAggregateAccess(context, inst);
  114. }
  115. auto EvalConstantInst(Context& context, SemIR::ClassDecl inst)
  116. -> ConstantEvalResult {
  117. const auto& class_info = context.classes().Get(inst.class_id);
  118. // If the class has generic parameters, we don't produce a class type, but a
  119. // callable whose return value is a class type.
  120. if (class_info.has_parameters()) {
  121. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  122. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  123. }
  124. // A non-generic class declaration evaluates to the class type.
  125. return ConstantEvalResult::NewAnyPhase(SemIR::ClassType{
  126. .type_id = SemIR::TypeType::TypeId,
  127. .class_id = inst.class_id,
  128. .specific_id =
  129. context.generics().GetSelfSpecific(class_info.generic_id)});
  130. }
  131. auto EvalConstantInst(Context& /*context*/, SemIR::ClassInit inst)
  132. -> ConstantEvalResult {
  133. // TODO: Add a `ClassValue` to represent a constant class object
  134. // representation instead of using a `StructValue`.
  135. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  136. .type_id = inst.type_id, .elements_id = inst.elements_id});
  137. }
  138. auto EvalConstantInst(Context& context, SemIR::ConstType inst)
  139. -> ConstantEvalResult {
  140. // `const (const T)` evaluates to `const T`.
  141. if (context.insts().Is<SemIR::ConstType>(inst.inner_id)) {
  142. return ConstantEvalResult::Existing(
  143. context.constant_values().Get(inst.inner_id));
  144. }
  145. // Otherwise, `const T` evaluates to itself.
  146. return ConstantEvalResult::NewSamePhase(inst);
  147. }
  148. auto EvalConstantInst(Context& context, SemIR::Converted inst)
  149. -> ConstantEvalResult {
  150. // A conversion evaluates to the result of the conversion.
  151. return ConstantEvalResult::Existing(
  152. context.constant_values().Get(inst.result_id));
  153. }
  154. auto EvalConstantInst(Context& /*context*/, SemIR::Deref /*inst*/)
  155. -> ConstantEvalResult {
  156. // TODO: Handle this.
  157. return ConstantEvalResult::TODO;
  158. }
  159. auto EvalConstantInst(Context& context, SemIR::ExportDecl inst)
  160. -> ConstantEvalResult {
  161. // An export instruction evaluates to the exported declaration.
  162. return ConstantEvalResult::Existing(
  163. context.constant_values().Get(inst.value_id));
  164. }
  165. auto EvalConstantInst(Context& context, SemIR::FacetAccessType inst)
  166. -> ConstantEvalResult {
  167. if (auto facet_value = context.insts().TryGetAs<SemIR::FacetValue>(
  168. inst.facet_value_inst_id)) {
  169. return ConstantEvalResult::Existing(
  170. context.constant_values().Get(facet_value->type_inst_id));
  171. }
  172. return ConstantEvalResult::NewSamePhase(inst);
  173. }
  174. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  175. SemIR::FloatType inst) -> ConstantEvalResult {
  176. return ValidateFloatType(context, SemIR::LocId(inst_id), inst)
  177. ? ConstantEvalResult::NewSamePhase(inst)
  178. : ConstantEvalResult::Error;
  179. }
  180. auto EvalConstantInst(Context& /*context*/, SemIR::FunctionDecl inst)
  181. -> ConstantEvalResult {
  182. // A function declaration evaluates to a function object, which is an empty
  183. // object of function type.
  184. // TODO: Eventually we may need to handle captures here.
  185. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  186. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  187. }
  188. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  189. SemIR::LookupImplWitness inst) -> ConstantEvalResult {
  190. // The self value is canonicalized in order to produce a canonical
  191. // LookupImplWitness instruction. We save the non-canonical instruction as it
  192. // may be a concrete `FacetValue` that contains a concrete witness.
  193. auto non_canonical_query_self_inst_id = inst.query_self_inst_id;
  194. inst.query_self_inst_id =
  195. GetCanonicalizedFacetOrTypeValue(context, inst.query_self_inst_id);
  196. auto result = EvalLookupSingleImplWitness(
  197. context, SemIR::LocId(inst_id), inst, non_canonical_query_self_inst_id,
  198. /*poison_concrete_results=*/true);
  199. if (!result.has_value()) {
  200. // We use NotConstant to communicate back to impl lookup that the lookup
  201. // failed. This can not happen for a deferred symbolic lookup in a generic
  202. // eval block, since we only add the deferred lookup instruction (being
  203. // evaluated here) to the SemIR if the lookup succeeds.
  204. return ConstantEvalResult::NotConstant;
  205. }
  206. if (!result.has_concrete_value()) {
  207. return ConstantEvalResult::NewSamePhase(inst);
  208. }
  209. return ConstantEvalResult::Existing(
  210. context.constant_values().Get(result.concrete_witness()));
  211. }
  212. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  213. SemIR::ImplWitnessAccess inst) -> ConstantEvalResult {
  214. if (auto witness =
  215. context.insts().TryGetAs<SemIR::ImplWitness>(inst.witness_id)) {
  216. // This is PerformAggregateAccess followed by GetConstantValueInSpecific.
  217. auto witness_table = context.insts().GetAs<SemIR::ImplWitnessTable>(
  218. witness->witness_table_id);
  219. auto elements = context.inst_blocks().Get(witness_table.elements_id);
  220. // `elements` can be empty if there is only a forward declaration of the
  221. // impl.
  222. if (!elements.empty()) {
  223. auto index = static_cast<size_t>(inst.index.index);
  224. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  225. auto element = elements[index];
  226. if (element.has_value()) {
  227. LoadImportRef(context, element);
  228. return ConstantEvalResult::Existing(GetConstantValueInSpecific(
  229. context.sem_ir(), witness->specific_id, element));
  230. }
  231. }
  232. CARBON_DIAGNOSTIC(
  233. ImplAccessMemberBeforeSet, Error,
  234. "accessing member from impl before it has a defined value");
  235. // TODO: Add note pointing to the impl declaration.
  236. context.emitter().Emit(inst_id, ImplAccessMemberBeforeSet);
  237. return ConstantEvalResult::Error;
  238. } else if (auto witness = context.insts().TryGetAs<SemIR::LookupImplWitness>(
  239. inst.witness_id)) {
  240. // If the witness is symbolic but has a self type that is a FacetType, it
  241. // can pull rewrite values from the self type. If the access is for one of
  242. // those rewrites, evaluate to the RHS of the rewrite.
  243. auto witness_self_type_id =
  244. context.insts().Get(witness->query_self_inst_id).type_id();
  245. if (!context.types().Is<SemIR::FacetType>(witness_self_type_id)) {
  246. return ConstantEvalResult::NewSamePhase(inst);
  247. }
  248. // The `ImplWitnessAccess` is accessing a value, by index, for this
  249. // interface.
  250. auto access_interface_id = witness->query_specific_interface_id;
  251. auto witness_self_facet_type_id =
  252. context.types()
  253. .GetAs<SemIR::FacetType>(witness_self_type_id)
  254. .facet_type_id;
  255. // TODO: We could consider something better than linear search here, such as
  256. // a map. However that would probably require heap allocations which may be
  257. // worse overall since the number of rewrite constraints is generally low.
  258. // If the `rewrite_constraints` were sorted so that associated constants are
  259. // grouped together, as in ResolveFacetTypeRewriteConstraints(), and limited
  260. // to just the `ImplWitnessAccess` entries, then a binary search may work
  261. // here.
  262. for (auto witness_rewrite : context.facet_types()
  263. .Get(witness_self_facet_type_id)
  264. .rewrite_constraints) {
  265. // Look at each rewrite constraint in the self facet value's type. If the
  266. // LHS is an `ImplWitnessAccess` into the same interface that `inst` is
  267. // indexing into, then we can use its RHS as the value.
  268. auto witness_rewrite_lhs_access =
  269. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(
  270. witness_rewrite.lhs_id);
  271. if (!witness_rewrite_lhs_access) {
  272. continue;
  273. }
  274. if (witness_rewrite_lhs_access->index != inst.index) {
  275. continue;
  276. }
  277. auto witness_rewrite_lhs_interface_id =
  278. context.insts()
  279. .GetAs<SemIR::LookupImplWitness>(
  280. witness_rewrite_lhs_access->witness_id)
  281. .query_specific_interface_id;
  282. if (witness_rewrite_lhs_interface_id != access_interface_id) {
  283. continue;
  284. }
  285. // The `ImplWitnessAccess` evaluates to the RHS from the witness self
  286. // facet value's type.
  287. return ConstantEvalResult::Existing(
  288. context.constant_values().Get(witness_rewrite.rhs_id));
  289. }
  290. }
  291. return ConstantEvalResult::NewSamePhase(inst);
  292. }
  293. auto EvalConstantInst(Context& context,
  294. SemIR::ImplWitnessAssociatedConstant inst)
  295. -> ConstantEvalResult {
  296. return ConstantEvalResult::Existing(
  297. context.constant_values().Get(inst.inst_id));
  298. }
  299. auto EvalConstantInst(Context& /*context*/, SemIR::ImportRefUnloaded inst)
  300. -> ConstantEvalResult {
  301. CARBON_FATAL("ImportRefUnloaded should be loaded before TryEvalInst: {0}",
  302. inst);
  303. }
  304. auto EvalConstantInst(Context& context, SemIR::InitializeFrom inst)
  305. -> ConstantEvalResult {
  306. // Initialization is not performed in-place during constant evaluation, so
  307. // just return the value of the initializer.
  308. return ConstantEvalResult::Existing(
  309. context.constant_values().Get(inst.src_id));
  310. }
  311. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  312. SemIR::IntType inst) -> ConstantEvalResult {
  313. return ValidateIntType(context, SemIR::LocId(inst_id), inst)
  314. ? ConstantEvalResult::NewSamePhase(inst)
  315. : ConstantEvalResult::Error;
  316. }
  317. auto EvalConstantInst(Context& context, SemIR::InterfaceDecl inst)
  318. -> ConstantEvalResult {
  319. const auto& interface_info = context.interfaces().Get(inst.interface_id);
  320. // If the interface has generic parameters, we don't produce an interface
  321. // type, but a callable whose return value is an interface type.
  322. if (interface_info.has_parameters()) {
  323. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  324. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  325. }
  326. // A non-parameterized interface declaration evaluates to a facet type.
  327. return ConstantEvalResult::NewAnyPhase(FacetTypeFromInterface(
  328. context, inst.interface_id,
  329. context.generics().GetSelfSpecific(interface_info.generic_id)));
  330. }
  331. auto EvalConstantInst(Context& context, SemIR::NameRef inst)
  332. -> ConstantEvalResult {
  333. // A name reference evaluates to the value the name resolves to.
  334. return ConstantEvalResult::Existing(
  335. context.constant_values().Get(inst.value_id));
  336. }
  337. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  338. SemIR::RequireCompleteType inst) -> ConstantEvalResult {
  339. auto witness_type_id =
  340. GetSingletonType(context, SemIR::WitnessType::TypeInstId);
  341. // If the type is a concrete constant, require it to be complete now.
  342. auto complete_type_id =
  343. context.types().GetTypeIdForTypeInstId(inst.complete_type_inst_id);
  344. if (complete_type_id.is_concrete()) {
  345. if (!TryToCompleteType(
  346. context, complete_type_id, SemIR::LocId(inst_id), [&] {
  347. CARBON_DIAGNOSTIC(IncompleteTypeInMonomorphization, Error,
  348. "{0} evaluates to incomplete type {1}",
  349. InstIdAsType, InstIdAsType);
  350. return context.emitter().Build(
  351. inst_id, IncompleteTypeInMonomorphization,
  352. context.insts()
  353. .GetAs<SemIR::RequireCompleteType>(inst_id)
  354. .complete_type_inst_id,
  355. inst.complete_type_inst_id);
  356. })) {
  357. return ConstantEvalResult::Error;
  358. }
  359. return ConstantEvalResult::NewSamePhase(SemIR::CompleteTypeWitness{
  360. .type_id = witness_type_id,
  361. .object_repr_type_inst_id = context.types().GetInstId(
  362. context.types().GetObjectRepr(complete_type_id))});
  363. }
  364. // If it's not a concrete constant, require it to be complete once it
  365. // becomes one.
  366. return ConstantEvalResult::NewSamePhase(inst);
  367. }
  368. auto EvalConstantInst(Context& context, SemIR::SpecificConstant inst)
  369. -> ConstantEvalResult {
  370. // Pull the constant value out of the specific.
  371. return ConstantEvalResult::Existing(SemIR::GetConstantValueInSpecific(
  372. context.sem_ir(), inst.specific_id, inst.inst_id));
  373. }
  374. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  375. SemIR::SpecificImplFunction inst) -> ConstantEvalResult {
  376. auto callee_inst = context.insts().Get(inst.callee_id);
  377. // If the callee is not a function value, we're not ready to evaluate this
  378. // yet. Build a symbolic `SpecificImplFunction` constant.
  379. if (!callee_inst.Is<SemIR::StructValue>()) {
  380. return ConstantEvalResult::NewSamePhase(inst);
  381. }
  382. auto callee_type_id = callee_inst.type_id();
  383. auto callee_fn_type =
  384. context.types().TryGetAs<SemIR::FunctionType>(callee_type_id);
  385. if (!callee_fn_type) {
  386. return ConstantEvalResult::NewSamePhase(inst);
  387. }
  388. // If the callee function found in the impl witness is not generic, the result
  389. // is simply that function.
  390. // TODO: We could do this even before the callee is concrete.
  391. auto generic_id =
  392. context.functions().Get(callee_fn_type->function_id).generic_id;
  393. if (!generic_id.has_value()) {
  394. return ConstantEvalResult::Existing(
  395. context.constant_values().Get(inst.callee_id));
  396. }
  397. // Find the arguments to use.
  398. auto enclosing_specific_id = callee_fn_type->specific_id;
  399. auto enclosing_args = context.inst_blocks().Get(
  400. context.specifics().GetArgsOrEmpty(enclosing_specific_id));
  401. auto interface_fn_args = context.inst_blocks().Get(
  402. context.specifics().GetArgsOrEmpty(inst.specific_id));
  403. // Form new specific for the generic callee function. The arguments for this
  404. // specific are the enclosing arguments of the callee followed by the
  405. // remaining arguments from the interface function. Impl checking has ensured
  406. // that these arguments can also be used for the function in the impl witness.
  407. auto num_params = context.inst_blocks()
  408. .Get(context.generics().Get(generic_id).bindings_id)
  409. .size();
  410. llvm::SmallVector<SemIR::InstId> args;
  411. args.reserve(num_params);
  412. args.append(enclosing_args.begin(), enclosing_args.end());
  413. int remaining_params = num_params - args.size();
  414. CARBON_CHECK(static_cast<int>(interface_fn_args.size()) >= remaining_params);
  415. args.append(interface_fn_args.end() - remaining_params,
  416. interface_fn_args.end());
  417. auto specific_id =
  418. MakeSpecific(context, SemIR::LocId(inst_id), generic_id, args);
  419. context.definitions_required_by_use().push_back(
  420. {SemIR::LocId(inst_id), specific_id});
  421. return ConstantEvalResult::NewSamePhase(
  422. SemIR::SpecificFunction{.type_id = inst.type_id,
  423. .callee_id = inst.callee_id,
  424. .specific_id = specific_id});
  425. }
  426. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  427. SemIR::SpecificFunction inst) -> ConstantEvalResult {
  428. if (!SemIR::GetCalleeFunction(context.sem_ir(), inst.callee_id)
  429. .self_type_id.has_value()) {
  430. // This is not an associated function. Those will be required to be defined
  431. // as part of checking that the impl is complete.
  432. context.definitions_required_by_use().push_back(
  433. {SemIR::LocId(inst_id), inst.specific_id});
  434. }
  435. // Create new constant for a specific function.
  436. return ConstantEvalResult::NewSamePhase(inst);
  437. }
  438. auto EvalConstantInst(Context& context, SemIR::SpliceBlock inst)
  439. -> ConstantEvalResult {
  440. // SpliceBlock evaluates to the result value that is (typically) within the
  441. // block. This can be constant even if the block contains other non-constant
  442. // instructions.
  443. return ConstantEvalResult::Existing(
  444. context.constant_values().Get(inst.result_id));
  445. }
  446. auto EvalConstantInst(Context& context, SemIR::SpliceInst inst)
  447. -> ConstantEvalResult {
  448. // The constant value of a SpliceInst is the constant value of the instruction
  449. // being spliced. Note that `inst.inst_id` is the instruction being spliced,
  450. // so we need to go through another round of obtaining the constant value in
  451. // addition to the one performed by the eval infrastructure.
  452. if (auto inst_value =
  453. context.insts().TryGetAs<SemIR::InstValue>(inst.inst_id)) {
  454. return ConstantEvalResult::Existing(
  455. context.constant_values().Get(inst_value->inst_id));
  456. }
  457. // TODO: Consider creating a new `ValueOfInst` instruction analogous to
  458. // `TypeOfInst` to defer determining the constant value until we know the
  459. // instruction. Alternatively, produce a symbolic `SpliceInst` constant.
  460. return ConstantEvalResult::NotConstant;
  461. }
  462. auto EvalConstantInst(Context& context, SemIR::StructAccess inst)
  463. -> ConstantEvalResult {
  464. return PerformAggregateAccess(context, inst);
  465. }
  466. auto EvalConstantInst(Context& /*context*/, SemIR::StructInit inst)
  467. -> ConstantEvalResult {
  468. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  469. .type_id = inst.type_id, .elements_id = inst.elements_id});
  470. }
  471. auto EvalConstantInst(Context& /*context*/, SemIR::Temporary /*inst*/)
  472. -> ConstantEvalResult {
  473. // TODO: Handle this. Can we just return the value of `init_id`?
  474. return ConstantEvalResult::TODO;
  475. }
  476. auto EvalConstantInst(Context& context, SemIR::TupleAccess inst)
  477. -> ConstantEvalResult {
  478. return PerformAggregateAccess(context, inst);
  479. }
  480. auto EvalConstantInst(Context& /*context*/, SemIR::TupleInit inst)
  481. -> ConstantEvalResult {
  482. return ConstantEvalResult::NewSamePhase(SemIR::TupleValue{
  483. .type_id = inst.type_id, .elements_id = inst.elements_id});
  484. }
  485. auto EvalConstantInst(Context& context, SemIR::TypeOfInst inst)
  486. -> ConstantEvalResult {
  487. // Grab the type from the instruction produced as our operand.
  488. if (auto inst_value =
  489. context.insts().TryGetAs<SemIR::InstValue>(inst.inst_id)) {
  490. return ConstantEvalResult::Existing(context.types().GetConstantId(
  491. context.insts().Get(inst_value->inst_id).type_id()));
  492. }
  493. return ConstantEvalResult::NewSamePhase(inst);
  494. }
  495. auto EvalConstantInst(Context& context, SemIR::UnaryOperatorNot inst)
  496. -> ConstantEvalResult {
  497. // `not true` -> `false`, `not false` -> `true`.
  498. // All other uses of unary `not` are non-constant.
  499. auto const_id = context.constant_values().Get(inst.operand_id);
  500. if (const_id.is_concrete()) {
  501. auto value = context.insts().GetAs<SemIR::BoolLiteral>(
  502. context.constant_values().GetInstId(const_id));
  503. value.value = SemIR::BoolValue::From(!value.value.ToBool());
  504. return ConstantEvalResult::NewSamePhase(value);
  505. }
  506. return ConstantEvalResult::NotConstant;
  507. }
  508. auto EvalConstantInst(Context& context, SemIR::ValueOfInitializer inst)
  509. -> ConstantEvalResult {
  510. // Values of value expressions and initializing expressions are represented in
  511. // the same way during constant evaluation, so just return the value of the
  512. // operand.
  513. return ConstantEvalResult::Existing(
  514. context.constant_values().Get(inst.init_id));
  515. }
  516. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  517. SemIR::VarStorage inst) -> ConstantEvalResult {
  518. // A variable is constant if it's global.
  519. auto entity_name_id = SemIR::GetFirstBindingNameFromPatternId(
  520. context.sem_ir(), inst.pattern_id);
  521. if (!entity_name_id.has_value()) {
  522. // Variable doesn't introduce any bindings, so can only be referenced by its
  523. // own initializer. We treat such a reference as not being constant.
  524. return ConstantEvalResult::NotConstant;
  525. }
  526. auto scope_id = context.entity_names().Get(entity_name_id).parent_scope_id;
  527. if (!scope_id.has_value() ||
  528. !context.insts().Is<SemIR::Namespace>(
  529. context.name_scopes().Get(scope_id).inst_id())) {
  530. // Only namespace-scope variables are reference constants.
  531. return ConstantEvalResult::NotConstant;
  532. }
  533. // This is a constant reference expression denoting this global variable.
  534. return ConstantEvalResult::Existing(
  535. SemIR::ConstantId::ForConcreteConstant(inst_id));
  536. }
  537. } // namespace Carbon::Check