eval.cpp 43 KB

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