eval.cpp 69 KB

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