eval_inst.cpp 22 KB

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