eval.cpp 61 KB

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