eval.cpp 49 KB

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