eval_inst.cpp 26 KB

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