eval.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  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/base/kind_switch.h"
  6. #include "toolchain/check/diagnostic_helpers.h"
  7. #include "toolchain/diagnostics/diagnostic_emitter.h"
  8. #include "toolchain/sem_ir/builtin_function_kind.h"
  9. #include "toolchain/sem_ir/function.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. #include "toolchain/sem_ir/typed_insts.h"
  12. namespace Carbon::Check {
  13. namespace {
  14. // The evaluation phase for an expression, computed by evaluation. These are
  15. // ordered so that the phase of an expression is the numerically highest phase
  16. // of its constituent evaluations. Note that an expression with any runtime
  17. // component is known to have Runtime phase even if it involves an evaluation
  18. // with UnknownDueToError phase.
  19. enum class Phase : uint8_t {
  20. // Value could be entirely and concretely computed.
  21. Template,
  22. // Evaluation phase is symbolic because the expression involves a reference to
  23. // a symbolic binding.
  24. Symbolic,
  25. // The evaluation phase is unknown because evaluation encountered an
  26. // already-diagnosed semantic or syntax error. This is treated as being
  27. // potentially constant, but with an unknown phase.
  28. UnknownDueToError,
  29. // The expression has runtime phase because of a non-constant subexpression.
  30. Runtime,
  31. };
  32. } // namespace
  33. // Gets the phase in which the value of a constant will become available.
  34. static auto GetPhase(SemIR::ConstantId constant_id) -> Phase {
  35. if (!constant_id.is_constant()) {
  36. return Phase::Runtime;
  37. } else if (constant_id == SemIR::ConstantId::Error) {
  38. return Phase::UnknownDueToError;
  39. } else if (constant_id.is_template()) {
  40. return Phase::Template;
  41. } else {
  42. CARBON_CHECK(constant_id.is_symbolic());
  43. return Phase::Symbolic;
  44. }
  45. }
  46. // Returns the later of two phases.
  47. static auto LatestPhase(Phase a, Phase b) -> Phase {
  48. return static_cast<Phase>(
  49. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  50. }
  51. // Forms a `constant_id` describing a given evaluation result.
  52. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  53. -> SemIR::ConstantId {
  54. switch (phase) {
  55. case Phase::Template:
  56. return context.AddConstant(inst, /*is_symbolic=*/false);
  57. case Phase::Symbolic:
  58. return context.AddConstant(inst, /*is_symbolic=*/true);
  59. case Phase::UnknownDueToError:
  60. return SemIR::ConstantId::Error;
  61. case Phase::Runtime:
  62. return SemIR::ConstantId::NotConstant;
  63. }
  64. }
  65. // Forms a `constant_id` describing why an evaluation was not constant.
  66. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  67. return phase == Phase::UnknownDueToError ? SemIR::ConstantId::Error
  68. : SemIR::ConstantId::NotConstant;
  69. }
  70. // Converts a bool value into a ConstantId.
  71. static auto MakeBoolResult(Context& context, SemIR::TypeId bool_type_id,
  72. bool result) -> SemIR::ConstantId {
  73. return MakeConstantResult(
  74. context, SemIR::BoolLiteral{bool_type_id, SemIR::BoolValue::From(result)},
  75. Phase::Template);
  76. }
  77. // Converts an APInt value into a ConstantId.
  78. static auto MakeIntResult(Context& context, SemIR::TypeId type_id,
  79. llvm::APInt value) -> SemIR::ConstantId {
  80. auto result = context.ints().Add(std::move(value));
  81. return MakeConstantResult(context, SemIR::IntLiteral{type_id, result},
  82. Phase::Template);
  83. }
  84. // Converts an APFloat value into a ConstantId.
  85. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  86. llvm::APFloat value) -> SemIR::ConstantId {
  87. auto result = context.floats().Add(std::move(value));
  88. return MakeConstantResult(context, SemIR::FloatLiteral{type_id, result},
  89. Phase::Template);
  90. }
  91. // `GetConstantValue` checks to see whether the provided ID describes a value
  92. // with constant phase, and if so, returns the corresponding constant value.
  93. // Overloads are provided for different kinds of ID.
  94. // If the given instruction is constant, returns its constant value.
  95. static auto GetConstantValue(Context& context, SemIR::InstId inst_id,
  96. Phase* phase) -> SemIR::InstId {
  97. auto const_id = context.constant_values().Get(inst_id);
  98. *phase = LatestPhase(*phase, GetPhase(const_id));
  99. return const_id.inst_id();
  100. }
  101. // A type is always constant, but we still need to extract its phase.
  102. static auto GetConstantValue(Context& context, SemIR::TypeId type_id,
  103. Phase* phase) -> SemIR::TypeId {
  104. auto const_id = context.types().GetConstantId(type_id);
  105. *phase = LatestPhase(*phase, GetPhase(const_id));
  106. return type_id;
  107. }
  108. // If the given instruction block contains only constants, returns a
  109. // corresponding block of those values.
  110. static auto GetConstantValue(Context& context, SemIR::InstBlockId inst_block_id,
  111. Phase* phase) -> SemIR::InstBlockId {
  112. auto insts = context.inst_blocks().Get(inst_block_id);
  113. llvm::SmallVector<SemIR::InstId> const_insts;
  114. for (auto inst_id : insts) {
  115. auto const_inst_id = GetConstantValue(context, inst_id, phase);
  116. if (!const_inst_id.is_valid()) {
  117. return SemIR::InstBlockId::Invalid;
  118. }
  119. // Once we leave the small buffer, we know the first few elements are all
  120. // constant, so it's likely that the entire block is constant. Resize to the
  121. // target size given that we're going to allocate memory now anyway.
  122. if (const_insts.size() == const_insts.capacity()) {
  123. const_insts.reserve(insts.size());
  124. }
  125. const_insts.push_back(const_inst_id);
  126. }
  127. // TODO: If the new block is identical to the original block, return the
  128. // original ID.
  129. return context.inst_blocks().Add(const_insts);
  130. }
  131. // The constant value of a type block is that type block, but we still need to
  132. // extract its phase.
  133. static auto GetConstantValue(Context& context, SemIR::TypeBlockId type_block_id,
  134. Phase* phase) -> SemIR::TypeBlockId {
  135. auto types = context.type_blocks().Get(type_block_id);
  136. for (auto type_id : types) {
  137. GetConstantValue(context, type_id, phase);
  138. }
  139. return type_block_id;
  140. }
  141. // Replaces the specified field of the given typed instruction with its constant
  142. // value, if it has constant phase. Returns true on success, false if the value
  143. // has runtime phase.
  144. template <typename InstT, typename FieldIdT>
  145. static auto ReplaceFieldWithConstantValue(Context& context, InstT* inst,
  146. FieldIdT InstT::*field, Phase* phase)
  147. -> bool {
  148. auto unwrapped = GetConstantValue(context, inst->*field, phase);
  149. if (!unwrapped.is_valid()) {
  150. return false;
  151. }
  152. inst->*field = unwrapped;
  153. return true;
  154. }
  155. // If the specified fields of the given typed instruction have constant values,
  156. // replaces the fields with their constant values and builds a corresponding
  157. // constant value. Otherwise returns `ConstantId::NotConstant`. Returns
  158. // `ConstantId::Error` if any subexpression is an error.
  159. //
  160. // The constant value is then checked by calling `validate_fn(typed_inst)`,
  161. // which should return a `bool` indicating whether the new constant is valid. If
  162. // validation passes, a corresponding ConstantId for the new constant is
  163. // returned. If validation fails, it should produce a suitable error message.
  164. // `ConstantId::Error` is returned.
  165. template <typename InstT, typename ValidateFn, typename... EachFieldIdT>
  166. static auto RebuildAndValidateIfFieldsAreConstant(
  167. Context& context, SemIR::Inst inst, ValidateFn validate_fn,
  168. EachFieldIdT InstT::*... each_field_id) -> SemIR::ConstantId {
  169. // Build a constant instruction by replacing each non-constant operand with
  170. // its constant value.
  171. auto typed_inst = inst.As<InstT>();
  172. Phase phase = Phase::Template;
  173. if ((ReplaceFieldWithConstantValue(context, &typed_inst, each_field_id,
  174. &phase) &&
  175. ...)) {
  176. if (phase == Phase::UnknownDueToError || !validate_fn(typed_inst)) {
  177. return SemIR::ConstantId::Error;
  178. }
  179. return MakeConstantResult(context, typed_inst, phase);
  180. }
  181. return MakeNonConstantResult(phase);
  182. }
  183. // Same as above but with no validation step.
  184. template <typename InstT, typename... EachFieldIdT>
  185. static auto RebuildIfFieldsAreConstant(Context& context, SemIR::Inst inst,
  186. EachFieldIdT InstT::*... each_field_id)
  187. -> SemIR::ConstantId {
  188. return RebuildAndValidateIfFieldsAreConstant(
  189. context, inst, [](...) { return true; }, each_field_id...);
  190. }
  191. // Rebuilds the given aggregate initialization instruction as a corresponding
  192. // constant aggregate value, if its elements are all constants.
  193. static auto RebuildInitAsValue(Context& context, SemIR::Inst inst,
  194. SemIR::InstKind value_kind)
  195. -> SemIR::ConstantId {
  196. auto init_inst = inst.As<SemIR::AnyAggregateInit>();
  197. Phase phase = Phase::Template;
  198. auto elements_id = GetConstantValue(context, init_inst.elements_id, &phase);
  199. return MakeConstantResult(
  200. context,
  201. SemIR::AnyAggregateValue{.kind = value_kind,
  202. .type_id = init_inst.type_id,
  203. .elements_id = elements_id},
  204. phase);
  205. }
  206. // Performs an access into an aggregate, retrieving the specified element.
  207. static auto PerformAggregateAccess(Context& context, SemIR::Inst inst)
  208. -> SemIR::ConstantId {
  209. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  210. Phase phase = Phase::Template;
  211. if (auto aggregate_id =
  212. GetConstantValue(context, access_inst.aggregate_id, &phase);
  213. aggregate_id.is_valid()) {
  214. if (auto aggregate =
  215. context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id)) {
  216. auto elements = context.inst_blocks().Get(aggregate->elements_id);
  217. auto index = static_cast<size_t>(access_inst.index.index);
  218. CARBON_CHECK(index < elements.size()) << "Access out of bounds.";
  219. // `Phase` is not used here. If this element is a template constant, then
  220. // so is the result of indexing, even if the aggregate also contains a
  221. // symbolic context.
  222. return context.constant_values().Get(elements[index]);
  223. } else {
  224. CARBON_CHECK(phase != Phase::Template)
  225. << "Failed to evaluate template constant " << inst;
  226. }
  227. }
  228. return MakeNonConstantResult(phase);
  229. }
  230. // Performs an index into a homogeneous aggregate, retrieving the specified
  231. // element.
  232. static auto PerformAggregateIndex(Context& context, SemIR::Inst inst)
  233. -> SemIR::ConstantId {
  234. auto index_inst = inst.As<SemIR::AnyAggregateIndex>();
  235. Phase phase = Phase::Template;
  236. auto aggregate_id =
  237. GetConstantValue(context, index_inst.aggregate_id, &phase);
  238. auto index_id = GetConstantValue(context, index_inst.index_id, &phase);
  239. if (!index_id.is_valid()) {
  240. return MakeNonConstantResult(phase);
  241. }
  242. auto index = context.insts().TryGetAs<SemIR::IntLiteral>(index_id);
  243. if (!index) {
  244. CARBON_CHECK(phase != Phase::Template)
  245. << "Template constant integer should be a literal";
  246. return MakeNonConstantResult(phase);
  247. }
  248. // Array indexing is invalid if the index is constant and out of range.
  249. auto aggregate_type_id =
  250. context.insts().Get(index_inst.aggregate_id).type_id();
  251. const auto& index_val = context.ints().Get(index->int_id);
  252. if (auto array_type =
  253. context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  254. if (auto bound =
  255. context.insts().TryGetAs<SemIR::IntLiteral>(array_type->bound_id)) {
  256. // This awkward call to `getZExtValue` is a workaround for APInt not
  257. // supporting comparisons between integers of different bit widths.
  258. if (index_val.getActiveBits() > 64 ||
  259. context.ints().Get(bound->int_id).ule(index_val.getZExtValue())) {
  260. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  261. "Array index `{0}` is past the end of type `{1}`.",
  262. TypedInt, SemIR::TypeId);
  263. context.emitter().Emit(index_inst.index_id, ArrayIndexOutOfBounds,
  264. TypedInt{index->type_id, index_val},
  265. aggregate_type_id);
  266. return SemIR::ConstantId::Error;
  267. }
  268. }
  269. }
  270. if (!aggregate_id.is_valid()) {
  271. return MakeNonConstantResult(phase);
  272. }
  273. auto aggregate =
  274. context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  275. if (!aggregate) {
  276. CARBON_CHECK(phase != Phase::Template)
  277. << "Unexpected representation for template constant aggregate";
  278. return MakeNonConstantResult(phase);
  279. }
  280. auto elements = context.inst_blocks().Get(aggregate->elements_id);
  281. // We checked this for the array case above.
  282. CARBON_CHECK(index_val.ult(elements.size()))
  283. << "Index out of bounds in tuple indexing";
  284. return context.constant_values().Get(elements[index_val.getZExtValue()]);
  285. }
  286. // Enforces that an integer type has a valid bit width.
  287. auto ValidateIntType(Context& context, SemIRLoc loc, SemIR::IntType result)
  288. -> bool {
  289. auto bit_width =
  290. context.insts().TryGetAs<SemIR::IntLiteral>(result.bit_width_id);
  291. if (!bit_width) {
  292. // Symbolic bit width.
  293. return true;
  294. }
  295. const auto& bit_width_val = context.ints().Get(bit_width->int_id);
  296. if (bit_width_val.isZero() ||
  297. (context.types().IsSignedInt(bit_width->type_id) &&
  298. bit_width_val.isNegative())) {
  299. CARBON_DIAGNOSTIC(IntWidthNotPositive, Error,
  300. "Integer type width of {0} is not positive.", TypedInt);
  301. context.emitter().Emit(loc, IntWidthNotPositive,
  302. TypedInt{bit_width->type_id, bit_width_val});
  303. return false;
  304. }
  305. // TODO: Pick a maximum size and document it in the design. For now
  306. // we use 2^^23, because that's the largest size that LLVM supports.
  307. constexpr int MaxIntWidth = 1 << 23;
  308. if (bit_width_val.ugt(MaxIntWidth)) {
  309. CARBON_DIAGNOSTIC(IntWidthTooLarge, Error,
  310. "Integer type width of {0} is greater than the "
  311. "maximum supported width of {1}.",
  312. TypedInt, int);
  313. context.emitter().Emit(loc, IntWidthTooLarge,
  314. TypedInt{bit_width->type_id, bit_width_val},
  315. MaxIntWidth);
  316. return false;
  317. }
  318. return true;
  319. }
  320. // Forms a constant int type as an evaluation result. Requires that width_id is
  321. // constant.
  322. auto MakeIntTypeResult(Context& context, SemIRLoc loc, SemIR::IntKind int_kind,
  323. SemIR::InstId width_id, Phase phase)
  324. -> SemIR::ConstantId {
  325. auto result = SemIR::IntType{
  326. .type_id = context.GetBuiltinType(SemIR::BuiltinKind::TypeType),
  327. .int_kind = int_kind,
  328. .bit_width_id = width_id};
  329. if (!ValidateIntType(context, loc, result)) {
  330. return SemIR::ConstantId::Error;
  331. }
  332. return MakeConstantResult(context, result, phase);
  333. }
  334. // Enforces that the bit width is 64 for a float.
  335. static auto ValidateFloatBitWidth(Context& context, SemIRLoc loc,
  336. SemIR::InstId inst_id) -> bool {
  337. auto inst = context.insts().GetAs<SemIR::IntLiteral>(inst_id);
  338. if (context.ints().Get(inst.int_id) == 64) {
  339. return true;
  340. }
  341. CARBON_DIAGNOSTIC(CompileTimeFloatBitWidth, Error, "Bit width must be 64.");
  342. context.emitter().Emit(loc, CompileTimeFloatBitWidth);
  343. return false;
  344. }
  345. // Enforces that a float type has a valid bit width.
  346. auto ValidateFloatType(Context& context, SemIRLoc loc, SemIR::FloatType result)
  347. -> bool {
  348. auto bit_width =
  349. context.insts().TryGetAs<SemIR::IntLiteral>(result.bit_width_id);
  350. if (!bit_width) {
  351. // Symbolic bit width.
  352. return true;
  353. }
  354. return ValidateFloatBitWidth(context, loc, result.bit_width_id);
  355. }
  356. // Issues a diagnostic for a compile-time division by zero.
  357. static auto DiagnoseDivisionByZero(Context& context, SemIRLoc loc) -> void {
  358. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "Division by zero.");
  359. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  360. }
  361. // Performs a builtin unary integer -> integer operation.
  362. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLoc loc,
  363. SemIR::BuiltinFunctionKind builtin_kind,
  364. SemIR::InstId arg_id)
  365. -> SemIR::ConstantId {
  366. auto op = context.insts().GetAs<SemIR::IntLiteral>(arg_id);
  367. auto op_val = context.ints().Get(op.int_id);
  368. switch (builtin_kind) {
  369. case SemIR::BuiltinFunctionKind::IntSNegate:
  370. if (context.types().IsSignedInt(op.type_id) &&
  371. op_val.isMinSignedValue()) {
  372. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  373. "Integer overflow in negation of {0}.", TypedInt);
  374. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  375. TypedInt{op.type_id, op_val});
  376. }
  377. op_val.negate();
  378. break;
  379. case SemIR::BuiltinFunctionKind::IntUNegate:
  380. op_val.negate();
  381. break;
  382. case SemIR::BuiltinFunctionKind::IntComplement:
  383. op_val.flipAllBits();
  384. break;
  385. default:
  386. CARBON_FATAL() << "Unexpected builtin kind";
  387. }
  388. return MakeIntResult(context, op.type_id, std::move(op_val));
  389. }
  390. // Performs a builtin binary integer -> integer operation.
  391. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLoc loc,
  392. SemIR::BuiltinFunctionKind builtin_kind,
  393. SemIR::InstId lhs_id,
  394. SemIR::InstId rhs_id)
  395. -> SemIR::ConstantId {
  396. auto lhs = context.insts().GetAs<SemIR::IntLiteral>(lhs_id);
  397. auto rhs = context.insts().GetAs<SemIR::IntLiteral>(rhs_id);
  398. const auto& lhs_val = context.ints().Get(lhs.int_id);
  399. const auto& rhs_val = context.ints().Get(rhs.int_id);
  400. // Check for division by zero.
  401. switch (builtin_kind) {
  402. case SemIR::BuiltinFunctionKind::IntSDiv:
  403. case SemIR::BuiltinFunctionKind::IntSMod:
  404. case SemIR::BuiltinFunctionKind::IntUDiv:
  405. case SemIR::BuiltinFunctionKind::IntUMod:
  406. if (rhs_val.isZero()) {
  407. DiagnoseDivisionByZero(context, loc);
  408. return SemIR::ConstantId::Error;
  409. }
  410. break;
  411. default:
  412. break;
  413. }
  414. bool overflow = false;
  415. llvm::APInt result_val;
  416. llvm::StringLiteral op_str = "<error>";
  417. switch (builtin_kind) {
  418. // Arithmetic.
  419. case SemIR::BuiltinFunctionKind::IntSAdd:
  420. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  421. op_str = "+";
  422. break;
  423. case SemIR::BuiltinFunctionKind::IntSSub:
  424. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  425. op_str = "-";
  426. break;
  427. case SemIR::BuiltinFunctionKind::IntSMul:
  428. result_val = lhs_val.smul_ov(rhs_val, overflow);
  429. op_str = "*";
  430. break;
  431. case SemIR::BuiltinFunctionKind::IntSDiv:
  432. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  433. op_str = "/";
  434. break;
  435. case SemIR::BuiltinFunctionKind::IntSMod:
  436. result_val = lhs_val.srem(rhs_val);
  437. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  438. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  439. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  440. op_str = "%";
  441. break;
  442. case SemIR::BuiltinFunctionKind::IntUAdd:
  443. result_val = lhs_val + rhs_val;
  444. op_str = "+";
  445. break;
  446. case SemIR::BuiltinFunctionKind::IntUSub:
  447. result_val = lhs_val - rhs_val;
  448. op_str = "-";
  449. break;
  450. case SemIR::BuiltinFunctionKind::IntUMul:
  451. result_val = lhs_val * rhs_val;
  452. op_str = "*";
  453. break;
  454. case SemIR::BuiltinFunctionKind::IntUDiv:
  455. result_val = lhs_val.udiv(rhs_val);
  456. op_str = "/";
  457. break;
  458. case SemIR::BuiltinFunctionKind::IntUMod:
  459. result_val = lhs_val.urem(rhs_val);
  460. op_str = "%";
  461. break;
  462. // Bitwise.
  463. case SemIR::BuiltinFunctionKind::IntAnd:
  464. result_val = lhs_val & rhs_val;
  465. op_str = "&";
  466. break;
  467. case SemIR::BuiltinFunctionKind::IntOr:
  468. result_val = lhs_val | rhs_val;
  469. op_str = "|";
  470. break;
  471. case SemIR::BuiltinFunctionKind::IntXor:
  472. result_val = lhs_val ^ rhs_val;
  473. op_str = "^";
  474. break;
  475. // Bit shift.
  476. case SemIR::BuiltinFunctionKind::IntLeftShift:
  477. case SemIR::BuiltinFunctionKind::IntRightShift:
  478. op_str = (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift)
  479. ? llvm::StringLiteral("<<")
  480. : llvm::StringLiteral(">>");
  481. if (rhs_val.uge(lhs_val.getBitWidth()) ||
  482. (rhs_val.isNegative() && context.types().IsSignedInt(rhs.type_id))) {
  483. CARBON_DIAGNOSTIC(
  484. CompileTimeShiftOutOfRange, Error,
  485. "Shift distance not in range [0, {0}) in {1} {2} {3}.", unsigned,
  486. TypedInt, llvm::StringLiteral, TypedInt);
  487. context.emitter().Emit(loc, CompileTimeShiftOutOfRange,
  488. lhs_val.getBitWidth(),
  489. TypedInt{lhs.type_id, lhs_val}, op_str,
  490. TypedInt{rhs.type_id, rhs_val});
  491. // TODO: Is it useful to recover by returning 0 or -1?
  492. return SemIR::ConstantId::Error;
  493. }
  494. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  495. result_val = lhs_val.shl(rhs_val);
  496. } else if (context.types().IsSignedInt(lhs.type_id)) {
  497. result_val = lhs_val.ashr(rhs_val);
  498. } else {
  499. result_val = lhs_val.lshr(rhs_val);
  500. }
  501. break;
  502. default:
  503. CARBON_FATAL() << "Unexpected operation kind.";
  504. }
  505. if (overflow) {
  506. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  507. "Integer overflow in calculation {0} {1} {2}.", TypedInt,
  508. llvm::StringLiteral, TypedInt);
  509. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  510. TypedInt{lhs.type_id, lhs_val}, op_str,
  511. TypedInt{rhs.type_id, rhs_val});
  512. }
  513. return MakeIntResult(context, lhs.type_id, std::move(result_val));
  514. }
  515. // Performs a builtin integer comparison.
  516. static auto PerformBuiltinIntComparison(Context& context,
  517. SemIR::BuiltinFunctionKind builtin_kind,
  518. SemIR::InstId lhs_id,
  519. SemIR::InstId rhs_id,
  520. SemIR::TypeId bool_type_id)
  521. -> SemIR::ConstantId {
  522. auto lhs = context.insts().GetAs<SemIR::IntLiteral>(lhs_id);
  523. const auto& lhs_val = context.ints().Get(lhs.int_id);
  524. const auto& rhs_val = context.ints().Get(
  525. context.insts().GetAs<SemIR::IntLiteral>(rhs_id).int_id);
  526. bool is_signed = context.types().IsSignedInt(lhs.type_id);
  527. bool result;
  528. switch (builtin_kind) {
  529. case SemIR::BuiltinFunctionKind::IntEq:
  530. result = (lhs_val == rhs_val);
  531. break;
  532. case SemIR::BuiltinFunctionKind::IntNeq:
  533. result = (lhs_val != rhs_val);
  534. break;
  535. case SemIR::BuiltinFunctionKind::IntLess:
  536. result = is_signed ? lhs_val.slt(rhs_val) : lhs_val.ult(rhs_val);
  537. break;
  538. case SemIR::BuiltinFunctionKind::IntLessEq:
  539. result = is_signed ? lhs_val.sle(rhs_val) : lhs_val.ule(rhs_val);
  540. break;
  541. case SemIR::BuiltinFunctionKind::IntGreater:
  542. result = is_signed ? lhs_val.sgt(rhs_val) : lhs_val.sgt(rhs_val);
  543. break;
  544. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  545. result = is_signed ? lhs_val.sge(rhs_val) : lhs_val.sge(rhs_val);
  546. break;
  547. default:
  548. CARBON_FATAL() << "Unexpected operation kind.";
  549. }
  550. return MakeBoolResult(context, bool_type_id, result);
  551. }
  552. // Performs a builtin unary float -> float operation.
  553. static auto PerformBuiltinUnaryFloatOp(Context& context,
  554. SemIR::BuiltinFunctionKind builtin_kind,
  555. SemIR::InstId arg_id)
  556. -> SemIR::ConstantId {
  557. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  558. auto op_val = context.floats().Get(op.float_id);
  559. switch (builtin_kind) {
  560. case SemIR::BuiltinFunctionKind::FloatNegate:
  561. op_val.changeSign();
  562. break;
  563. default:
  564. CARBON_FATAL() << "Unexpected builtin kind";
  565. }
  566. return MakeFloatResult(context, op.type_id, std::move(op_val));
  567. }
  568. // Performs a builtin binary float -> float operation.
  569. static auto PerformBuiltinBinaryFloatOp(Context& context,
  570. SemIR::BuiltinFunctionKind builtin_kind,
  571. SemIR::InstId lhs_id,
  572. SemIR::InstId rhs_id)
  573. -> SemIR::ConstantId {
  574. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  575. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  576. auto lhs_val = context.floats().Get(lhs.float_id);
  577. auto rhs_val = context.floats().Get(rhs.float_id);
  578. llvm::APFloat result_val(lhs_val.getSemantics());
  579. switch (builtin_kind) {
  580. case SemIR::BuiltinFunctionKind::FloatAdd:
  581. result_val = lhs_val + rhs_val;
  582. break;
  583. case SemIR::BuiltinFunctionKind::FloatSub:
  584. result_val = lhs_val - rhs_val;
  585. break;
  586. case SemIR::BuiltinFunctionKind::FloatMul:
  587. result_val = lhs_val * rhs_val;
  588. break;
  589. case SemIR::BuiltinFunctionKind::FloatDiv:
  590. result_val = lhs_val / rhs_val;
  591. break;
  592. default:
  593. CARBON_FATAL() << "Unexpected operation kind.";
  594. }
  595. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  596. }
  597. // Performs a builtin float comparison.
  598. static auto PerformBuiltinFloatComparison(
  599. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  600. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  601. -> SemIR::ConstantId {
  602. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  603. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  604. const auto& lhs_val = context.floats().Get(lhs.float_id);
  605. const auto& rhs_val = context.floats().Get(rhs.float_id);
  606. bool result;
  607. switch (builtin_kind) {
  608. case SemIR::BuiltinFunctionKind::FloatEq:
  609. result = (lhs_val == rhs_val);
  610. break;
  611. case SemIR::BuiltinFunctionKind::FloatNeq:
  612. result = (lhs_val != rhs_val);
  613. break;
  614. case SemIR::BuiltinFunctionKind::FloatLess:
  615. result = lhs_val < rhs_val;
  616. break;
  617. case SemIR::BuiltinFunctionKind::FloatLessEq:
  618. result = lhs_val <= rhs_val;
  619. break;
  620. case SemIR::BuiltinFunctionKind::FloatGreater:
  621. result = lhs_val > rhs_val;
  622. break;
  623. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  624. result = lhs_val >= rhs_val;
  625. break;
  626. default:
  627. CARBON_FATAL() << "Unexpected operation kind.";
  628. }
  629. return MakeBoolResult(context, bool_type_id, result);
  630. }
  631. // Returns a constant for a call to a builtin function.
  632. static auto MakeConstantForBuiltinCall(Context& context, SemIRLoc loc,
  633. SemIR::Call call,
  634. SemIR::BuiltinFunctionKind builtin_kind,
  635. llvm::ArrayRef<SemIR::InstId> arg_ids,
  636. Phase phase) -> SemIR::ConstantId {
  637. switch (builtin_kind) {
  638. case SemIR::BuiltinFunctionKind::None:
  639. CARBON_FATAL() << "Not a builtin function.";
  640. case SemIR::BuiltinFunctionKind::IntMakeType32: {
  641. return context.constant_values().Get(SemIR::InstId::BuiltinIntType);
  642. }
  643. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  644. return MakeIntTypeResult(context, loc, SemIR::IntKind::Signed, arg_ids[0],
  645. phase);
  646. }
  647. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  648. return MakeIntTypeResult(context, loc, SemIR::IntKind::Unsigned,
  649. arg_ids[0], phase);
  650. }
  651. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  652. // TODO: Support a symbolic constant width.
  653. if (phase != Phase::Template) {
  654. break;
  655. }
  656. if (!ValidateFloatBitWidth(context, loc, arg_ids[0])) {
  657. return SemIR::ConstantId::Error;
  658. }
  659. return context.constant_values().Get(SemIR::InstId::BuiltinFloatType);
  660. }
  661. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  662. return context.constant_values().Get(SemIR::InstId::BuiltinBoolType);
  663. }
  664. // Unary integer -> integer operations.
  665. case SemIR::BuiltinFunctionKind::IntSNegate:
  666. case SemIR::BuiltinFunctionKind::IntUNegate:
  667. case SemIR::BuiltinFunctionKind::IntComplement: {
  668. if (phase != Phase::Template) {
  669. break;
  670. }
  671. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  672. }
  673. // Binary integer -> integer operations.
  674. case SemIR::BuiltinFunctionKind::IntSAdd:
  675. case SemIR::BuiltinFunctionKind::IntSSub:
  676. case SemIR::BuiltinFunctionKind::IntSMul:
  677. case SemIR::BuiltinFunctionKind::IntSDiv:
  678. case SemIR::BuiltinFunctionKind::IntSMod:
  679. case SemIR::BuiltinFunctionKind::IntUAdd:
  680. case SemIR::BuiltinFunctionKind::IntUSub:
  681. case SemIR::BuiltinFunctionKind::IntUMul:
  682. case SemIR::BuiltinFunctionKind::IntUDiv:
  683. case SemIR::BuiltinFunctionKind::IntUMod:
  684. case SemIR::BuiltinFunctionKind::IntAnd:
  685. case SemIR::BuiltinFunctionKind::IntOr:
  686. case SemIR::BuiltinFunctionKind::IntXor:
  687. case SemIR::BuiltinFunctionKind::IntLeftShift:
  688. case SemIR::BuiltinFunctionKind::IntRightShift: {
  689. if (phase != Phase::Template) {
  690. break;
  691. }
  692. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  693. arg_ids[1]);
  694. }
  695. // Integer comparisons.
  696. case SemIR::BuiltinFunctionKind::IntEq:
  697. case SemIR::BuiltinFunctionKind::IntNeq:
  698. case SemIR::BuiltinFunctionKind::IntLess:
  699. case SemIR::BuiltinFunctionKind::IntLessEq:
  700. case SemIR::BuiltinFunctionKind::IntGreater:
  701. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  702. if (phase != Phase::Template) {
  703. break;
  704. }
  705. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  706. arg_ids[1], call.type_id);
  707. }
  708. // Unary float -> float operations.
  709. case SemIR::BuiltinFunctionKind::FloatNegate: {
  710. if (phase != Phase::Template) {
  711. break;
  712. }
  713. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  714. }
  715. // Binary float -> float operations.
  716. case SemIR::BuiltinFunctionKind::FloatAdd:
  717. case SemIR::BuiltinFunctionKind::FloatSub:
  718. case SemIR::BuiltinFunctionKind::FloatMul:
  719. case SemIR::BuiltinFunctionKind::FloatDiv: {
  720. if (phase != Phase::Template) {
  721. break;
  722. }
  723. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  724. arg_ids[1]);
  725. }
  726. // Float comparisons.
  727. case SemIR::BuiltinFunctionKind::FloatEq:
  728. case SemIR::BuiltinFunctionKind::FloatNeq:
  729. case SemIR::BuiltinFunctionKind::FloatLess:
  730. case SemIR::BuiltinFunctionKind::FloatLessEq:
  731. case SemIR::BuiltinFunctionKind::FloatGreater:
  732. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  733. if (phase != Phase::Template) {
  734. break;
  735. }
  736. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  737. arg_ids[1], call.type_id);
  738. }
  739. }
  740. return SemIR::ConstantId::NotConstant;
  741. }
  742. // Makes a constant for a call instruction.
  743. static auto MakeConstantForCall(Context& context, SemIRLoc loc,
  744. SemIR::Call call) -> SemIR::ConstantId {
  745. Phase phase = Phase::Template;
  746. // A call with an invalid argument list is used to represent an erroneous
  747. // call.
  748. //
  749. // TODO: Use a better representation for this.
  750. if (call.args_id == SemIR::InstBlockId::Invalid) {
  751. return SemIR::ConstantId::Error;
  752. }
  753. // If the callee isn't constant, this is not a constant call.
  754. if (!ReplaceFieldWithConstantValue(context, &call, &SemIR::Call::callee_id,
  755. &phase)) {
  756. return SemIR::ConstantId::NotConstant;
  757. }
  758. auto callee_function =
  759. SemIR::GetCalleeFunction(context.sem_ir(), call.callee_id);
  760. if (!callee_function.function_id.is_valid()) {
  761. return SemIR::ConstantId::Error;
  762. }
  763. const auto& function = context.functions().Get(callee_function.function_id);
  764. // Handle calls to builtins.
  765. if (function.builtin_kind != SemIR::BuiltinFunctionKind::None) {
  766. if (!ReplaceFieldWithConstantValue(context, &call, &SemIR::Call::args_id,
  767. &phase)) {
  768. return SemIR::ConstantId::NotConstant;
  769. }
  770. if (phase == Phase::UnknownDueToError) {
  771. return SemIR::ConstantId::Error;
  772. }
  773. return MakeConstantForBuiltinCall(context, loc, call, function.builtin_kind,
  774. context.inst_blocks().Get(call.args_id),
  775. phase);
  776. }
  777. return SemIR::ConstantId::NotConstant;
  778. }
  779. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  780. -> SemIR::ConstantId {
  781. // TODO: Ensure we have test coverage for each of these cases that can result
  782. // in a constant, once those situations are all reachable.
  783. CARBON_KIND_SWITCH(inst) {
  784. // These cases are constants if their operands are.
  785. case SemIR::AddrOf::Kind:
  786. return RebuildIfFieldsAreConstant(context, inst,
  787. &SemIR::AddrOf::lvalue_id);
  788. case CARBON_KIND(SemIR::ArrayType array_type): {
  789. return RebuildAndValidateIfFieldsAreConstant(
  790. context, inst,
  791. [&](SemIR::ArrayType result) {
  792. auto bound_id = array_type.bound_id;
  793. auto int_bound =
  794. context.insts().TryGetAs<SemIR::IntLiteral>(result.bound_id);
  795. if (!int_bound) {
  796. // TODO: Permit symbolic array bounds. This will require fixing
  797. // callers of `GetArrayBoundValue`.
  798. context.TODO(bound_id, "symbolic array bound");
  799. return false;
  800. }
  801. // TODO: We should check that the size of the resulting array type
  802. // fits in 64 bits, not just that the bound does. Should we use a
  803. // 32-bit limit for 32-bit targets?
  804. const auto& bound_val = context.ints().Get(int_bound->int_id);
  805. if (context.types().IsSignedInt(int_bound->type_id) &&
  806. bound_val.isNegative()) {
  807. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  808. "Array bound of {0} is negative.", TypedInt);
  809. context.emitter().Emit(bound_id, ArrayBoundNegative,
  810. TypedInt{int_bound->type_id, bound_val});
  811. return false;
  812. }
  813. if (bound_val.getActiveBits() > 64) {
  814. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  815. "Array bound of {0} is too large.", TypedInt);
  816. context.emitter().Emit(bound_id, ArrayBoundTooLarge,
  817. TypedInt{int_bound->type_id, bound_val});
  818. return false;
  819. }
  820. return true;
  821. },
  822. &SemIR::ArrayType::bound_id, &SemIR::ArrayType::element_type_id);
  823. }
  824. case SemIR::AssociatedEntityType::Kind:
  825. return RebuildIfFieldsAreConstant(
  826. context, inst, &SemIR::AssociatedEntityType::entity_type_id);
  827. case SemIR::BoundMethod::Kind:
  828. return RebuildIfFieldsAreConstant(context, inst,
  829. &SemIR::BoundMethod::object_id,
  830. &SemIR::BoundMethod::function_id);
  831. case SemIR::InterfaceWitness::Kind:
  832. return RebuildIfFieldsAreConstant(context, inst,
  833. &SemIR::InterfaceWitness::elements_id);
  834. case CARBON_KIND(SemIR::IntType int_type): {
  835. return RebuildAndValidateIfFieldsAreConstant(
  836. context, inst,
  837. [&](SemIR::IntType result) {
  838. return ValidateIntType(context, int_type.bit_width_id, result);
  839. },
  840. &SemIR::IntType::bit_width_id);
  841. }
  842. case SemIR::PointerType::Kind:
  843. return RebuildIfFieldsAreConstant(context, inst,
  844. &SemIR::PointerType::pointee_id);
  845. case CARBON_KIND(SemIR::FloatType float_type): {
  846. return RebuildAndValidateIfFieldsAreConstant(
  847. context, inst,
  848. [&](SemIR::FloatType result) {
  849. return ValidateFloatType(context, float_type.bit_width_id, result);
  850. },
  851. &SemIR::FloatType::bit_width_id);
  852. }
  853. case SemIR::StructType::Kind:
  854. return RebuildIfFieldsAreConstant(context, inst,
  855. &SemIR::StructType::fields_id);
  856. case SemIR::StructTypeField::Kind:
  857. return RebuildIfFieldsAreConstant(context, inst,
  858. &SemIR::StructTypeField::field_type_id);
  859. case SemIR::StructValue::Kind:
  860. return RebuildIfFieldsAreConstant(context, inst,
  861. &SemIR::StructValue::elements_id);
  862. case SemIR::TupleType::Kind:
  863. return RebuildIfFieldsAreConstant(context, inst,
  864. &SemIR::TupleType::elements_id);
  865. case SemIR::TupleValue::Kind:
  866. return RebuildIfFieldsAreConstant(context, inst,
  867. &SemIR::TupleValue::elements_id);
  868. case SemIR::UnboundElementType::Kind:
  869. return RebuildIfFieldsAreConstant(
  870. context, inst, &SemIR::UnboundElementType::class_type_id,
  871. &SemIR::UnboundElementType::element_type_id);
  872. // Initializers evaluate to a value of the object representation.
  873. case SemIR::ArrayInit::Kind:
  874. // TODO: Add an `ArrayValue` to represent a constant array object
  875. // representation instead of using a `TupleValue`.
  876. return RebuildInitAsValue(context, inst, SemIR::TupleValue::Kind);
  877. case SemIR::ClassInit::Kind:
  878. // TODO: Add a `ClassValue` to represent a constant class object
  879. // representation instead of using a `StructValue`.
  880. return RebuildInitAsValue(context, inst, SemIR::StructValue::Kind);
  881. case SemIR::StructInit::Kind:
  882. return RebuildInitAsValue(context, inst, SemIR::StructValue::Kind);
  883. case SemIR::TupleInit::Kind:
  884. return RebuildInitAsValue(context, inst, SemIR::TupleValue::Kind);
  885. case SemIR::AssociatedEntity::Kind:
  886. case SemIR::Builtin::Kind:
  887. case SemIR::FunctionType::Kind:
  888. // Builtins are always template constants.
  889. return MakeConstantResult(context, inst, Phase::Template);
  890. case CARBON_KIND(SemIR::FunctionDecl fn_decl): {
  891. return MakeConstantResult(
  892. context,
  893. SemIR::StructValue{fn_decl.type_id, SemIR::InstBlockId::Empty},
  894. Phase::Template);
  895. }
  896. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  897. // TODO: Once classes have generic arguments, handle them.
  898. return MakeConstantResult(
  899. context,
  900. SemIR::ClassType{SemIR::TypeId::TypeType, class_decl.class_id},
  901. Phase::Template);
  902. }
  903. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  904. // TODO: Once interfaces have generic arguments, handle them.
  905. return MakeConstantResult(
  906. context,
  907. SemIR::InterfaceType{SemIR::TypeId::TypeType,
  908. interface_decl.interface_id},
  909. Phase::Template);
  910. }
  911. case SemIR::ClassType::Kind:
  912. case SemIR::InterfaceType::Kind:
  913. CARBON_FATAL() << inst.kind()
  914. << " is only created during corresponding Decl handling.";
  915. // These cases are treated as being the unique canonical definition of the
  916. // corresponding constant value.
  917. // TODO: This doesn't properly handle redeclarations. Consider adding a
  918. // corresponding `Value` inst for each of these cases.
  919. case SemIR::AssociatedConstantDecl::Kind:
  920. case SemIR::BaseDecl::Kind:
  921. case SemIR::FieldDecl::Kind:
  922. case SemIR::Namespace::Kind:
  923. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  924. case SemIR::BoolLiteral::Kind:
  925. case SemIR::FloatLiteral::Kind:
  926. case SemIR::IntLiteral::Kind:
  927. case SemIR::RealLiteral::Kind:
  928. case SemIR::StringLiteral::Kind:
  929. // Promote literals to the constant block.
  930. // TODO: Convert literals into a canonical form. Currently we can form two
  931. // different `i32` constants with the same value if they are represented
  932. // by `APInt`s with different bit widths.
  933. return MakeConstantResult(context, inst, Phase::Template);
  934. // The elements of a constant aggregate can be accessed.
  935. case SemIR::ClassElementAccess::Kind:
  936. case SemIR::InterfaceWitnessAccess::Kind:
  937. case SemIR::StructAccess::Kind:
  938. case SemIR::TupleAccess::Kind:
  939. return PerformAggregateAccess(context, inst);
  940. case SemIR::ArrayIndex::Kind:
  941. case SemIR::TupleIndex::Kind:
  942. return PerformAggregateIndex(context, inst);
  943. case CARBON_KIND(SemIR::Call call): {
  944. return MakeConstantForCall(context, inst_id, call);
  945. }
  946. // TODO: These need special handling.
  947. case SemIR::BindValue::Kind:
  948. case SemIR::Deref::Kind:
  949. case SemIR::ImportRefLoaded::Kind:
  950. case SemIR::Temporary::Kind:
  951. case SemIR::TemporaryStorage::Kind:
  952. case SemIR::ValueAsRef::Kind:
  953. break;
  954. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  955. // The constant form of a symbolic binding is an idealized form of the
  956. // original, with no equivalent value.
  957. bind.value_id = SemIR::InstId::Invalid;
  958. return MakeConstantResult(context, bind, Phase::Symbolic);
  959. }
  960. // These semantic wrappers don't change the constant value.
  961. case CARBON_KIND(SemIR::AsCompatible inst): {
  962. return context.constant_values().Get(inst.source_id);
  963. }
  964. case CARBON_KIND(SemIR::BindAlias typed_inst): {
  965. return context.constant_values().Get(typed_inst.value_id);
  966. }
  967. case CARBON_KIND(SemIR::NameRef typed_inst): {
  968. return context.constant_values().Get(typed_inst.value_id);
  969. }
  970. case CARBON_KIND(SemIR::Converted typed_inst): {
  971. return context.constant_values().Get(typed_inst.result_id);
  972. }
  973. case CARBON_KIND(SemIR::InitializeFrom typed_inst): {
  974. return context.constant_values().Get(typed_inst.src_id);
  975. }
  976. case CARBON_KIND(SemIR::SpliceBlock typed_inst): {
  977. return context.constant_values().Get(typed_inst.result_id);
  978. }
  979. case CARBON_KIND(SemIR::ValueOfInitializer typed_inst): {
  980. return context.constant_values().Get(typed_inst.init_id);
  981. }
  982. case CARBON_KIND(SemIR::FacetTypeAccess typed_inst): {
  983. // TODO: Once we start tracking the witness in the facet value, remove it
  984. // here. For now, we model a facet value as just a type.
  985. return context.constant_values().Get(typed_inst.facet_id);
  986. }
  987. // `not true` -> `false`, `not false` -> `true`.
  988. // All other uses of unary `not` are non-constant.
  989. case CARBON_KIND(SemIR::UnaryOperatorNot typed_inst): {
  990. auto const_id = context.constant_values().Get(typed_inst.operand_id);
  991. auto phase = GetPhase(const_id);
  992. if (phase == Phase::Template) {
  993. auto value =
  994. context.insts().GetAs<SemIR::BoolLiteral>(const_id.inst_id());
  995. return MakeBoolResult(context, value.type_id, !value.value.ToBool());
  996. }
  997. if (phase == Phase::UnknownDueToError) {
  998. return SemIR::ConstantId::Error;
  999. }
  1000. break;
  1001. }
  1002. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  1003. // to itself.
  1004. case CARBON_KIND(SemIR::ConstType typed_inst): {
  1005. auto inner_id = context.constant_values().Get(
  1006. context.types().GetInstId(typed_inst.inner_id));
  1007. if (inner_id.is_constant() &&
  1008. context.insts().Get(inner_id.inst_id()).Is<SemIR::ConstType>()) {
  1009. return inner_id;
  1010. }
  1011. return MakeConstantResult(context, inst, GetPhase(inner_id));
  1012. }
  1013. // These cases are either not expressions or not constant.
  1014. case SemIR::AdaptDecl::Kind:
  1015. case SemIR::AddrPattern::Kind:
  1016. case SemIR::Assign::Kind:
  1017. case SemIR::BindName::Kind:
  1018. case SemIR::BlockArg::Kind:
  1019. case SemIR::Branch::Kind:
  1020. case SemIR::BranchIf::Kind:
  1021. case SemIR::BranchWithArg::Kind:
  1022. case SemIR::ImplDecl::Kind:
  1023. case SemIR::Param::Kind:
  1024. case SemIR::ReturnExpr::Kind:
  1025. case SemIR::Return::Kind:
  1026. case SemIR::StructLiteral::Kind:
  1027. case SemIR::TupleLiteral::Kind:
  1028. case SemIR::VarStorage::Kind:
  1029. break;
  1030. case SemIR::ImportRefUnloaded::Kind:
  1031. CARBON_FATAL()
  1032. << "ImportRefUnloaded should be loaded before TryEvalInst.";
  1033. }
  1034. return SemIR::ConstantId::NotConstant;
  1035. }
  1036. } // namespace Carbon::Check