eval.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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.h"
  5. #include "toolchain/diagnostics/diagnostic_emitter.h"
  6. #include "toolchain/sem_ir/function.h"
  7. #include "toolchain/sem_ir/ids.h"
  8. #include "toolchain/sem_ir/typed_insts.h"
  9. namespace Carbon::Check {
  10. namespace {
  11. // The evaluation phase for an expression, computed by evaluation. These are
  12. // ordered so that the phase of an expression is the numerically highest phase
  13. // of its constituent evaluations. Note that an expression with any runtime
  14. // component is known to have Runtime phase even if it involves an evaluation
  15. // with UnknownDueToError phase.
  16. enum class Phase : uint8_t {
  17. // Value could be entirely and concretely computed.
  18. Template,
  19. // Evaluation phase is symbolic because the expression involves a reference to
  20. // a symbolic binding.
  21. Symbolic,
  22. // The evaluation phase is unknown because evaluation encountered an
  23. // already-diagnosed semantic or syntax error. This is treated as being
  24. // potentially constant, but with an unknown phase.
  25. UnknownDueToError,
  26. // The expression has runtime phase because of a non-constant subexpression.
  27. Runtime,
  28. };
  29. } // namespace
  30. // Gets the phase in which the value of a constant will become available.
  31. static auto GetPhase(SemIR::ConstantId constant_id) -> Phase {
  32. if (!constant_id.is_constant()) {
  33. return Phase::Runtime;
  34. } else if (constant_id == SemIR::ConstantId::Error) {
  35. return Phase::UnknownDueToError;
  36. } else if (constant_id.is_template()) {
  37. return Phase::Template;
  38. } else {
  39. CARBON_CHECK(constant_id.is_symbolic());
  40. return Phase::Symbolic;
  41. }
  42. }
  43. // Returns the later of two phases.
  44. static auto LatestPhase(Phase a, Phase b) -> Phase {
  45. return static_cast<Phase>(
  46. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  47. }
  48. // Forms a `constant_id` describing a given evaluation result.
  49. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  50. -> SemIR::ConstantId {
  51. switch (phase) {
  52. case Phase::Template:
  53. return context.AddConstant(inst, /*is_symbolic=*/false);
  54. case Phase::Symbolic:
  55. return context.AddConstant(inst, /*is_symbolic=*/true);
  56. case Phase::UnknownDueToError:
  57. return SemIR::ConstantId::Error;
  58. case Phase::Runtime:
  59. return SemIR::ConstantId::NotConstant;
  60. }
  61. }
  62. // Forms a `constant_id` describing why an evaluation was not constant.
  63. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  64. return phase == Phase::UnknownDueToError ? SemIR::ConstantId::Error
  65. : SemIR::ConstantId::NotConstant;
  66. }
  67. // `GetConstantValue` checks to see whether the provided ID describes a value
  68. // with constant phase, and if so, returns the corresponding constant value.
  69. // Overloads are provided for different kinds of ID.
  70. // If the given instruction is constant, returns its constant value.
  71. static auto GetConstantValue(Context& context, SemIR::InstId inst_id,
  72. Phase* phase) -> SemIR::InstId {
  73. auto const_id = context.constant_values().Get(inst_id);
  74. *phase = LatestPhase(*phase, GetPhase(const_id));
  75. return const_id.inst_id();
  76. }
  77. // A type is always constant, but we still need to extract its phase.
  78. static auto GetConstantValue(Context& context, SemIR::TypeId type_id,
  79. Phase* phase) -> SemIR::TypeId {
  80. auto const_id = context.types().GetConstantId(type_id);
  81. *phase = LatestPhase(*phase, GetPhase(const_id));
  82. return type_id;
  83. }
  84. // If the given instruction block contains only constants, returns a
  85. // corresponding block of those values.
  86. static auto GetConstantValue(Context& context, SemIR::InstBlockId inst_block_id,
  87. Phase* phase) -> SemIR::InstBlockId {
  88. auto insts = context.inst_blocks().Get(inst_block_id);
  89. llvm::SmallVector<SemIR::InstId> const_insts;
  90. for (auto inst_id : insts) {
  91. auto const_inst_id = GetConstantValue(context, inst_id, phase);
  92. if (!const_inst_id.is_valid()) {
  93. return SemIR::InstBlockId::Invalid;
  94. }
  95. // Once we leave the small buffer, we know the first few elements are all
  96. // constant, so it's likely that the entire block is constant. Resize to the
  97. // target size given that we're going to allocate memory now anyway.
  98. if (const_insts.size() == const_insts.capacity()) {
  99. const_insts.reserve(insts.size());
  100. }
  101. const_insts.push_back(const_inst_id);
  102. }
  103. // TODO: If the new block is identical to the original block, return the
  104. // original ID.
  105. return context.inst_blocks().Add(const_insts);
  106. }
  107. // The constant value of a type block is that type block, but we still need to
  108. // extract its phase.
  109. static auto GetConstantValue(Context& context, SemIR::TypeBlockId type_block_id,
  110. Phase* phase) -> SemIR::TypeBlockId {
  111. auto types = context.type_blocks().Get(type_block_id);
  112. for (auto type_id : types) {
  113. GetConstantValue(context, type_id, phase);
  114. }
  115. return type_block_id;
  116. }
  117. // Replaces the specified field of the given typed instruction with its constant
  118. // value, if it has constant phase. Returns true on success, false if the value
  119. // has runtime phase.
  120. template <typename InstT, typename FieldIdT>
  121. static auto ReplaceFieldWithConstantValue(Context& context, InstT* inst,
  122. FieldIdT InstT::*field, Phase* phase)
  123. -> bool {
  124. auto unwrapped = GetConstantValue(context, inst->*field, phase);
  125. if (!unwrapped.is_valid()) {
  126. return false;
  127. }
  128. inst->*field = unwrapped;
  129. return true;
  130. }
  131. // If the specified fields of the given typed instruction have constant values,
  132. // replaces the fields with their constant values and builds a corresponding
  133. // constant value. Otherwise returns `ConstantId::NotConstant`. Returns
  134. // `ConstantId::Error` if any subexpression is an error.
  135. //
  136. // The constant value is then checked by calling `validate_fn(typed_inst)`,
  137. // which should return a `bool` indicating whether the new constant is valid. If
  138. // validation passes, a corresponding ConstantId for the new constant is
  139. // returned. If validation fails, it should produce a suitable error message.
  140. // `ConstantId::Error` is returned.
  141. template <typename InstT, typename ValidateFn, typename... EachFieldIdT>
  142. static auto RebuildAndValidateIfFieldsAreConstant(
  143. Context& context, SemIR::Inst inst, ValidateFn validate_fn,
  144. EachFieldIdT InstT::*... each_field_id) -> SemIR::ConstantId {
  145. // Build a constant instruction by replacing each non-constant operand with
  146. // its constant value.
  147. auto typed_inst = inst.As<InstT>();
  148. Phase phase = Phase::Template;
  149. if ((ReplaceFieldWithConstantValue(context, &typed_inst, each_field_id,
  150. &phase) &&
  151. ...)) {
  152. if (phase == Phase::UnknownDueToError || !validate_fn(typed_inst)) {
  153. return SemIR::ConstantId::Error;
  154. }
  155. return MakeConstantResult(context, typed_inst, phase);
  156. }
  157. return MakeNonConstantResult(phase);
  158. }
  159. // Same as above but with no validation step.
  160. template <typename InstT, typename... EachFieldIdT>
  161. static auto RebuildIfFieldsAreConstant(Context& context, SemIR::Inst inst,
  162. EachFieldIdT InstT::*... each_field_id)
  163. -> SemIR::ConstantId {
  164. return RebuildAndValidateIfFieldsAreConstant(
  165. context, inst, [](...) { return true; }, each_field_id...);
  166. }
  167. // Rebuilds the given aggregate initialization instruction as a corresponding
  168. // constant aggregate value, if its elements are all constants.
  169. static auto RebuildInitAsValue(Context& context, SemIR::Inst inst,
  170. SemIR::InstKind value_kind)
  171. -> SemIR::ConstantId {
  172. auto init_inst = inst.As<SemIR::AnyAggregateInit>();
  173. Phase phase = Phase::Template;
  174. auto elements_id = GetConstantValue(context, init_inst.elements_id, &phase);
  175. return MakeConstantResult(
  176. context,
  177. SemIR::AnyAggregateValue{.kind = value_kind,
  178. .type_id = init_inst.type_id,
  179. .elements_id = elements_id},
  180. phase);
  181. }
  182. // Performs an access into an aggregate, retrieving the specified element.
  183. static auto PerformAggregateAccess(Context& context, SemIR::Inst inst)
  184. -> SemIR::ConstantId {
  185. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  186. Phase phase = Phase::Template;
  187. if (auto aggregate_id =
  188. GetConstantValue(context, access_inst.aggregate_id, &phase);
  189. aggregate_id.is_valid()) {
  190. if (auto aggregate =
  191. context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id)) {
  192. auto elements = context.inst_blocks().Get(aggregate->elements_id);
  193. auto index = static_cast<size_t>(access_inst.index.index);
  194. CARBON_CHECK(index < elements.size()) << "Access out of bounds.";
  195. // `Phase` is not used here. If this element is a template constant, then
  196. // so is the result of indexing, even if the aggregate also contains a
  197. // symbolic context.
  198. return context.constant_values().Get(elements[index]);
  199. } else {
  200. CARBON_CHECK(phase != Phase::Template)
  201. << "Failed to evaluate template constant " << inst;
  202. }
  203. }
  204. return MakeNonConstantResult(phase);
  205. }
  206. // Performs an index into a homogeneous aggregate, retrieving the specified
  207. // element.
  208. static auto PerformAggregateIndex(Context& context, SemIR::Inst inst)
  209. -> SemIR::ConstantId {
  210. auto index_inst = inst.As<SemIR::AnyAggregateIndex>();
  211. Phase phase = Phase::Template;
  212. auto aggregate_id =
  213. GetConstantValue(context, index_inst.aggregate_id, &phase);
  214. auto index_id = GetConstantValue(context, index_inst.index_id, &phase);
  215. if (!index_id.is_valid()) {
  216. return MakeNonConstantResult(phase);
  217. }
  218. auto index = context.insts().TryGetAs<SemIR::IntLiteral>(index_id);
  219. if (!index) {
  220. CARBON_CHECK(phase != Phase::Template)
  221. << "Template constant integer should be a literal";
  222. return MakeNonConstantResult(phase);
  223. }
  224. // Array indexing is invalid if the index is constant and out of range.
  225. auto aggregate_type_id =
  226. context.insts().Get(index_inst.aggregate_id).type_id();
  227. const auto& index_val = context.ints().Get(index->int_id);
  228. if (auto array_type =
  229. context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  230. if (auto bound =
  231. context.insts().TryGetAs<SemIR::IntLiteral>(array_type->bound_id)) {
  232. // This awkward call to `getZExtValue` is a workaround for APInt not
  233. // supporting comparisons between integers of different bit widths.
  234. if (index_val.getActiveBits() > 64 ||
  235. context.ints().Get(bound->int_id).ule(index_val.getZExtValue())) {
  236. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  237. "Array index `{0}` is past the end of type `{1}`.",
  238. llvm::APSInt, SemIR::TypeId);
  239. context.emitter().Emit(index_inst.index_id, ArrayIndexOutOfBounds,
  240. llvm::APSInt(index_val, /*isUnsigned=*/true),
  241. aggregate_type_id);
  242. return SemIR::ConstantId::Error;
  243. }
  244. }
  245. }
  246. if (!aggregate_id.is_valid()) {
  247. return MakeNonConstantResult(phase);
  248. }
  249. auto aggregate =
  250. context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  251. if (!aggregate) {
  252. CARBON_CHECK(phase != Phase::Template)
  253. << "Unexpected representation for template constant aggregate";
  254. return MakeNonConstantResult(phase);
  255. }
  256. auto elements = context.inst_blocks().Get(aggregate->elements_id);
  257. // We checked this for the array case above.
  258. CARBON_CHECK(index_val.ult(elements.size()))
  259. << "Index out of bounds in tuple indexing";
  260. return context.constant_values().Get(elements[index_val.getZExtValue()]);
  261. }
  262. static auto PerformBuiltinCall(Context& context, SemIRLocation loc,
  263. SemIR::Call call,
  264. SemIR::BuiltinFunctionKind builtin_kind,
  265. llvm::ArrayRef<SemIR::InstId> arg_ids,
  266. Phase phase) -> SemIR::ConstantId {
  267. switch (builtin_kind) {
  268. case SemIR::BuiltinFunctionKind::None:
  269. CARBON_FATAL() << "Not a builtin function.";
  270. case SemIR::BuiltinFunctionKind::IntAdd: {
  271. if (phase != Phase::Template) {
  272. break;
  273. }
  274. if (arg_ids.size() != 2) {
  275. break;
  276. }
  277. auto lhs = context.insts().TryGetAs<SemIR::IntLiteral>(arg_ids[0]);
  278. auto rhs = context.insts().TryGetAs<SemIR::IntLiteral>(arg_ids[1]);
  279. // TODO: Move type checking to the point where we make the call.
  280. if (!lhs || !rhs || lhs->type_id != rhs->type_id ||
  281. call.type_id != lhs->type_id) {
  282. break;
  283. }
  284. // TODO: Integer values should be stored in the correct bit width for
  285. // their types. For now we assume i32.
  286. auto lhs_val = context.ints().Get(lhs->int_id).sextOrTrunc(32);
  287. auto rhs_val = context.ints().Get(rhs->int_id).sextOrTrunc(32);
  288. bool overflow = false;
  289. auto result = context.ints().Add(lhs_val.sadd_ov(rhs_val, overflow));
  290. if (overflow) {
  291. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  292. "Integer overflow in calculation {0} + {1}.",
  293. llvm::APSInt, llvm::APSInt);
  294. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  295. llvm::APSInt(lhs_val, false),
  296. llvm::APSInt(rhs_val, false));
  297. }
  298. return MakeConstantResult(context,
  299. SemIR::IntLiteral{lhs->type_id, result}, phase);
  300. }
  301. }
  302. return SemIR::ConstantId::NotConstant;
  303. }
  304. // Extracts the callee function from a callee constant. Returns
  305. // FunctionId::Invalid if the callee is not known.
  306. static auto GetCalleeFunctionId(Context& context, SemIR::InstId callee_id)
  307. -> SemIR::FunctionId {
  308. if (auto bound_method =
  309. context.insts().TryGetAs<SemIR::BoundMethod>(callee_id)) {
  310. callee_id = bound_method->function_id;
  311. }
  312. if (auto callee = context.insts().TryGetAs<SemIR::FunctionDecl>(callee_id)) {
  313. return {callee->function_id};
  314. }
  315. return {SemIR::FunctionId::Invalid};
  316. }
  317. static auto PerformCall(Context& context, SemIRLocation loc, SemIR::Call call)
  318. -> SemIR::ConstantId {
  319. Phase phase = Phase::Template;
  320. // A call with an invalid argument list is used to represent an erroneous
  321. // call.
  322. //
  323. // TODO: Use a better representation for this.
  324. if (call.args_id == SemIR::InstBlockId::Invalid) {
  325. return SemIR::ConstantId::Error;
  326. }
  327. // If the callee isn't constant, this is not a constant call.
  328. if (!ReplaceFieldWithConstantValue(context, &call, &SemIR::Call::callee_id,
  329. &phase)) {
  330. return SemIR::ConstantId::NotConstant;
  331. }
  332. auto function_id = GetCalleeFunctionId(context, call.callee_id);
  333. // Handle calls to builtins.
  334. auto& function = context.functions().Get(function_id);
  335. if (function.builtin_kind != SemIR::BuiltinFunctionKind::None) {
  336. if (!ReplaceFieldWithConstantValue(context, &call, &SemIR::Call::args_id,
  337. &phase)) {
  338. return SemIR::ConstantId::NotConstant;
  339. }
  340. if (phase == Phase::UnknownDueToError) {
  341. return SemIR::ConstantId::Error;
  342. }
  343. return PerformBuiltinCall(context, loc, call, function.builtin_kind,
  344. context.inst_blocks().Get(call.args_id), phase);
  345. }
  346. return SemIR::ConstantId::NotConstant;
  347. }
  348. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  349. -> SemIR::ConstantId {
  350. // TODO: Ensure we have test coverage for each of these cases that can result
  351. // in a constant, once those situations are all reachable.
  352. switch (inst.kind()) {
  353. // These cases are constants if their operands are.
  354. case SemIR::AddrOf::Kind:
  355. return RebuildIfFieldsAreConstant(context, inst,
  356. &SemIR::AddrOf::lvalue_id);
  357. case SemIR::ArrayType::Kind:
  358. return RebuildAndValidateIfFieldsAreConstant(
  359. context, inst,
  360. [&](SemIR::ArrayType result) {
  361. auto bound_id = inst.As<SemIR::ArrayType>().bound_id;
  362. auto int_bound =
  363. context.insts().TryGetAs<SemIR::IntLiteral>(result.bound_id);
  364. if (!int_bound) {
  365. // TODO: Permit symbolic array bounds. This will require fixing
  366. // callers of `GetArrayBoundValue`.
  367. context.TODO(bound_id, "symbolic array bound");
  368. return false;
  369. }
  370. // TODO: We should check that the size of the resulting array type
  371. // fits in 64 bits, not just that the bound does. Should we use a
  372. // 32-bit limit for 32-bit targets?
  373. // TODO: Also check for a negative bound, once that's something we
  374. // can represent.
  375. const auto& bound_val = context.ints().Get(int_bound->int_id);
  376. if (bound_val.getActiveBits() > 64) {
  377. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  378. "Array bound of {0} is too large.",
  379. llvm::APInt);
  380. context.emitter().Emit(bound_id, ArrayBoundTooLarge, bound_val);
  381. return false;
  382. }
  383. return true;
  384. },
  385. &SemIR::ArrayType::bound_id, &SemIR::ArrayType::element_type_id);
  386. case SemIR::AssociatedEntityType::Kind:
  387. return RebuildIfFieldsAreConstant(
  388. context, inst, &SemIR::AssociatedEntityType::entity_type_id);
  389. case SemIR::BoundMethod::Kind:
  390. return RebuildIfFieldsAreConstant(context, inst,
  391. &SemIR::BoundMethod::object_id,
  392. &SemIR::BoundMethod::function_id);
  393. case SemIR::InterfaceWitness::Kind:
  394. return RebuildIfFieldsAreConstant(context, inst,
  395. &SemIR::InterfaceWitness::elements_id);
  396. case SemIR::PointerType::Kind:
  397. return RebuildIfFieldsAreConstant(context, inst,
  398. &SemIR::PointerType::pointee_id);
  399. case SemIR::StructType::Kind:
  400. return RebuildIfFieldsAreConstant(context, inst,
  401. &SemIR::StructType::fields_id);
  402. case SemIR::StructTypeField::Kind:
  403. return RebuildIfFieldsAreConstant(context, inst,
  404. &SemIR::StructTypeField::field_type_id);
  405. case SemIR::StructValue::Kind:
  406. return RebuildIfFieldsAreConstant(context, inst,
  407. &SemIR::StructValue::elements_id);
  408. case SemIR::TupleType::Kind:
  409. return RebuildIfFieldsAreConstant(context, inst,
  410. &SemIR::TupleType::elements_id);
  411. case SemIR::TupleValue::Kind:
  412. return RebuildIfFieldsAreConstant(context, inst,
  413. &SemIR::TupleValue::elements_id);
  414. case SemIR::UnboundElementType::Kind:
  415. return RebuildIfFieldsAreConstant(
  416. context, inst, &SemIR::UnboundElementType::class_type_id,
  417. &SemIR::UnboundElementType::element_type_id);
  418. // Initializers evaluate to a value of the object representation.
  419. case SemIR::ArrayInit::Kind:
  420. // TODO: Add an `ArrayValue` to represent a constant array object
  421. // representation instead of using a `TupleValue`.
  422. return RebuildInitAsValue(context, inst, SemIR::TupleValue::Kind);
  423. case SemIR::ClassInit::Kind:
  424. // TODO: Add a `ClassValue` to represent a constant class object
  425. // representation instead of using a `StructValue`.
  426. return RebuildInitAsValue(context, inst, SemIR::StructValue::Kind);
  427. case SemIR::StructInit::Kind:
  428. return RebuildInitAsValue(context, inst, SemIR::StructValue::Kind);
  429. case SemIR::TupleInit::Kind:
  430. return RebuildInitAsValue(context, inst, SemIR::TupleValue::Kind);
  431. case SemIR::AssociatedEntity::Kind:
  432. case SemIR::Builtin::Kind:
  433. // Builtins are always template constants.
  434. return MakeConstantResult(context, inst, Phase::Template);
  435. case SemIR::ClassDecl::Kind:
  436. // TODO: Once classes have generic arguments, handle them.
  437. return MakeConstantResult(
  438. context,
  439. SemIR::ClassType{SemIR::TypeId::TypeType,
  440. inst.As<SemIR::ClassDecl>().class_id},
  441. Phase::Template);
  442. case SemIR::InterfaceDecl::Kind:
  443. // TODO: Once interfaces have generic arguments, handle them.
  444. return MakeConstantResult(
  445. context,
  446. SemIR::InterfaceType{SemIR::TypeId::TypeType,
  447. inst.As<SemIR::InterfaceDecl>().interface_id},
  448. Phase::Template);
  449. case SemIR::ClassType::Kind:
  450. case SemIR::InterfaceType::Kind:
  451. CARBON_FATAL() << inst.kind()
  452. << " is only created during corresponding Decl handling.";
  453. // These cases are treated as being the unique canonical definition of the
  454. // corresponding constant value.
  455. // TODO: This doesn't properly handle redeclarations. Consider adding a
  456. // corresponding `Value` inst for each of these cases.
  457. case SemIR::AssociatedConstantDecl::Kind:
  458. case SemIR::BaseDecl::Kind:
  459. case SemIR::FieldDecl::Kind:
  460. case SemIR::FunctionDecl::Kind:
  461. case SemIR::Namespace::Kind:
  462. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  463. case SemIR::BoolLiteral::Kind:
  464. case SemIR::IntLiteral::Kind:
  465. case SemIR::RealLiteral::Kind:
  466. case SemIR::StringLiteral::Kind:
  467. // Promote literals to the constant block.
  468. // TODO: Convert literals into a canonical form. Currently we can form two
  469. // different `i32` constants with the same value if they are represented
  470. // by `APInt`s with different bit widths.
  471. return MakeConstantResult(context, inst, Phase::Template);
  472. // The elements of a constant aggregate can be accessed.
  473. case SemIR::ClassElementAccess::Kind:
  474. case SemIR::InterfaceWitnessAccess::Kind:
  475. case SemIR::StructAccess::Kind:
  476. case SemIR::TupleAccess::Kind:
  477. return PerformAggregateAccess(context, inst);
  478. case SemIR::ArrayIndex::Kind:
  479. case SemIR::TupleIndex::Kind:
  480. return PerformAggregateIndex(context, inst);
  481. case SemIR::Call::Kind:
  482. return PerformCall(context, inst_id, inst.As<SemIR::Call>());
  483. // TODO: These need special handling.
  484. case SemIR::BindValue::Kind:
  485. case SemIR::Deref::Kind:
  486. case SemIR::ImportRefUsed::Kind:
  487. case SemIR::Temporary::Kind:
  488. case SemIR::TemporaryStorage::Kind:
  489. case SemIR::ValueAsRef::Kind:
  490. break;
  491. case SemIR::BindSymbolicName::Kind:
  492. // TODO: Consider forming a constant value here using a de Bruijn index or
  493. // similar, so that corresponding symbolic parameters in redeclarations
  494. // are treated as the same value.
  495. return SemIR::ConstantId::ForSymbolicConstant(inst_id);
  496. // These semantic wrappers don't change the constant value.
  497. case SemIR::BindAlias::Kind:
  498. return context.constant_values().Get(
  499. inst.As<SemIR::BindAlias>().value_id);
  500. case SemIR::NameRef::Kind:
  501. return context.constant_values().Get(inst.As<SemIR::NameRef>().value_id);
  502. case SemIR::Converted::Kind:
  503. return context.constant_values().Get(
  504. inst.As<SemIR::Converted>().result_id);
  505. case SemIR::InitializeFrom::Kind:
  506. return context.constant_values().Get(
  507. inst.As<SemIR::InitializeFrom>().src_id);
  508. case SemIR::SpliceBlock::Kind:
  509. return context.constant_values().Get(
  510. inst.As<SemIR::SpliceBlock>().result_id);
  511. case SemIR::ValueOfInitializer::Kind:
  512. return context.constant_values().Get(
  513. inst.As<SemIR::ValueOfInitializer>().init_id);
  514. case SemIR::FacetTypeAccess::Kind:
  515. // TODO: Once we start tracking the witness in the facet value, remove it
  516. // here. For now, we model a facet value as just a type.
  517. return context.constant_values().Get(
  518. inst.As<SemIR::FacetTypeAccess>().facet_id);
  519. // `not true` -> `false`, `not false` -> `true`.
  520. // All other uses of unary `not` are non-constant.
  521. case SemIR::UnaryOperatorNot::Kind: {
  522. auto const_id = context.constant_values().Get(
  523. inst.As<SemIR::UnaryOperatorNot>().operand_id);
  524. auto phase = GetPhase(const_id);
  525. if (phase == Phase::Template) {
  526. auto value =
  527. context.insts().GetAs<SemIR::BoolLiteral>(const_id.inst_id());
  528. value.value =
  529. (value.value == SemIR::BoolValue::False ? SemIR::BoolValue::True
  530. : SemIR::BoolValue::False);
  531. return MakeConstantResult(context, value, Phase::Template);
  532. }
  533. if (phase == Phase::UnknownDueToError) {
  534. return SemIR::ConstantId::Error;
  535. }
  536. break;
  537. }
  538. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  539. // to itself.
  540. case SemIR::ConstType::Kind: {
  541. auto inner_id = context.constant_values().Get(
  542. context.types().GetInstId(inst.As<SemIR::ConstType>().inner_id));
  543. if (inner_id.is_constant() &&
  544. context.insts().Get(inner_id.inst_id()).Is<SemIR::ConstType>()) {
  545. return inner_id;
  546. }
  547. return MakeConstantResult(context, inst, GetPhase(inner_id));
  548. }
  549. // These cases are either not expressions or not constant.
  550. case SemIR::AddrPattern::Kind:
  551. case SemIR::Assign::Kind:
  552. case SemIR::BindName::Kind:
  553. case SemIR::BlockArg::Kind:
  554. case SemIR::Branch::Kind:
  555. case SemIR::BranchIf::Kind:
  556. case SemIR::BranchWithArg::Kind:
  557. case SemIR::ImplDecl::Kind:
  558. case SemIR::Param::Kind:
  559. case SemIR::ReturnExpr::Kind:
  560. case SemIR::Return::Kind:
  561. case SemIR::StructLiteral::Kind:
  562. case SemIR::TupleLiteral::Kind:
  563. case SemIR::VarStorage::Kind:
  564. break;
  565. case SemIR::ImportRefUnused::Kind:
  566. CARBON_FATAL() << "ImportRefUnused should transform to ImportRefUsed "
  567. "before TryEvalInst.";
  568. }
  569. return SemIR::ConstantId::NotConstant;
  570. }
  571. } // namespace Carbon::Check