eval.cpp 34 KB

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