eval.cpp 65 KB

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