eval.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  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::IntValue{.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::ArrayIndex inst)
  435. -> SemIR::ConstantId {
  436. Phase phase = Phase::Template;
  437. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  438. if (!index_id.is_valid()) {
  439. return MakeNonConstantResult(phase);
  440. }
  441. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  442. if (!index) {
  443. CARBON_CHECK(phase != Phase::Template,
  444. "Template constant integer should be a literal");
  445. return MakeNonConstantResult(phase);
  446. }
  447. // Array indexing is invalid if the index is constant and out of range,
  448. // regardless of whether the array itself is constant.
  449. const auto& index_val = eval_context.ints().Get(index->int_id);
  450. auto aggregate_type_id = eval_context.GetConstantValueAsType(
  451. eval_context.insts().Get(inst.array_id).type_id());
  452. if (auto array_type =
  453. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  454. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  455. array_type->bound_id)) {
  456. // This awkward call to `getZExtValue` is a workaround for APInt not
  457. // supporting comparisons between integers of different bit widths.
  458. if (index_val.getActiveBits() > 64 ||
  459. eval_context.ints()
  460. .Get(bound->int_id)
  461. .ule(index_val.getZExtValue())) {
  462. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  463. "array index `{0}` is past the end of type {1}",
  464. TypedInt, SemIR::TypeId);
  465. eval_context.emitter().Emit(
  466. inst.index_id, ArrayIndexOutOfBounds,
  467. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  468. return SemIR::ConstantId::Error;
  469. }
  470. }
  471. }
  472. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  473. if (!aggregate_id.is_valid()) {
  474. return MakeNonConstantResult(phase);
  475. }
  476. auto aggregate =
  477. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  478. if (!aggregate) {
  479. CARBON_CHECK(phase != Phase::Template,
  480. "Unexpected representation for template constant aggregate");
  481. return MakeNonConstantResult(phase);
  482. }
  483. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  484. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  485. }
  486. // Enforces that an integer type has a valid bit width.
  487. static auto ValidateIntType(Context& context, SemIRLoc loc,
  488. SemIR::IntType result) -> bool {
  489. auto bit_width =
  490. context.insts().TryGetAs<SemIR::IntValue>(result.bit_width_id);
  491. if (!bit_width) {
  492. // Symbolic bit width.
  493. return true;
  494. }
  495. const auto& bit_width_val = context.ints().Get(bit_width->int_id);
  496. if (bit_width_val.isZero() ||
  497. (context.types().IsSignedInt(bit_width->type_id) &&
  498. bit_width_val.isNegative())) {
  499. CARBON_DIAGNOSTIC(IntWidthNotPositive, Error,
  500. "integer type width of {0} is not positive", TypedInt);
  501. context.emitter().Emit(
  502. loc, IntWidthNotPositive,
  503. {.type = bit_width->type_id, .value = bit_width_val});
  504. return false;
  505. }
  506. // TODO: Pick a maximum size and document it in the design. For now
  507. // we use 2^^23, because that's the largest size that LLVM supports.
  508. constexpr int MaxIntWidth = 1 << 23;
  509. if (bit_width_val.ugt(MaxIntWidth)) {
  510. CARBON_DIAGNOSTIC(IntWidthTooLarge, Error,
  511. "integer type width of {0} is greater than the "
  512. "maximum supported width of {1}",
  513. TypedInt, int);
  514. context.emitter().Emit(loc, IntWidthTooLarge,
  515. {.type = bit_width->type_id, .value = bit_width_val},
  516. MaxIntWidth);
  517. return false;
  518. }
  519. return true;
  520. }
  521. // Forms a constant int type as an evaluation result. Requires that width_id is
  522. // constant.
  523. static auto MakeIntTypeResult(Context& context, SemIRLoc loc,
  524. SemIR::IntKind int_kind, SemIR::InstId width_id,
  525. Phase phase) -> SemIR::ConstantId {
  526. auto result = SemIR::IntType{
  527. .type_id = context.GetBuiltinType(SemIR::BuiltinInstKind::TypeType),
  528. .int_kind = int_kind,
  529. .bit_width_id = width_id};
  530. if (!ValidateIntType(context, loc, result)) {
  531. return SemIR::ConstantId::Error;
  532. }
  533. return MakeConstantResult(context, result, phase);
  534. }
  535. // Enforces that the bit width is 64 for a float.
  536. static auto ValidateFloatBitWidth(Context& context, SemIRLoc loc,
  537. SemIR::InstId inst_id) -> bool {
  538. auto inst = context.insts().GetAs<SemIR::IntValue>(inst_id);
  539. if (context.ints().Get(inst.int_id) == 64) {
  540. return true;
  541. }
  542. CARBON_DIAGNOSTIC(CompileTimeFloatBitWidth, Error, "bit width must be 64");
  543. context.emitter().Emit(loc, CompileTimeFloatBitWidth);
  544. return false;
  545. }
  546. // Enforces that a float type has a valid bit width.
  547. static auto ValidateFloatType(Context& context, SemIRLoc loc,
  548. SemIR::FloatType result) -> bool {
  549. auto bit_width =
  550. context.insts().TryGetAs<SemIR::IntValue>(result.bit_width_id);
  551. if (!bit_width) {
  552. // Symbolic bit width.
  553. return true;
  554. }
  555. return ValidateFloatBitWidth(context, loc, result.bit_width_id);
  556. }
  557. // Issues a diagnostic for a compile-time division by zero.
  558. static auto DiagnoseDivisionByZero(Context& context, SemIRLoc loc) -> void {
  559. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  560. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  561. }
  562. // Performs a builtin unary integer -> integer operation.
  563. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLoc loc,
  564. SemIR::BuiltinFunctionKind builtin_kind,
  565. SemIR::InstId arg_id)
  566. -> SemIR::ConstantId {
  567. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  568. auto op_val = context.ints().Get(op.int_id);
  569. switch (builtin_kind) {
  570. case SemIR::BuiltinFunctionKind::IntSNegate:
  571. if (context.types().IsSignedInt(op.type_id) &&
  572. op_val.isMinSignedValue()) {
  573. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  574. "integer overflow in negation of {0}", TypedInt);
  575. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  576. {.type = op.type_id, .value = op_val});
  577. }
  578. op_val.negate();
  579. break;
  580. case SemIR::BuiltinFunctionKind::IntUNegate:
  581. op_val.negate();
  582. break;
  583. case SemIR::BuiltinFunctionKind::IntComplement:
  584. op_val.flipAllBits();
  585. break;
  586. default:
  587. CARBON_FATAL("Unexpected builtin kind");
  588. }
  589. return MakeIntResult(context, op.type_id, std::move(op_val));
  590. }
  591. // Performs a builtin binary integer -> integer operation.
  592. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLoc loc,
  593. SemIR::BuiltinFunctionKind builtin_kind,
  594. SemIR::InstId lhs_id,
  595. SemIR::InstId rhs_id)
  596. -> SemIR::ConstantId {
  597. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  598. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  599. const auto& lhs_val = context.ints().Get(lhs.int_id);
  600. const auto& rhs_val = context.ints().Get(rhs.int_id);
  601. // Check for division by zero.
  602. switch (builtin_kind) {
  603. case SemIR::BuiltinFunctionKind::IntSDiv:
  604. case SemIR::BuiltinFunctionKind::IntSMod:
  605. case SemIR::BuiltinFunctionKind::IntUDiv:
  606. case SemIR::BuiltinFunctionKind::IntUMod:
  607. if (rhs_val.isZero()) {
  608. DiagnoseDivisionByZero(context, loc);
  609. return SemIR::ConstantId::Error;
  610. }
  611. break;
  612. default:
  613. break;
  614. }
  615. bool overflow = false;
  616. llvm::APInt result_val;
  617. Lex::TokenKind op_token = Lex::TokenKind::Not;
  618. switch (builtin_kind) {
  619. // Arithmetic.
  620. case SemIR::BuiltinFunctionKind::IntSAdd:
  621. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  622. op_token = Lex::TokenKind::Plus;
  623. break;
  624. case SemIR::BuiltinFunctionKind::IntSSub:
  625. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  626. op_token = Lex::TokenKind::Minus;
  627. break;
  628. case SemIR::BuiltinFunctionKind::IntSMul:
  629. result_val = lhs_val.smul_ov(rhs_val, overflow);
  630. op_token = Lex::TokenKind::Star;
  631. break;
  632. case SemIR::BuiltinFunctionKind::IntSDiv:
  633. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  634. op_token = Lex::TokenKind::Slash;
  635. break;
  636. case SemIR::BuiltinFunctionKind::IntSMod:
  637. result_val = lhs_val.srem(rhs_val);
  638. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  639. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  640. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  641. op_token = Lex::TokenKind::Percent;
  642. break;
  643. case SemIR::BuiltinFunctionKind::IntUAdd:
  644. result_val = lhs_val + rhs_val;
  645. op_token = Lex::TokenKind::Plus;
  646. break;
  647. case SemIR::BuiltinFunctionKind::IntUSub:
  648. result_val = lhs_val - rhs_val;
  649. op_token = Lex::TokenKind::Minus;
  650. break;
  651. case SemIR::BuiltinFunctionKind::IntUMul:
  652. result_val = lhs_val * rhs_val;
  653. op_token = Lex::TokenKind::Star;
  654. break;
  655. case SemIR::BuiltinFunctionKind::IntUDiv:
  656. result_val = lhs_val.udiv(rhs_val);
  657. op_token = Lex::TokenKind::Slash;
  658. break;
  659. case SemIR::BuiltinFunctionKind::IntUMod:
  660. result_val = lhs_val.urem(rhs_val);
  661. op_token = Lex::TokenKind::Percent;
  662. break;
  663. // Bitwise.
  664. case SemIR::BuiltinFunctionKind::IntAnd:
  665. result_val = lhs_val & rhs_val;
  666. op_token = Lex::TokenKind::And;
  667. break;
  668. case SemIR::BuiltinFunctionKind::IntOr:
  669. result_val = lhs_val | rhs_val;
  670. op_token = Lex::TokenKind::Pipe;
  671. break;
  672. case SemIR::BuiltinFunctionKind::IntXor:
  673. result_val = lhs_val ^ rhs_val;
  674. op_token = Lex::TokenKind::Caret;
  675. break;
  676. // Bit shift.
  677. case SemIR::BuiltinFunctionKind::IntLeftShift:
  678. case SemIR::BuiltinFunctionKind::IntRightShift:
  679. if (rhs_val.uge(lhs_val.getBitWidth()) ||
  680. (rhs_val.isNegative() && context.types().IsSignedInt(rhs.type_id))) {
  681. CARBON_DIAGNOSTIC(
  682. CompileTimeShiftOutOfRange, Error,
  683. "shift distance not in range [0, {0}) in {1} {2:<<|>>} {3}",
  684. unsigned, TypedInt, BoolAsSelect, TypedInt);
  685. context.emitter().Emit(
  686. loc, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  687. {.type = lhs.type_id, .value = lhs_val},
  688. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  689. {.type = rhs.type_id, .value = rhs_val});
  690. // TODO: Is it useful to recover by returning 0 or -1?
  691. return SemIR::ConstantId::Error;
  692. }
  693. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  694. result_val = lhs_val.shl(rhs_val);
  695. } else if (context.types().IsSignedInt(lhs.type_id)) {
  696. result_val = lhs_val.ashr(rhs_val);
  697. } else {
  698. result_val = lhs_val.lshr(rhs_val);
  699. }
  700. break;
  701. default:
  702. CARBON_FATAL("Unexpected operation kind.");
  703. }
  704. if (overflow) {
  705. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  706. "integer overflow in calculation {0} {1} {2}", TypedInt,
  707. Lex::TokenKind, TypedInt);
  708. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  709. {.type = lhs.type_id, .value = lhs_val}, op_token,
  710. {.type = rhs.type_id, .value = rhs_val});
  711. }
  712. return MakeIntResult(context, lhs.type_id, std::move(result_val));
  713. }
  714. // Performs a builtin integer comparison.
  715. static auto PerformBuiltinIntComparison(Context& context,
  716. SemIR::BuiltinFunctionKind builtin_kind,
  717. SemIR::InstId lhs_id,
  718. SemIR::InstId rhs_id,
  719. SemIR::TypeId bool_type_id)
  720. -> SemIR::ConstantId {
  721. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  722. const auto& lhs_val = context.ints().Get(lhs.int_id);
  723. const auto& rhs_val =
  724. context.ints().Get(context.insts().GetAs<SemIR::IntValue>(rhs_id).int_id);
  725. bool is_signed = context.types().IsSignedInt(lhs.type_id);
  726. bool result;
  727. switch (builtin_kind) {
  728. case SemIR::BuiltinFunctionKind::IntEq:
  729. result = (lhs_val == rhs_val);
  730. break;
  731. case SemIR::BuiltinFunctionKind::IntNeq:
  732. result = (lhs_val != rhs_val);
  733. break;
  734. case SemIR::BuiltinFunctionKind::IntLess:
  735. result = is_signed ? lhs_val.slt(rhs_val) : lhs_val.ult(rhs_val);
  736. break;
  737. case SemIR::BuiltinFunctionKind::IntLessEq:
  738. result = is_signed ? lhs_val.sle(rhs_val) : lhs_val.ule(rhs_val);
  739. break;
  740. case SemIR::BuiltinFunctionKind::IntGreater:
  741. result = is_signed ? lhs_val.sgt(rhs_val) : lhs_val.sgt(rhs_val);
  742. break;
  743. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  744. result = is_signed ? lhs_val.sge(rhs_val) : lhs_val.sge(rhs_val);
  745. break;
  746. default:
  747. CARBON_FATAL("Unexpected operation kind.");
  748. }
  749. return MakeBoolResult(context, bool_type_id, result);
  750. }
  751. // Performs a builtin unary float -> float operation.
  752. static auto PerformBuiltinUnaryFloatOp(Context& context,
  753. SemIR::BuiltinFunctionKind builtin_kind,
  754. SemIR::InstId arg_id)
  755. -> SemIR::ConstantId {
  756. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  757. auto op_val = context.floats().Get(op.float_id);
  758. switch (builtin_kind) {
  759. case SemIR::BuiltinFunctionKind::FloatNegate:
  760. op_val.changeSign();
  761. break;
  762. default:
  763. CARBON_FATAL("Unexpected builtin kind");
  764. }
  765. return MakeFloatResult(context, op.type_id, std::move(op_val));
  766. }
  767. // Performs a builtin binary float -> float operation.
  768. static auto PerformBuiltinBinaryFloatOp(Context& context,
  769. SemIR::BuiltinFunctionKind builtin_kind,
  770. SemIR::InstId lhs_id,
  771. SemIR::InstId rhs_id)
  772. -> SemIR::ConstantId {
  773. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  774. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  775. auto lhs_val = context.floats().Get(lhs.float_id);
  776. auto rhs_val = context.floats().Get(rhs.float_id);
  777. llvm::APFloat result_val(lhs_val.getSemantics());
  778. switch (builtin_kind) {
  779. case SemIR::BuiltinFunctionKind::FloatAdd:
  780. result_val = lhs_val + rhs_val;
  781. break;
  782. case SemIR::BuiltinFunctionKind::FloatSub:
  783. result_val = lhs_val - rhs_val;
  784. break;
  785. case SemIR::BuiltinFunctionKind::FloatMul:
  786. result_val = lhs_val * rhs_val;
  787. break;
  788. case SemIR::BuiltinFunctionKind::FloatDiv:
  789. result_val = lhs_val / rhs_val;
  790. break;
  791. default:
  792. CARBON_FATAL("Unexpected operation kind.");
  793. }
  794. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  795. }
  796. // Performs a builtin float comparison.
  797. static auto PerformBuiltinFloatComparison(
  798. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  799. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  800. -> SemIR::ConstantId {
  801. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  802. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  803. const auto& lhs_val = context.floats().Get(lhs.float_id);
  804. const auto& rhs_val = context.floats().Get(rhs.float_id);
  805. bool result;
  806. switch (builtin_kind) {
  807. case SemIR::BuiltinFunctionKind::FloatEq:
  808. result = (lhs_val == rhs_val);
  809. break;
  810. case SemIR::BuiltinFunctionKind::FloatNeq:
  811. result = (lhs_val != rhs_val);
  812. break;
  813. case SemIR::BuiltinFunctionKind::FloatLess:
  814. result = lhs_val < rhs_val;
  815. break;
  816. case SemIR::BuiltinFunctionKind::FloatLessEq:
  817. result = lhs_val <= rhs_val;
  818. break;
  819. case SemIR::BuiltinFunctionKind::FloatGreater:
  820. result = lhs_val > rhs_val;
  821. break;
  822. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  823. result = lhs_val >= rhs_val;
  824. break;
  825. default:
  826. CARBON_FATAL("Unexpected operation kind.");
  827. }
  828. return MakeBoolResult(context, bool_type_id, result);
  829. }
  830. // Returns a constant for a call to a builtin function.
  831. static auto MakeConstantForBuiltinCall(Context& context, SemIRLoc loc,
  832. SemIR::Call call,
  833. SemIR::BuiltinFunctionKind builtin_kind,
  834. llvm::ArrayRef<SemIR::InstId> arg_ids,
  835. Phase phase) -> SemIR::ConstantId {
  836. switch (builtin_kind) {
  837. case SemIR::BuiltinFunctionKind::None:
  838. CARBON_FATAL("Not a builtin function.");
  839. case SemIR::BuiltinFunctionKind::PrintInt: {
  840. // Providing a constant result would allow eliding the function call.
  841. return SemIR::ConstantId::NotConstant;
  842. }
  843. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  844. return context.constant_values().Get(
  845. SemIR::InstId::BuiltinIntLiteralType);
  846. }
  847. case SemIR::BuiltinFunctionKind::IntMakeType32: {
  848. return context.constant_values().Get(SemIR::InstId::BuiltinIntType);
  849. }
  850. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  851. return MakeIntTypeResult(context, loc, SemIR::IntKind::Signed, arg_ids[0],
  852. phase);
  853. }
  854. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  855. return MakeIntTypeResult(context, loc, SemIR::IntKind::Unsigned,
  856. arg_ids[0], phase);
  857. }
  858. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  859. // TODO: Support a symbolic constant width.
  860. if (phase != Phase::Template) {
  861. break;
  862. }
  863. if (!ValidateFloatBitWidth(context, loc, arg_ids[0])) {
  864. return SemIR::ConstantId::Error;
  865. }
  866. return context.constant_values().Get(SemIR::InstId::BuiltinFloatType);
  867. }
  868. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  869. return context.constant_values().Get(SemIR::InstId::BuiltinBoolType);
  870. }
  871. // Unary integer -> integer operations.
  872. case SemIR::BuiltinFunctionKind::IntSNegate:
  873. case SemIR::BuiltinFunctionKind::IntUNegate:
  874. case SemIR::BuiltinFunctionKind::IntComplement: {
  875. if (phase != Phase::Template) {
  876. break;
  877. }
  878. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  879. }
  880. // Binary integer -> integer operations.
  881. case SemIR::BuiltinFunctionKind::IntSAdd:
  882. case SemIR::BuiltinFunctionKind::IntSSub:
  883. case SemIR::BuiltinFunctionKind::IntSMul:
  884. case SemIR::BuiltinFunctionKind::IntSDiv:
  885. case SemIR::BuiltinFunctionKind::IntSMod:
  886. case SemIR::BuiltinFunctionKind::IntUAdd:
  887. case SemIR::BuiltinFunctionKind::IntUSub:
  888. case SemIR::BuiltinFunctionKind::IntUMul:
  889. case SemIR::BuiltinFunctionKind::IntUDiv:
  890. case SemIR::BuiltinFunctionKind::IntUMod:
  891. case SemIR::BuiltinFunctionKind::IntAnd:
  892. case SemIR::BuiltinFunctionKind::IntOr:
  893. case SemIR::BuiltinFunctionKind::IntXor:
  894. case SemIR::BuiltinFunctionKind::IntLeftShift:
  895. case SemIR::BuiltinFunctionKind::IntRightShift: {
  896. if (phase != Phase::Template) {
  897. break;
  898. }
  899. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  900. arg_ids[1]);
  901. }
  902. // Integer comparisons.
  903. case SemIR::BuiltinFunctionKind::IntEq:
  904. case SemIR::BuiltinFunctionKind::IntNeq:
  905. case SemIR::BuiltinFunctionKind::IntLess:
  906. case SemIR::BuiltinFunctionKind::IntLessEq:
  907. case SemIR::BuiltinFunctionKind::IntGreater:
  908. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  909. if (phase != Phase::Template) {
  910. break;
  911. }
  912. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  913. arg_ids[1], call.type_id);
  914. }
  915. // Unary float -> float operations.
  916. case SemIR::BuiltinFunctionKind::FloatNegate: {
  917. if (phase != Phase::Template) {
  918. break;
  919. }
  920. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  921. }
  922. // Binary float -> float operations.
  923. case SemIR::BuiltinFunctionKind::FloatAdd:
  924. case SemIR::BuiltinFunctionKind::FloatSub:
  925. case SemIR::BuiltinFunctionKind::FloatMul:
  926. case SemIR::BuiltinFunctionKind::FloatDiv: {
  927. if (phase != Phase::Template) {
  928. break;
  929. }
  930. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  931. arg_ids[1]);
  932. }
  933. // Float comparisons.
  934. case SemIR::BuiltinFunctionKind::FloatEq:
  935. case SemIR::BuiltinFunctionKind::FloatNeq:
  936. case SemIR::BuiltinFunctionKind::FloatLess:
  937. case SemIR::BuiltinFunctionKind::FloatLessEq:
  938. case SemIR::BuiltinFunctionKind::FloatGreater:
  939. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  940. if (phase != Phase::Template) {
  941. break;
  942. }
  943. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  944. arg_ids[1], call.type_id);
  945. }
  946. }
  947. return SemIR::ConstantId::NotConstant;
  948. }
  949. // Makes a constant for a call instruction.
  950. static auto MakeConstantForCall(EvalContext& eval_context, SemIRLoc loc,
  951. SemIR::Call call) -> SemIR::ConstantId {
  952. Phase phase = Phase::Template;
  953. // A call with an invalid argument list is used to represent an erroneous
  954. // call.
  955. //
  956. // TODO: Use a better representation for this.
  957. if (call.args_id == SemIR::InstBlockId::Invalid) {
  958. return SemIR::ConstantId::Error;
  959. }
  960. // If the callee or return type isn't constant, this is not a constant call.
  961. if (!ReplaceFieldWithConstantValue(eval_context, &call,
  962. &SemIR::Call::callee_id, &phase) ||
  963. !ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::type_id,
  964. &phase)) {
  965. return SemIR::ConstantId::NotConstant;
  966. }
  967. auto callee_function =
  968. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  969. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  970. if (callee_function.function_id.is_valid()) {
  971. // Calls to builtins might be constant.
  972. builtin_kind = eval_context.functions()
  973. .Get(callee_function.function_id)
  974. .builtin_function_kind;
  975. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  976. // TODO: Eventually we'll want to treat some kinds of non-builtin
  977. // functions as producing constants.
  978. return SemIR::ConstantId::NotConstant;
  979. }
  980. } else {
  981. // Calls to non-functions, such as calls to generic entity names, might be
  982. // constant.
  983. }
  984. // If the arguments aren't constant, this is not a constant call.
  985. if (!ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  986. &phase)) {
  987. return SemIR::ConstantId::NotConstant;
  988. }
  989. if (phase == Phase::UnknownDueToError) {
  990. return SemIR::ConstantId::Error;
  991. }
  992. // Handle calls to builtins.
  993. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  994. return MakeConstantForBuiltinCall(
  995. eval_context.context(), loc, call, builtin_kind,
  996. eval_context.inst_blocks().Get(call.args_id), phase);
  997. }
  998. return SemIR::ConstantId::NotConstant;
  999. }
  1000. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1001. static auto TryEvalInstInContext(EvalContext& eval_context,
  1002. SemIR::InstId inst_id, SemIR::Inst inst)
  1003. -> SemIR::ConstantId {
  1004. // TODO: Ensure we have test coverage for each of these cases that can result
  1005. // in a constant, once those situations are all reachable.
  1006. CARBON_KIND_SWITCH(inst) {
  1007. // These cases are constants if their operands are.
  1008. case SemIR::AddrOf::Kind:
  1009. return RebuildIfFieldsAreConstant(eval_context, inst,
  1010. &SemIR::AddrOf::type_id,
  1011. &SemIR::AddrOf::lvalue_id);
  1012. case CARBON_KIND(SemIR::ArrayType array_type): {
  1013. return RebuildAndValidateIfFieldsAreConstant(
  1014. eval_context, inst,
  1015. [&](SemIR::ArrayType result) {
  1016. auto bound_id = array_type.bound_id;
  1017. auto int_bound =
  1018. eval_context.insts().TryGetAs<SemIR::IntValue>(result.bound_id);
  1019. if (!int_bound) {
  1020. // TODO: Permit symbolic array bounds. This will require fixing
  1021. // callers of `GetArrayBoundValue`.
  1022. eval_context.context().TODO(bound_id, "symbolic array bound");
  1023. return false;
  1024. }
  1025. // TODO: We should check that the size of the resulting array type
  1026. // fits in 64 bits, not just that the bound does. Should we use a
  1027. // 32-bit limit for 32-bit targets?
  1028. const auto& bound_val = eval_context.ints().Get(int_bound->int_id);
  1029. if (eval_context.types().IsSignedInt(int_bound->type_id) &&
  1030. bound_val.isNegative()) {
  1031. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  1032. "array bound of {0} is negative", TypedInt);
  1033. eval_context.emitter().Emit(
  1034. bound_id, ArrayBoundNegative,
  1035. {.type = int_bound->type_id, .value = bound_val});
  1036. return false;
  1037. }
  1038. if (bound_val.getActiveBits() > 64) {
  1039. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  1040. "array bound of {0} is too large", TypedInt);
  1041. eval_context.emitter().Emit(
  1042. bound_id, ArrayBoundTooLarge,
  1043. {.type = int_bound->type_id, .value = bound_val});
  1044. return false;
  1045. }
  1046. return true;
  1047. },
  1048. &SemIR::ArrayType::bound_id, &SemIR::ArrayType::element_type_id);
  1049. }
  1050. case SemIR::AssociatedEntity::Kind:
  1051. return RebuildIfFieldsAreConstant(eval_context, inst,
  1052. &SemIR::AssociatedEntity::type_id);
  1053. case SemIR::AssociatedEntityType::Kind:
  1054. return RebuildIfFieldsAreConstant(
  1055. eval_context, inst, &SemIR::AssociatedEntityType::interface_type_id,
  1056. &SemIR::AssociatedEntityType::entity_type_id);
  1057. case SemIR::BoundMethod::Kind:
  1058. return RebuildIfFieldsAreConstant(
  1059. eval_context, inst, &SemIR::BoundMethod::type_id,
  1060. &SemIR::BoundMethod::object_id, &SemIR::BoundMethod::function_id);
  1061. case SemIR::ClassType::Kind:
  1062. return RebuildIfFieldsAreConstant(eval_context, inst,
  1063. &SemIR::ClassType::specific_id);
  1064. case SemIR::CompleteTypeWitness::Kind:
  1065. return RebuildIfFieldsAreConstant(
  1066. eval_context, inst, &SemIR::CompleteTypeWitness::object_repr_id);
  1067. case SemIR::FunctionType::Kind:
  1068. return RebuildIfFieldsAreConstant(eval_context, inst,
  1069. &SemIR::FunctionType::specific_id);
  1070. case SemIR::GenericClassType::Kind:
  1071. return RebuildIfFieldsAreConstant(
  1072. eval_context, inst, &SemIR::GenericClassType::enclosing_specific_id);
  1073. case SemIR::GenericInterfaceType::Kind:
  1074. return RebuildIfFieldsAreConstant(
  1075. eval_context, inst,
  1076. &SemIR::GenericInterfaceType::enclosing_specific_id);
  1077. case SemIR::InterfaceType::Kind:
  1078. return RebuildIfFieldsAreConstant(eval_context, inst,
  1079. &SemIR::InterfaceType::specific_id);
  1080. case SemIR::InterfaceWitness::Kind:
  1081. return RebuildIfFieldsAreConstant(eval_context, inst,
  1082. &SemIR::InterfaceWitness::elements_id);
  1083. case CARBON_KIND(SemIR::IntType int_type): {
  1084. return RebuildAndValidateIfFieldsAreConstant(
  1085. eval_context, inst,
  1086. [&](SemIR::IntType result) {
  1087. return ValidateIntType(
  1088. eval_context.context(),
  1089. inst_id.is_valid() ? inst_id : int_type.bit_width_id, result);
  1090. },
  1091. &SemIR::IntType::bit_width_id);
  1092. }
  1093. case SemIR::PointerType::Kind:
  1094. return RebuildIfFieldsAreConstant(eval_context, inst,
  1095. &SemIR::PointerType::pointee_id);
  1096. case CARBON_KIND(SemIR::FloatType float_type): {
  1097. return RebuildAndValidateIfFieldsAreConstant(
  1098. eval_context, inst,
  1099. [&](SemIR::FloatType result) {
  1100. return ValidateFloatType(eval_context.context(),
  1101. float_type.bit_width_id, result);
  1102. },
  1103. &SemIR::FloatType::bit_width_id);
  1104. }
  1105. case SemIR::SpecificFunction::Kind:
  1106. return RebuildIfFieldsAreConstant(eval_context, inst,
  1107. &SemIR::SpecificFunction::callee_id,
  1108. &SemIR::SpecificFunction::specific_id);
  1109. case SemIR::StructType::Kind:
  1110. return RebuildIfFieldsAreConstant(eval_context, inst,
  1111. &SemIR::StructType::fields_id);
  1112. case SemIR::StructTypeField::Kind:
  1113. return RebuildIfFieldsAreConstant(eval_context, inst,
  1114. &SemIR::StructTypeField::field_type_id);
  1115. case SemIR::StructValue::Kind:
  1116. return RebuildIfFieldsAreConstant(eval_context, inst,
  1117. &SemIR::StructValue::type_id,
  1118. &SemIR::StructValue::elements_id);
  1119. case SemIR::TupleType::Kind:
  1120. return RebuildIfFieldsAreConstant(eval_context, inst,
  1121. &SemIR::TupleType::elements_id);
  1122. case SemIR::TupleValue::Kind:
  1123. return RebuildIfFieldsAreConstant(eval_context, inst,
  1124. &SemIR::TupleValue::type_id,
  1125. &SemIR::TupleValue::elements_id);
  1126. case SemIR::UnboundElementType::Kind:
  1127. return RebuildIfFieldsAreConstant(
  1128. eval_context, inst, &SemIR::UnboundElementType::class_type_id,
  1129. &SemIR::UnboundElementType::element_type_id);
  1130. // Initializers evaluate to a value of the object representation.
  1131. case SemIR::ArrayInit::Kind:
  1132. // TODO: Add an `ArrayValue` to represent a constant array object
  1133. // representation instead of using a `TupleValue`.
  1134. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1135. case SemIR::ClassInit::Kind:
  1136. // TODO: Add a `ClassValue` to represent a constant class object
  1137. // representation instead of using a `StructValue`.
  1138. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1139. case SemIR::StructInit::Kind:
  1140. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1141. case SemIR::TupleInit::Kind:
  1142. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1143. case SemIR::BuiltinInst::Kind:
  1144. // Builtins are always template constants.
  1145. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1146. case CARBON_KIND(SemIR::FunctionDecl fn_decl): {
  1147. return TransformIfFieldsAreConstant(
  1148. eval_context, fn_decl,
  1149. [&](SemIR::FunctionDecl result) {
  1150. return SemIR::StructValue{.type_id = result.type_id,
  1151. .elements_id = SemIR::InstBlockId::Empty};
  1152. },
  1153. &SemIR::FunctionDecl::type_id);
  1154. }
  1155. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  1156. // If the class has generic parameters, we don't produce a class type, but
  1157. // a callable whose return value is a class type.
  1158. if (eval_context.classes().Get(class_decl.class_id).has_parameters()) {
  1159. return TransformIfFieldsAreConstant(
  1160. eval_context, class_decl,
  1161. [&](SemIR::ClassDecl result) {
  1162. return SemIR::StructValue{
  1163. .type_id = result.type_id,
  1164. .elements_id = SemIR::InstBlockId::Empty};
  1165. },
  1166. &SemIR::ClassDecl::type_id);
  1167. }
  1168. // A non-generic class declaration evaluates to the class type.
  1169. return MakeConstantResult(
  1170. eval_context.context(),
  1171. SemIR::ClassType{.type_id = SemIR::TypeId::TypeType,
  1172. .class_id = class_decl.class_id,
  1173. .specific_id = SemIR::SpecificId::Invalid},
  1174. Phase::Template);
  1175. }
  1176. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  1177. // If the interface has generic parameters, we don't produce an interface
  1178. // type, but a callable whose return value is an interface type.
  1179. if (eval_context.interfaces()
  1180. .Get(interface_decl.interface_id)
  1181. .has_parameters()) {
  1182. return TransformIfFieldsAreConstant(
  1183. eval_context, interface_decl,
  1184. [&](SemIR::InterfaceDecl result) {
  1185. return SemIR::StructValue{
  1186. .type_id = result.type_id,
  1187. .elements_id = SemIR::InstBlockId::Empty};
  1188. },
  1189. &SemIR::InterfaceDecl::type_id);
  1190. }
  1191. // A non-generic interface declaration evaluates to the interface type.
  1192. return MakeConstantResult(
  1193. eval_context.context(),
  1194. SemIR::InterfaceType{.type_id = SemIR::TypeId::TypeType,
  1195. .interface_id = interface_decl.interface_id,
  1196. .specific_id = SemIR::SpecificId::Invalid},
  1197. Phase::Template);
  1198. }
  1199. case CARBON_KIND(SemIR::SpecificConstant specific): {
  1200. // Pull the constant value out of the specific.
  1201. return SemIR::GetConstantValueInSpecific(
  1202. eval_context.sem_ir(), specific.specific_id, specific.inst_id);
  1203. }
  1204. // These cases are treated as being the unique canonical definition of the
  1205. // corresponding constant value.
  1206. // TODO: This doesn't properly handle redeclarations. Consider adding a
  1207. // corresponding `Value` inst for each of these cases, or returning the
  1208. // first declaration.
  1209. case SemIR::AssociatedConstantDecl::Kind:
  1210. case SemIR::BaseDecl::Kind:
  1211. case SemIR::FieldDecl::Kind:
  1212. case SemIR::ImplDecl::Kind:
  1213. case SemIR::Namespace::Kind:
  1214. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  1215. case SemIR::BoolLiteral::Kind:
  1216. case SemIR::FloatLiteral::Kind:
  1217. case SemIR::IntValue::Kind:
  1218. case SemIR::StringLiteral::Kind:
  1219. // Promote literals to the constant block.
  1220. // TODO: Convert literals into a canonical form. Currently we can form two
  1221. // different `i32` constants with the same value if they are represented
  1222. // by `APInt`s with different bit widths.
  1223. // TODO: Can the type of an IntValue or FloatLiteral be symbolic? If so,
  1224. // we may need to rebuild.
  1225. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1226. // The elements of a constant aggregate can be accessed.
  1227. case SemIR::ClassElementAccess::Kind:
  1228. case SemIR::InterfaceWitnessAccess::Kind:
  1229. case SemIR::StructAccess::Kind:
  1230. case SemIR::TupleAccess::Kind:
  1231. return PerformAggregateAccess(eval_context, inst);
  1232. case CARBON_KIND(SemIR::ArrayIndex index): {
  1233. return PerformArrayIndex(eval_context, index);
  1234. }
  1235. case CARBON_KIND(SemIR::Call call): {
  1236. return MakeConstantForCall(eval_context, inst_id, call);
  1237. }
  1238. // TODO: These need special handling.
  1239. case SemIR::BindValue::Kind:
  1240. case SemIR::Deref::Kind:
  1241. case SemIR::ImportRefLoaded::Kind:
  1242. case SemIR::ReturnSlot::Kind:
  1243. case SemIR::Temporary::Kind:
  1244. case SemIR::TemporaryStorage::Kind:
  1245. case SemIR::ValueAsRef::Kind:
  1246. break;
  1247. case CARBON_KIND(SemIR::SymbolicBindingPattern bind): {
  1248. // TODO: disable constant evaluation of SymbolicBindingPattern once
  1249. // DeduceGenericCallArguments no longer needs implicit params to have
  1250. // constant values.
  1251. const auto& bind_name =
  1252. eval_context.entity_names().Get(bind.entity_name_id);
  1253. // If we know which specific we're evaluating within and this is an
  1254. // argument of that specific, its constant value is the corresponding
  1255. // argument value.
  1256. if (auto value =
  1257. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1258. value.is_valid()) {
  1259. return value;
  1260. }
  1261. // The constant form of a symbolic binding is an idealized form of the
  1262. // original, with no equivalent value.
  1263. bind.entity_name_id =
  1264. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1265. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1266. }
  1267. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  1268. const auto& bind_name =
  1269. eval_context.entity_names().Get(bind.entity_name_id);
  1270. // If we know which specific we're evaluating within and this is an
  1271. // argument of that specific, its constant value is the corresponding
  1272. // argument value.
  1273. if (auto value =
  1274. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1275. value.is_valid()) {
  1276. return value;
  1277. }
  1278. // The constant form of a symbolic binding is an idealized form of the
  1279. // original, with no equivalent value.
  1280. bind.entity_name_id =
  1281. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1282. bind.value_id = SemIR::InstId::Invalid;
  1283. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1284. }
  1285. // These semantic wrappers don't change the constant value.
  1286. case CARBON_KIND(SemIR::AsCompatible inst): {
  1287. return eval_context.GetConstantValue(inst.source_id);
  1288. }
  1289. case CARBON_KIND(SemIR::BindAlias typed_inst): {
  1290. return eval_context.GetConstantValue(typed_inst.value_id);
  1291. }
  1292. case CARBON_KIND(SemIR::ExportDecl typed_inst): {
  1293. return eval_context.GetConstantValue(typed_inst.value_id);
  1294. }
  1295. case CARBON_KIND(SemIR::NameRef typed_inst): {
  1296. return eval_context.GetConstantValue(typed_inst.value_id);
  1297. }
  1298. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  1299. // TODO: treat this as a non-expression (here and in GetExprCategory)
  1300. // once generic deduction doesn't need patterns to have constant values.
  1301. return eval_context.GetConstantValue(param_pattern.subpattern_id);
  1302. }
  1303. case CARBON_KIND(SemIR::Converted typed_inst): {
  1304. return eval_context.GetConstantValue(typed_inst.result_id);
  1305. }
  1306. case CARBON_KIND(SemIR::InitializeFrom typed_inst): {
  1307. return eval_context.GetConstantValue(typed_inst.src_id);
  1308. }
  1309. case CARBON_KIND(SemIR::SpliceBlock typed_inst): {
  1310. return eval_context.GetConstantValue(typed_inst.result_id);
  1311. }
  1312. case CARBON_KIND(SemIR::ValueOfInitializer typed_inst): {
  1313. return eval_context.GetConstantValue(typed_inst.init_id);
  1314. }
  1315. case CARBON_KIND(SemIR::FacetTypeAccess typed_inst): {
  1316. // TODO: Once we start tracking the witness in the facet value, remove it
  1317. // here. For now, we model a facet value as just a type.
  1318. return eval_context.GetConstantValue(typed_inst.facet_id);
  1319. }
  1320. case CARBON_KIND(SemIR::WhereExpr typed_inst): {
  1321. // TODO: This currently ignores the requirements and just produces the
  1322. // left-hand type argument to the `where`.
  1323. return eval_context.GetConstantValue(
  1324. eval_context.insts().Get(typed_inst.period_self_id).type_id());
  1325. }
  1326. // `not true` -> `false`, `not false` -> `true`.
  1327. // All other uses of unary `not` are non-constant.
  1328. case CARBON_KIND(SemIR::UnaryOperatorNot typed_inst): {
  1329. auto const_id = eval_context.GetConstantValue(typed_inst.operand_id);
  1330. auto phase = GetPhase(const_id);
  1331. if (phase == Phase::Template) {
  1332. auto value = eval_context.insts().GetAs<SemIR::BoolLiteral>(
  1333. eval_context.constant_values().GetInstId(const_id));
  1334. return MakeBoolResult(eval_context.context(), value.type_id,
  1335. !value.value.ToBool());
  1336. }
  1337. if (phase == Phase::UnknownDueToError) {
  1338. return SemIR::ConstantId::Error;
  1339. }
  1340. break;
  1341. }
  1342. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  1343. // to itself.
  1344. case CARBON_KIND(SemIR::ConstType typed_inst): {
  1345. auto phase = Phase::Template;
  1346. auto inner_id =
  1347. GetConstantValue(eval_context, typed_inst.inner_id, &phase);
  1348. if (eval_context.context().types().Is<SemIR::ConstType>(inner_id)) {
  1349. return eval_context.context().types().GetConstantId(inner_id);
  1350. }
  1351. typed_inst.inner_id = inner_id;
  1352. return MakeConstantResult(eval_context.context(), typed_inst, phase);
  1353. }
  1354. // These cases are either not expressions or not constant.
  1355. case SemIR::AdaptDecl::Kind:
  1356. case SemIR::AddrPattern::Kind:
  1357. case SemIR::Assign::Kind:
  1358. case SemIR::BindName::Kind:
  1359. case SemIR::BindingPattern::Kind:
  1360. case SemIR::BlockArg::Kind:
  1361. case SemIR::Branch::Kind:
  1362. case SemIR::BranchIf::Kind:
  1363. case SemIR::BranchWithArg::Kind:
  1364. case SemIR::ImportDecl::Kind:
  1365. case SemIR::OutParam::Kind:
  1366. case SemIR::OutParamPattern::Kind:
  1367. case SemIR::RequirementEquivalent::Kind:
  1368. case SemIR::RequirementImpls::Kind:
  1369. case SemIR::RequirementRewrite::Kind:
  1370. case SemIR::Return::Kind:
  1371. case SemIR::ReturnExpr::Kind:
  1372. case SemIR::ReturnSlotPattern::Kind:
  1373. case SemIR::StructLiteral::Kind:
  1374. case SemIR::TupleLiteral::Kind:
  1375. case SemIR::ValueParam::Kind:
  1376. case SemIR::VarStorage::Kind:
  1377. break;
  1378. case SemIR::ImportRefUnloaded::Kind:
  1379. CARBON_FATAL("ImportRefUnloaded should be loaded before TryEvalInst: {0}",
  1380. inst);
  1381. }
  1382. return SemIR::ConstantId::NotConstant;
  1383. }
  1384. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  1385. -> SemIR::ConstantId {
  1386. EvalContext eval_context(context);
  1387. return TryEvalInstInContext(eval_context, inst_id, inst);
  1388. }
  1389. auto TryEvalBlockForSpecific(Context& context, SemIR::SpecificId specific_id,
  1390. SemIR::GenericInstIndex::Region region)
  1391. -> SemIR::InstBlockId {
  1392. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1393. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1394. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1395. llvm::SmallVector<SemIR::InstId> result;
  1396. result.resize(eval_block.size(), SemIR::InstId::Invalid);
  1397. EvalContext eval_context(context, specific_id,
  1398. SpecificEvalInfo{
  1399. .region = region,
  1400. .values = result,
  1401. });
  1402. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1403. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1404. context.insts().Get(inst_id));
  1405. result[i] = context.constant_values().GetInstId(const_id);
  1406. // TODO: If this becomes possible through monomorphization failure, produce
  1407. // a diagnostic and put `SemIR::InstId::BuiltinError` in the table entry.
  1408. CARBON_CHECK(result[i].is_valid());
  1409. }
  1410. return context.inst_blocks().Add(result);
  1411. }
  1412. } // namespace Carbon::Check