eval.cpp 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936
  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, SemIRLoc fallback_loc,
  30. SemIR::SpecificId specific_id = SemIR::SpecificId::Invalid,
  31. std::optional<SpecificEvalInfo> specific_eval_info = std::nullopt)
  32. : context_(context),
  33. fallback_loc_(fallback_loc),
  34. specific_id_(specific_id),
  35. specific_eval_info_(specific_eval_info) {}
  36. // Gets the location to use for diagnostics if a better location is
  37. // unavailable.
  38. // TODO: This is also sometimes unavailable.
  39. auto fallback_loc() const -> SemIRLoc { return fallback_loc_; }
  40. // Returns a location to use to point at an instruction in a diagnostic, given
  41. // a list of instructions that might have an attached location. This is the
  42. // location of the first instruction in the list that has a location if there
  43. // is one, and otherwise the fallback location.
  44. auto GetDiagnosticLoc(llvm::ArrayRef<SemIR::InstId> inst_ids) -> SemIRLoc {
  45. for (auto inst_id : inst_ids) {
  46. if (inst_id.is_valid() && context_.insts().GetLocId(inst_id).is_valid()) {
  47. return inst_id;
  48. }
  49. }
  50. return fallback_loc_;
  51. }
  52. // Gets the value of the specified compile-time binding in this context.
  53. // Returns `Invalid` if the value is not fixed in this context.
  54. auto GetCompileTimeBindValue(SemIR::CompileTimeBindIndex bind_index)
  55. -> SemIR::ConstantId {
  56. if (!bind_index.is_valid() || !specific_id_.is_valid()) {
  57. return SemIR::ConstantId::Invalid;
  58. }
  59. const auto& specific = specifics().Get(specific_id_);
  60. auto args = inst_blocks().Get(specific.args_id);
  61. // Bindings past the ones with known arguments can appear as local
  62. // bindings of entities declared within this generic.
  63. if (static_cast<size_t>(bind_index.index) >= args.size()) {
  64. return SemIR::ConstantId::Invalid;
  65. }
  66. return constant_values().Get(args[bind_index.index]);
  67. }
  68. // Given a constant value from the SemIR we're evaluating, finds the
  69. // corresponding constant value to use in the context of this evaluation.
  70. // This can be different if the original SemIR is for a generic and we are
  71. // evaluating with specific arguments for the generic parameters.
  72. auto GetInContext(SemIR::ConstantId const_id) -> SemIR::ConstantId {
  73. if (!const_id.is_symbolic()) {
  74. return const_id;
  75. }
  76. // While resolving a specific, map from previous instructions in the eval
  77. // block into their evaluated values. These values won't be present on the
  78. // specific itself yet, so `GetConstantInSpecific` won't be able to find
  79. // them.
  80. if (specific_eval_info_) {
  81. const auto& symbolic_info =
  82. constant_values().GetSymbolicConstant(const_id);
  83. if (symbolic_info.index.is_valid() &&
  84. symbolic_info.generic_id ==
  85. specifics().Get(specific_id_).generic_id &&
  86. symbolic_info.index.region() == specific_eval_info_->region) {
  87. auto inst_id = specific_eval_info_->values[symbolic_info.index.index()];
  88. CARBON_CHECK(inst_id.is_valid(),
  89. "Forward reference in eval block: index {0} referenced "
  90. "before evaluation",
  91. symbolic_info.index.index());
  92. return constant_values().Get(inst_id);
  93. }
  94. }
  95. // Map from a specific constant value to the canonical value.
  96. return GetConstantInSpecific(sem_ir(), specific_id_, const_id);
  97. }
  98. // Gets the constant value of the specified instruction in this context.
  99. auto GetConstantValue(SemIR::InstId inst_id) -> SemIR::ConstantId {
  100. return GetInContext(constant_values().Get(inst_id));
  101. }
  102. // Gets the constant value of the specified type in this context.
  103. auto GetConstantValue(SemIR::TypeId type_id) -> SemIR::ConstantId {
  104. return GetInContext(types().GetConstantId(type_id));
  105. }
  106. // Gets the constant value of the specified type in this context.
  107. auto GetConstantValueAsType(SemIR::TypeId id) -> SemIR::TypeId {
  108. return context().GetTypeIdForTypeConstant(GetConstantValue(id));
  109. }
  110. // Gets the instruction describing the constant value of the specified type in
  111. // this context.
  112. auto GetConstantValueAsInst(SemIR::TypeId id) -> SemIR::Inst {
  113. return insts().Get(
  114. context().constant_values().GetInstId(GetConstantValue(id)));
  115. }
  116. auto ints() -> SharedValueStores::IntStore& { return sem_ir().ints(); }
  117. auto floats() -> SharedValueStores::FloatStore& { return sem_ir().floats(); }
  118. auto entity_names() -> SemIR::EntityNameStore& {
  119. return sem_ir().entity_names();
  120. }
  121. auto functions() -> const ValueStore<SemIR::FunctionId>& {
  122. return sem_ir().functions();
  123. }
  124. auto classes() -> const ValueStore<SemIR::ClassId>& {
  125. return sem_ir().classes();
  126. }
  127. auto interfaces() -> const ValueStore<SemIR::InterfaceId>& {
  128. return sem_ir().interfaces();
  129. }
  130. auto facet_types() -> CanonicalValueStore<SemIR::FacetTypeId>& {
  131. return sem_ir().facet_types();
  132. }
  133. auto specifics() -> const SemIR::SpecificStore& {
  134. return sem_ir().specifics();
  135. }
  136. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  137. return sem_ir().type_blocks();
  138. }
  139. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  140. auto inst_blocks() -> SemIR::InstBlockStore& {
  141. return sem_ir().inst_blocks();
  142. }
  143. // Gets the constant value store. Note that this does not provide the constant
  144. // values that should be used from this evaluation context, and so should be
  145. // used with caution.
  146. auto constant_values() -> const SemIR::ConstantValueStore& {
  147. return sem_ir().constant_values();
  148. }
  149. // Gets the types store. Note that this does not provide the type values that
  150. // should be used from this evaluation context, and so should be used with
  151. // caution.
  152. auto types() -> const SemIR::TypeStore& { return sem_ir().types(); }
  153. auto context() -> Context& { return context_; }
  154. auto sem_ir() -> SemIR::File& { return context().sem_ir(); }
  155. auto emitter() -> Context::DiagnosticEmitter& { return context().emitter(); }
  156. private:
  157. // The type-checking context in which we're performing evaluation.
  158. Context& context_;
  159. // The location to use for diagnostics when a better location isn't available.
  160. SemIRLoc fallback_loc_;
  161. // The specific that we are evaluating within.
  162. SemIR::SpecificId specific_id_;
  163. // If we are currently evaluating an eval block for `specific_id_`,
  164. // information about that evaluation.
  165. std::optional<SpecificEvalInfo> specific_eval_info_;
  166. };
  167. } // namespace
  168. namespace {
  169. // The evaluation phase for an expression, computed by evaluation. These are
  170. // ordered so that the phase of an expression is the numerically highest phase
  171. // of its constituent evaluations. Note that an expression with any runtime
  172. // component is known to have Runtime phase even if it involves an evaluation
  173. // with UnknownDueToError phase.
  174. enum class Phase : uint8_t {
  175. // Value could be entirely and concretely computed.
  176. Template,
  177. // Evaluation phase is symbolic because the expression involves specifically a
  178. // reference to `.Self`.
  179. PeriodSelfSymbolic,
  180. // Evaluation phase is symbolic because the expression involves a reference to
  181. // a symbolic binding.
  182. Symbolic,
  183. // The evaluation phase is unknown because evaluation encountered an
  184. // already-diagnosed semantic or syntax error. This is treated as being
  185. // potentially constant, but with an unknown phase.
  186. UnknownDueToError,
  187. // The expression has runtime phase because of a non-constant subexpression.
  188. Runtime,
  189. };
  190. } // namespace
  191. // Gets the phase in which the value of a constant will become available.
  192. static auto GetPhase(EvalContext& eval_context, SemIR::ConstantId constant_id)
  193. -> Phase {
  194. if (!constant_id.is_constant()) {
  195. return Phase::Runtime;
  196. } else if (constant_id == SemIR::ErrorInst::SingletonConstantId) {
  197. return Phase::UnknownDueToError;
  198. } else if (constant_id.is_template()) {
  199. return Phase::Template;
  200. } else if (eval_context.constant_values().DependsOnGenericParameter(
  201. constant_id)) {
  202. return Phase::Symbolic;
  203. } else {
  204. CARBON_CHECK(constant_id.is_symbolic());
  205. return Phase::PeriodSelfSymbolic;
  206. }
  207. }
  208. // Returns the later of two phases.
  209. static auto LatestPhase(Phase a, Phase b) -> Phase {
  210. return static_cast<Phase>(
  211. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  212. }
  213. // `where` expressions using `.Self` should not be considered symbolic
  214. // - `Interface where .Self impls I and .A = bool` -> template
  215. // - `T:! type` ... `Interface where .A = T` -> symbolic, since uses `T` which
  216. // is symbolic and not due to `.Self`.
  217. static auto UpdatePhaseIgnorePeriodSelf(EvalContext& eval_context,
  218. SemIR::ConstantId constant_id,
  219. Phase* phase) {
  220. Phase constant_phase = GetPhase(eval_context, constant_id);
  221. // Since LatestPhase(x, Phase::Template) == x, this is equivalent to replacing
  222. // Phase::PeriodSelfSymbolic with Phase::Template.
  223. if (constant_phase != Phase::PeriodSelfSymbolic) {
  224. *phase = LatestPhase(*phase, constant_phase);
  225. }
  226. }
  227. // Forms a `constant_id` describing a given evaluation result.
  228. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  229. -> SemIR::ConstantId {
  230. switch (phase) {
  231. case Phase::Template:
  232. return context.constants().GetOrAdd(inst,
  233. SemIR::ConstantStore::IsTemplate);
  234. case Phase::PeriodSelfSymbolic:
  235. return context.constants().GetOrAdd(
  236. inst, SemIR::ConstantStore::IsPeriodSelfSymbolic);
  237. case Phase::Symbolic:
  238. return context.constants().GetOrAdd(inst,
  239. SemIR::ConstantStore::IsSymbolic);
  240. case Phase::UnknownDueToError:
  241. return SemIR::ErrorInst::SingletonConstantId;
  242. case Phase::Runtime:
  243. return SemIR::ConstantId::NotConstant;
  244. }
  245. }
  246. // Forms a `constant_id` describing why an evaluation was not constant.
  247. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  248. return phase == Phase::UnknownDueToError
  249. ? SemIR::ErrorInst::SingletonConstantId
  250. : SemIR::ConstantId::NotConstant;
  251. }
  252. // Converts a bool value into a ConstantId.
  253. static auto MakeBoolResult(Context& context, SemIR::TypeId bool_type_id,
  254. bool result) -> SemIR::ConstantId {
  255. return MakeConstantResult(
  256. context,
  257. SemIR::BoolLiteral{.type_id = bool_type_id,
  258. .value = SemIR::BoolValue::From(result)},
  259. Phase::Template);
  260. }
  261. // Converts an APInt value into a ConstantId.
  262. static auto MakeIntResult(Context& context, SemIR::TypeId type_id,
  263. bool is_signed, llvm::APInt value)
  264. -> SemIR::ConstantId {
  265. CARBON_CHECK(is_signed == context.types().IsSignedInt(type_id));
  266. auto result = is_signed ? context.ints().AddSigned(std::move(value))
  267. : context.ints().AddUnsigned(std::move(value));
  268. return MakeConstantResult(
  269. context, SemIR::IntValue{.type_id = type_id, .int_id = result},
  270. Phase::Template);
  271. }
  272. // Converts an APFloat value into a ConstantId.
  273. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  274. llvm::APFloat value) -> SemIR::ConstantId {
  275. auto result = context.floats().Add(std::move(value));
  276. return MakeConstantResult(
  277. context, SemIR::FloatLiteral{.type_id = type_id, .float_id = result},
  278. Phase::Template);
  279. }
  280. // `GetConstantValue` checks to see whether the provided ID describes a value
  281. // with constant phase, and if so, returns the corresponding constant value.
  282. // Overloads are provided for different kinds of ID.
  283. // If the given instruction is constant, returns its constant value.
  284. static auto GetConstantValue(EvalContext& eval_context, SemIR::InstId inst_id,
  285. Phase* phase) -> SemIR::InstId {
  286. auto const_id = eval_context.GetConstantValue(inst_id);
  287. *phase = LatestPhase(*phase, GetPhase(eval_context, const_id));
  288. return eval_context.constant_values().GetInstId(const_id);
  289. }
  290. // Given a type which may refer to a generic parameter, returns the
  291. // corresponding type in the evaluation context.
  292. static auto GetConstantValue(EvalContext& eval_context, SemIR::TypeId type_id,
  293. Phase* phase) -> SemIR::TypeId {
  294. auto const_id = eval_context.GetConstantValue(type_id);
  295. *phase = LatestPhase(*phase, GetPhase(eval_context, const_id));
  296. return eval_context.context().GetTypeIdForTypeConstant(const_id);
  297. }
  298. // If the given instruction block contains only constants, returns a
  299. // corresponding block of those values.
  300. static auto GetConstantValue(EvalContext& eval_context,
  301. SemIR::InstBlockId inst_block_id, Phase* phase)
  302. -> SemIR::InstBlockId {
  303. if (!inst_block_id.is_valid()) {
  304. return SemIR::InstBlockId::Invalid;
  305. }
  306. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  307. llvm::SmallVector<SemIR::InstId> const_insts;
  308. for (auto inst_id : insts) {
  309. auto const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  310. if (!const_inst_id.is_valid()) {
  311. return SemIR::InstBlockId::Invalid;
  312. }
  313. // Once we leave the small buffer, we know the first few elements are all
  314. // constant, so it's likely that the entire block is constant. Resize to the
  315. // target size given that we're going to allocate memory now anyway.
  316. if (const_insts.size() == const_insts.capacity()) {
  317. const_insts.reserve(insts.size());
  318. }
  319. const_insts.push_back(const_inst_id);
  320. }
  321. // TODO: If the new block is identical to the original block, and we know the
  322. // old ID was canonical, return the original ID.
  323. return eval_context.inst_blocks().AddCanonical(const_insts);
  324. }
  325. // Compute the constant value of a type block. This may be different from the
  326. // input type block if we have known generic arguments.
  327. static auto GetConstantValue(EvalContext& eval_context,
  328. SemIR::StructTypeFieldsId fields_id, Phase* phase)
  329. -> SemIR::StructTypeFieldsId {
  330. if (!fields_id.is_valid()) {
  331. return SemIR::StructTypeFieldsId::Invalid;
  332. }
  333. auto fields = eval_context.context().struct_type_fields().Get(fields_id);
  334. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  335. for (auto field : fields) {
  336. auto new_type_id = GetConstantValue(eval_context, field.type_id, phase);
  337. if (!new_type_id.is_valid()) {
  338. return SemIR::StructTypeFieldsId::Invalid;
  339. }
  340. // Once we leave the small buffer, we know the first few elements are all
  341. // constant, so it's likely that the entire block is constant. Resize to the
  342. // target size given that we're going to allocate memory now anyway.
  343. if (new_fields.size() == new_fields.capacity()) {
  344. new_fields.reserve(fields.size());
  345. }
  346. new_fields.push_back({.name_id = field.name_id, .type_id = new_type_id});
  347. }
  348. // TODO: If the new block is identical to the original block, and we know the
  349. // old ID was canonical, return the original ID.
  350. return eval_context.context().struct_type_fields().AddCanonical(new_fields);
  351. }
  352. // Compute the constant value of a type block. This may be different from the
  353. // input type block if we have known generic arguments.
  354. static auto GetConstantValue(EvalContext& eval_context,
  355. SemIR::TypeBlockId type_block_id, Phase* phase)
  356. -> SemIR::TypeBlockId {
  357. if (!type_block_id.is_valid()) {
  358. return SemIR::TypeBlockId::Invalid;
  359. }
  360. auto types = eval_context.type_blocks().Get(type_block_id);
  361. llvm::SmallVector<SemIR::TypeId> new_types;
  362. for (auto type_id : types) {
  363. auto new_type_id = GetConstantValue(eval_context, type_id, phase);
  364. if (!new_type_id.is_valid()) {
  365. return SemIR::TypeBlockId::Invalid;
  366. }
  367. // Once we leave the small buffer, we know the first few elements are all
  368. // constant, so it's likely that the entire block is constant. Resize to the
  369. // target size given that we're going to allocate memory now anyway.
  370. if (new_types.size() == new_types.capacity()) {
  371. new_types.reserve(types.size());
  372. }
  373. new_types.push_back(new_type_id);
  374. }
  375. // TODO: If the new block is identical to the original block, and we know the
  376. // old ID was canonical, return the original ID.
  377. return eval_context.type_blocks().AddCanonical(new_types);
  378. }
  379. // The constant value of a specific is the specific with the corresponding
  380. // constant values for its arguments.
  381. static auto GetConstantValue(EvalContext& eval_context,
  382. SemIR::SpecificId specific_id, Phase* phase)
  383. -> SemIR::SpecificId {
  384. if (!specific_id.is_valid()) {
  385. return SemIR::SpecificId::Invalid;
  386. }
  387. const auto& specific = eval_context.specifics().Get(specific_id);
  388. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  389. if (!args_id.is_valid()) {
  390. return SemIR::SpecificId::Invalid;
  391. }
  392. if (args_id == specific.args_id) {
  393. return specific_id;
  394. }
  395. return MakeSpecific(eval_context.context(), eval_context.fallback_loc(),
  396. specific.generic_id, args_id);
  397. }
  398. // Like `GetConstantValue` but does a `FacetTypeId` -> `FacetTypeInfo`
  399. // conversion. Does not perform canonicalization.
  400. static auto GetConstantFacetTypeInfo(EvalContext& eval_context,
  401. SemIR::FacetTypeId facet_type_id,
  402. Phase* phase) -> SemIR::FacetTypeInfo {
  403. SemIR::FacetTypeInfo info = eval_context.facet_types().Get(facet_type_id);
  404. for (auto& interface : info.impls_constraints) {
  405. interface.specific_id =
  406. GetConstantValue(eval_context, interface.specific_id, phase);
  407. }
  408. for (auto& rewrite : info.rewrite_constraints) {
  409. rewrite.lhs_const_id = eval_context.GetInContext(rewrite.lhs_const_id);
  410. rewrite.rhs_const_id = eval_context.GetInContext(rewrite.rhs_const_id);
  411. // `where` requirements using `.Self` should not be considered symbolic
  412. UpdatePhaseIgnorePeriodSelf(eval_context, rewrite.lhs_const_id, phase);
  413. UpdatePhaseIgnorePeriodSelf(eval_context, rewrite.rhs_const_id, phase);
  414. }
  415. // TODO: Process other requirements.
  416. return info;
  417. }
  418. // Replaces the specified field of the given typed instruction with its constant
  419. // value, if it has constant phase. Returns true on success, false if the value
  420. // has runtime phase.
  421. template <typename InstT, typename FieldIdT>
  422. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  423. InstT* inst, FieldIdT InstT::*field,
  424. Phase* phase) -> bool {
  425. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  426. if (!unwrapped.is_valid() && (inst->*field).is_valid()) {
  427. return false;
  428. }
  429. inst->*field = unwrapped;
  430. return true;
  431. }
  432. // If the specified fields of the given typed instruction have constant values,
  433. // replaces the fields with their constant values and builds a corresponding
  434. // constant value. Otherwise returns `ConstantId::NotConstant`. Returns
  435. // `ErrorInst::SingletonConstantId` if any subexpression is an error.
  436. //
  437. // The constant value is then checked by calling `validate_fn(typed_inst)`,
  438. // which should return a `bool` indicating whether the new constant is valid. If
  439. // validation passes, `transform_fn(typed_inst)` is called to produce the final
  440. // constant instruction, and a corresponding ConstantId for the new constant is
  441. // returned. If validation fails, it should produce a suitable error message.
  442. // `ErrorInst::SingletonConstantId` is returned.
  443. template <typename InstT, typename ValidateFn, typename TransformFn,
  444. typename... EachFieldIdT>
  445. static auto RebuildIfFieldsAreConstantImpl(
  446. EvalContext& eval_context, SemIR::Inst inst, ValidateFn validate_fn,
  447. TransformFn transform_fn, EachFieldIdT InstT::*... each_field_id)
  448. -> SemIR::ConstantId {
  449. // Build a constant instruction by replacing each non-constant operand with
  450. // its constant value.
  451. auto typed_inst = inst.As<InstT>();
  452. Phase phase = Phase::Template;
  453. if ((ReplaceFieldWithConstantValue(eval_context, &typed_inst, each_field_id,
  454. &phase) &&
  455. ...)) {
  456. if (phase == Phase::UnknownDueToError || !validate_fn(typed_inst)) {
  457. return SemIR::ErrorInst::SingletonConstantId;
  458. }
  459. return MakeConstantResult(eval_context.context(), transform_fn(typed_inst),
  460. phase);
  461. }
  462. return MakeNonConstantResult(phase);
  463. }
  464. // Same as above but with an identity transform function.
  465. template <typename InstT, typename ValidateFn, typename... EachFieldIdT>
  466. static auto RebuildAndValidateIfFieldsAreConstant(
  467. EvalContext& eval_context, SemIR::Inst inst, ValidateFn validate_fn,
  468. EachFieldIdT InstT::*... each_field_id) -> SemIR::ConstantId {
  469. return RebuildIfFieldsAreConstantImpl(eval_context, inst, validate_fn,
  470. std::identity{}, each_field_id...);
  471. }
  472. // Same as above but with no validation step.
  473. template <typename InstT, typename TransformFn, typename... EachFieldIdT>
  474. static auto TransformIfFieldsAreConstant(EvalContext& eval_context,
  475. SemIR::Inst inst,
  476. TransformFn transform_fn,
  477. EachFieldIdT InstT::*... each_field_id)
  478. -> SemIR::ConstantId {
  479. return RebuildIfFieldsAreConstantImpl(
  480. eval_context, inst, [](...) { return true; }, transform_fn,
  481. each_field_id...);
  482. }
  483. // Same as above but with no validation or transform step.
  484. template <typename InstT, typename... EachFieldIdT>
  485. static auto RebuildIfFieldsAreConstant(EvalContext& eval_context,
  486. SemIR::Inst inst,
  487. EachFieldIdT InstT::*... each_field_id)
  488. -> SemIR::ConstantId {
  489. return RebuildIfFieldsAreConstantImpl(
  490. eval_context, inst, [](...) { return true; }, std::identity{},
  491. each_field_id...);
  492. }
  493. // Rebuilds the given aggregate initialization instruction as a corresponding
  494. // constant aggregate value, if its elements are all constants.
  495. static auto RebuildInitAsValue(EvalContext& eval_context, SemIR::Inst inst,
  496. SemIR::InstKind value_kind)
  497. -> SemIR::ConstantId {
  498. return TransformIfFieldsAreConstant(
  499. eval_context, inst,
  500. [&](SemIR::AnyAggregateInit result) {
  501. return SemIR::AnyAggregateValue{.kind = value_kind,
  502. .type_id = result.type_id,
  503. .elements_id = result.elements_id};
  504. },
  505. &SemIR::AnyAggregateInit::type_id, &SemIR::AnyAggregateInit::elements_id);
  506. }
  507. // Performs an access into an aggregate, retrieving the specified element.
  508. static auto PerformAggregateAccess(EvalContext& eval_context, SemIR::Inst inst)
  509. -> SemIR::ConstantId {
  510. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  511. Phase phase = Phase::Template;
  512. if (ReplaceFieldWithConstantValue(eval_context, &access_inst,
  513. &SemIR::AnyAggregateAccess::aggregate_id,
  514. &phase)) {
  515. if (auto aggregate =
  516. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(
  517. access_inst.aggregate_id)) {
  518. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  519. auto index = static_cast<size_t>(access_inst.index.index);
  520. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  521. // `Phase` is not used here. If this element is a template constant, then
  522. // so is the result of indexing, even if the aggregate also contains a
  523. // symbolic context.
  524. return eval_context.GetConstantValue(elements[index]);
  525. } else {
  526. CARBON_CHECK(phase != Phase::Template,
  527. "Failed to evaluate template constant {0} arg0: {1}", inst,
  528. eval_context.insts().Get(access_inst.aggregate_id));
  529. }
  530. return MakeConstantResult(eval_context.context(), access_inst, phase);
  531. }
  532. return MakeNonConstantResult(phase);
  533. }
  534. // Performs an index into a homogeneous aggregate, retrieving the specified
  535. // element.
  536. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  537. -> SemIR::ConstantId {
  538. Phase phase = Phase::Template;
  539. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  540. if (!index_id.is_valid()) {
  541. return MakeNonConstantResult(phase);
  542. }
  543. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  544. if (!index) {
  545. CARBON_CHECK(phase != Phase::Template,
  546. "Template constant integer should be a literal");
  547. return MakeNonConstantResult(phase);
  548. }
  549. // Array indexing is invalid if the index is constant and out of range,
  550. // regardless of whether the array itself is constant.
  551. const auto& index_val = eval_context.ints().Get(index->int_id);
  552. auto aggregate_type_id = eval_context.GetConstantValueAsType(
  553. eval_context.insts().Get(inst.array_id).type_id());
  554. if (auto array_type =
  555. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  556. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  557. array_type->bound_id)) {
  558. // This awkward call to `getZExtValue` is a workaround for APInt not
  559. // supporting comparisons between integers of different bit widths.
  560. if (index_val.getActiveBits() > 64 ||
  561. eval_context.ints()
  562. .Get(bound->int_id)
  563. .ule(index_val.getZExtValue())) {
  564. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  565. "array index `{0}` is past the end of type {1}",
  566. TypedInt, SemIR::TypeId);
  567. eval_context.emitter().Emit(
  568. eval_context.GetDiagnosticLoc(inst.index_id), ArrayIndexOutOfBounds,
  569. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  570. return SemIR::ErrorInst::SingletonConstantId;
  571. }
  572. }
  573. }
  574. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  575. if (!aggregate_id.is_valid()) {
  576. return MakeNonConstantResult(phase);
  577. }
  578. auto aggregate =
  579. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  580. if (!aggregate) {
  581. CARBON_CHECK(phase != Phase::Template,
  582. "Unexpected representation for template constant aggregate");
  583. return MakeNonConstantResult(phase);
  584. }
  585. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  586. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  587. }
  588. // Enforces that an integer type has a valid bit width.
  589. static auto ValidateIntType(Context& context, SemIRLoc loc,
  590. SemIR::IntType result) -> bool {
  591. auto bit_width =
  592. context.insts().TryGetAs<SemIR::IntValue>(result.bit_width_id);
  593. if (!bit_width) {
  594. // Symbolic bit width.
  595. return true;
  596. }
  597. const auto& bit_width_val = context.ints().Get(bit_width->int_id);
  598. if (bit_width_val.isZero() ||
  599. (context.types().IsSignedInt(bit_width->type_id) &&
  600. bit_width_val.isNegative())) {
  601. CARBON_DIAGNOSTIC(IntWidthNotPositive, Error,
  602. "integer type width of {0} is not positive", TypedInt);
  603. context.emitter().Emit(
  604. loc, IntWidthNotPositive,
  605. {.type = bit_width->type_id, .value = bit_width_val});
  606. return false;
  607. }
  608. // TODO: Pick a maximum size and document it in the design. For now
  609. // we use 2^^23, because that's the largest size that LLVM supports.
  610. constexpr int MaxIntWidth = 1 << 23;
  611. if (bit_width_val.ugt(MaxIntWidth)) {
  612. CARBON_DIAGNOSTIC(IntWidthTooLarge, Error,
  613. "integer type width of {0} is greater than the "
  614. "maximum supported width of {1}",
  615. TypedInt, int);
  616. context.emitter().Emit(loc, IntWidthTooLarge,
  617. {.type = bit_width->type_id, .value = bit_width_val},
  618. MaxIntWidth);
  619. return false;
  620. }
  621. return true;
  622. }
  623. // Forms a constant int type as an evaluation result. Requires that width_id is
  624. // constant.
  625. static auto MakeIntTypeResult(Context& context, SemIRLoc loc,
  626. SemIR::IntKind int_kind, SemIR::InstId width_id,
  627. Phase phase) -> SemIR::ConstantId {
  628. auto result = SemIR::IntType{
  629. .type_id = context.GetSingletonType(SemIR::TypeType::SingletonInstId),
  630. .int_kind = int_kind,
  631. .bit_width_id = width_id};
  632. if (!ValidateIntType(context, loc, result)) {
  633. return SemIR::ErrorInst::SingletonConstantId;
  634. }
  635. return MakeConstantResult(context, result, phase);
  636. }
  637. // Enforces that the bit width is 64 for a float.
  638. static auto ValidateFloatBitWidth(Context& context, SemIRLoc loc,
  639. SemIR::InstId inst_id) -> bool {
  640. auto inst = context.insts().GetAs<SemIR::IntValue>(inst_id);
  641. if (context.ints().Get(inst.int_id) == 64) {
  642. return true;
  643. }
  644. CARBON_DIAGNOSTIC(CompileTimeFloatBitWidth, Error, "bit width must be 64");
  645. context.emitter().Emit(loc, CompileTimeFloatBitWidth);
  646. return false;
  647. }
  648. // Enforces that a float type has a valid bit width.
  649. static auto ValidateFloatType(Context& context, SemIRLoc loc,
  650. SemIR::FloatType result) -> bool {
  651. auto bit_width =
  652. context.insts().TryGetAs<SemIR::IntValue>(result.bit_width_id);
  653. if (!bit_width) {
  654. // Symbolic bit width.
  655. return true;
  656. }
  657. return ValidateFloatBitWidth(context, loc, result.bit_width_id);
  658. }
  659. // Performs a conversion between integer types, diagnosing if the value doesn't
  660. // fit in the destination type.
  661. static auto PerformCheckedIntConvert(Context& context, SemIRLoc loc,
  662. SemIR::InstId arg_id,
  663. SemIR::TypeId dest_type_id)
  664. -> SemIR::ConstantId {
  665. auto arg = context.insts().GetAs<SemIR::IntValue>(arg_id);
  666. auto arg_val = context.ints().Get(arg.int_id);
  667. auto [is_signed, bit_width_id] =
  668. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  669. auto width = bit_width_id.is_valid()
  670. ? context.ints().Get(bit_width_id).getZExtValue()
  671. : arg_val.getBitWidth();
  672. if (!is_signed && arg_val.isNegative()) {
  673. CARBON_DIAGNOSTIC(
  674. NegativeIntInUnsignedType, Error,
  675. "negative integer value {0} converted to unsigned type {1}", TypedInt,
  676. SemIR::TypeId);
  677. context.emitter().Emit(loc, NegativeIntInUnsignedType,
  678. {.type = arg.type_id, .value = arg_val},
  679. dest_type_id);
  680. }
  681. unsigned arg_non_sign_bits = arg_val.getSignificantBits() - 1;
  682. if (arg_non_sign_bits + is_signed > width) {
  683. CARBON_DIAGNOSTIC(IntTooLargeForType, Error,
  684. "integer value {0} too large for type {1}", TypedInt,
  685. SemIR::TypeId);
  686. context.emitter().Emit(loc, IntTooLargeForType,
  687. {.type = arg.type_id, .value = arg_val},
  688. dest_type_id);
  689. }
  690. return MakeConstantResult(
  691. context, SemIR::IntValue{.type_id = dest_type_id, .int_id = arg.int_id},
  692. Phase::Template);
  693. }
  694. // Issues a diagnostic for a compile-time division by zero.
  695. static auto DiagnoseDivisionByZero(Context& context, SemIRLoc loc) -> void {
  696. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  697. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  698. }
  699. // Performs a builtin unary integer -> integer operation.
  700. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLoc loc,
  701. SemIR::BuiltinFunctionKind builtin_kind,
  702. SemIR::InstId arg_id)
  703. -> SemIR::ConstantId {
  704. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  705. auto [is_signed, bit_width_id] =
  706. context.sem_ir().types().GetIntTypeInfo(op.type_id);
  707. CARBON_CHECK(bit_width_id != IntId::Invalid,
  708. "Cannot evaluate a generic bit width integer: {0}", op);
  709. llvm::APInt op_val = context.ints().GetAtWidth(op.int_id, bit_width_id);
  710. switch (builtin_kind) {
  711. case SemIR::BuiltinFunctionKind::IntSNegate:
  712. if (op_val.isMinSignedValue()) {
  713. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  714. "integer overflow in negation of {0}", TypedInt);
  715. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  716. {.type = op.type_id, .value = op_val});
  717. }
  718. op_val.negate();
  719. break;
  720. case SemIR::BuiltinFunctionKind::IntUNegate:
  721. op_val.negate();
  722. break;
  723. case SemIR::BuiltinFunctionKind::IntComplement:
  724. op_val.flipAllBits();
  725. break;
  726. default:
  727. CARBON_FATAL("Unexpected builtin kind");
  728. }
  729. return MakeIntResult(context, op.type_id, is_signed, std::move(op_val));
  730. }
  731. // Performs a builtin binary integer -> integer operation.
  732. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLoc loc,
  733. SemIR::BuiltinFunctionKind builtin_kind,
  734. SemIR::InstId lhs_id,
  735. SemIR::InstId rhs_id)
  736. -> SemIR::ConstantId {
  737. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  738. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  739. // Check for division by zero.
  740. switch (builtin_kind) {
  741. case SemIR::BuiltinFunctionKind::IntSDiv:
  742. case SemIR::BuiltinFunctionKind::IntSMod:
  743. case SemIR::BuiltinFunctionKind::IntUDiv:
  744. case SemIR::BuiltinFunctionKind::IntUMod:
  745. if (context.ints().Get(rhs.int_id).isZero()) {
  746. DiagnoseDivisionByZero(context, loc);
  747. return SemIR::ErrorInst::SingletonConstantId;
  748. }
  749. break;
  750. default:
  751. break;
  752. }
  753. auto [lhs_is_signed, lhs_bit_width_id] =
  754. context.sem_ir().types().GetIntTypeInfo(lhs.type_id);
  755. llvm::APInt lhs_val = context.ints().GetAtWidth(lhs.int_id, lhs_bit_width_id);
  756. llvm::APInt result_val;
  757. // First handle shift, which can directly use the canonical RHS and doesn't
  758. // overflow.
  759. switch (builtin_kind) {
  760. // Bit shift.
  761. case SemIR::BuiltinFunctionKind::IntLeftShift:
  762. case SemIR::BuiltinFunctionKind::IntRightShift: {
  763. const auto& rhs_orig_val = context.ints().Get(rhs.int_id);
  764. if (rhs_orig_val.uge(lhs_val.getBitWidth()) ||
  765. (rhs_orig_val.isNegative() && lhs_is_signed)) {
  766. CARBON_DIAGNOSTIC(
  767. CompileTimeShiftOutOfRange, Error,
  768. "shift distance not in range [0, {0}) in {1} {2:<<|>>} {3}",
  769. unsigned, TypedInt, BoolAsSelect, TypedInt);
  770. context.emitter().Emit(
  771. loc, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  772. {.type = lhs.type_id, .value = lhs_val},
  773. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  774. {.type = rhs.type_id, .value = rhs_orig_val});
  775. // TODO: Is it useful to recover by returning 0 or -1?
  776. return SemIR::ErrorInst::SingletonConstantId;
  777. }
  778. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  779. result_val = lhs_val.shl(rhs_orig_val);
  780. } else if (lhs_is_signed) {
  781. result_val = lhs_val.ashr(rhs_orig_val);
  782. } else {
  783. result_val = lhs_val.lshr(rhs_orig_val);
  784. }
  785. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  786. std::move(result_val));
  787. }
  788. default:
  789. // Break to do additional setup for other builtin kinds.
  790. break;
  791. }
  792. // Other operations are already checked to be homogeneous, so we can extend
  793. // the RHS with the LHS bit width.
  794. CARBON_CHECK(rhs.type_id == lhs.type_id, "Heterogeneous builtin integer op!");
  795. llvm::APInt rhs_val = context.ints().GetAtWidth(rhs.int_id, lhs_bit_width_id);
  796. // We may also need to diagnose overflow for these operations.
  797. bool overflow = false;
  798. Lex::TokenKind op_token = Lex::TokenKind::Not;
  799. switch (builtin_kind) {
  800. // Arithmetic.
  801. case SemIR::BuiltinFunctionKind::IntSAdd:
  802. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  803. op_token = Lex::TokenKind::Plus;
  804. break;
  805. case SemIR::BuiltinFunctionKind::IntSSub:
  806. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  807. op_token = Lex::TokenKind::Minus;
  808. break;
  809. case SemIR::BuiltinFunctionKind::IntSMul:
  810. result_val = lhs_val.smul_ov(rhs_val, overflow);
  811. op_token = Lex::TokenKind::Star;
  812. break;
  813. case SemIR::BuiltinFunctionKind::IntSDiv:
  814. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  815. op_token = Lex::TokenKind::Slash;
  816. break;
  817. case SemIR::BuiltinFunctionKind::IntSMod:
  818. result_val = lhs_val.srem(rhs_val);
  819. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  820. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  821. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  822. op_token = Lex::TokenKind::Percent;
  823. break;
  824. case SemIR::BuiltinFunctionKind::IntUAdd:
  825. result_val = lhs_val + rhs_val;
  826. op_token = Lex::TokenKind::Plus;
  827. break;
  828. case SemIR::BuiltinFunctionKind::IntUSub:
  829. result_val = lhs_val - rhs_val;
  830. op_token = Lex::TokenKind::Minus;
  831. break;
  832. case SemIR::BuiltinFunctionKind::IntUMul:
  833. result_val = lhs_val * rhs_val;
  834. op_token = Lex::TokenKind::Star;
  835. break;
  836. case SemIR::BuiltinFunctionKind::IntUDiv:
  837. result_val = lhs_val.udiv(rhs_val);
  838. op_token = Lex::TokenKind::Slash;
  839. break;
  840. case SemIR::BuiltinFunctionKind::IntUMod:
  841. result_val = lhs_val.urem(rhs_val);
  842. op_token = Lex::TokenKind::Percent;
  843. break;
  844. // Bitwise.
  845. case SemIR::BuiltinFunctionKind::IntAnd:
  846. result_val = lhs_val & rhs_val;
  847. op_token = Lex::TokenKind::And;
  848. break;
  849. case SemIR::BuiltinFunctionKind::IntOr:
  850. result_val = lhs_val | rhs_val;
  851. op_token = Lex::TokenKind::Pipe;
  852. break;
  853. case SemIR::BuiltinFunctionKind::IntXor:
  854. result_val = lhs_val ^ rhs_val;
  855. op_token = Lex::TokenKind::Caret;
  856. break;
  857. case SemIR::BuiltinFunctionKind::IntLeftShift:
  858. case SemIR::BuiltinFunctionKind::IntRightShift:
  859. CARBON_FATAL("Handled specially above.");
  860. default:
  861. CARBON_FATAL("Unexpected operation kind.");
  862. }
  863. if (overflow) {
  864. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  865. "integer overflow in calculation {0} {1} {2}", TypedInt,
  866. Lex::TokenKind, TypedInt);
  867. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  868. {.type = lhs.type_id, .value = lhs_val}, op_token,
  869. {.type = rhs.type_id, .value = rhs_val});
  870. }
  871. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  872. std::move(result_val));
  873. }
  874. // Performs a builtin integer comparison.
  875. static auto PerformBuiltinIntComparison(Context& context,
  876. SemIR::BuiltinFunctionKind builtin_kind,
  877. SemIR::InstId lhs_id,
  878. SemIR::InstId rhs_id,
  879. SemIR::TypeId bool_type_id)
  880. -> SemIR::ConstantId {
  881. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  882. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  883. CARBON_CHECK(lhs.type_id == rhs.type_id,
  884. "Builtin comparison with mismatched types!");
  885. auto [is_signed, bit_width_id] =
  886. context.sem_ir().types().GetIntTypeInfo(lhs.type_id);
  887. CARBON_CHECK(bit_width_id != IntId::Invalid,
  888. "Cannot evaluate a generic bit width integer: {0}", lhs);
  889. llvm::APInt lhs_val = context.ints().GetAtWidth(lhs.int_id, bit_width_id);
  890. llvm::APInt rhs_val = context.ints().GetAtWidth(rhs.int_id, bit_width_id);
  891. bool result;
  892. switch (builtin_kind) {
  893. case SemIR::BuiltinFunctionKind::IntEq:
  894. result = (lhs_val == rhs_val);
  895. break;
  896. case SemIR::BuiltinFunctionKind::IntNeq:
  897. result = (lhs_val != rhs_val);
  898. break;
  899. case SemIR::BuiltinFunctionKind::IntLess:
  900. result = is_signed ? lhs_val.slt(rhs_val) : lhs_val.ult(rhs_val);
  901. break;
  902. case SemIR::BuiltinFunctionKind::IntLessEq:
  903. result = is_signed ? lhs_val.sle(rhs_val) : lhs_val.ule(rhs_val);
  904. break;
  905. case SemIR::BuiltinFunctionKind::IntGreater:
  906. result = is_signed ? lhs_val.sgt(rhs_val) : lhs_val.sgt(rhs_val);
  907. break;
  908. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  909. result = is_signed ? lhs_val.sge(rhs_val) : lhs_val.sge(rhs_val);
  910. break;
  911. default:
  912. CARBON_FATAL("Unexpected operation kind.");
  913. }
  914. return MakeBoolResult(context, bool_type_id, result);
  915. }
  916. // Performs a builtin unary float -> float operation.
  917. static auto PerformBuiltinUnaryFloatOp(Context& context,
  918. SemIR::BuiltinFunctionKind builtin_kind,
  919. SemIR::InstId arg_id)
  920. -> SemIR::ConstantId {
  921. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  922. auto op_val = context.floats().Get(op.float_id);
  923. switch (builtin_kind) {
  924. case SemIR::BuiltinFunctionKind::FloatNegate:
  925. op_val.changeSign();
  926. break;
  927. default:
  928. CARBON_FATAL("Unexpected builtin kind");
  929. }
  930. return MakeFloatResult(context, op.type_id, std::move(op_val));
  931. }
  932. // Performs a builtin binary float -> float operation.
  933. static auto PerformBuiltinBinaryFloatOp(Context& context,
  934. SemIR::BuiltinFunctionKind builtin_kind,
  935. SemIR::InstId lhs_id,
  936. SemIR::InstId rhs_id)
  937. -> SemIR::ConstantId {
  938. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  939. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  940. auto lhs_val = context.floats().Get(lhs.float_id);
  941. auto rhs_val = context.floats().Get(rhs.float_id);
  942. llvm::APFloat result_val(lhs_val.getSemantics());
  943. switch (builtin_kind) {
  944. case SemIR::BuiltinFunctionKind::FloatAdd:
  945. result_val = lhs_val + rhs_val;
  946. break;
  947. case SemIR::BuiltinFunctionKind::FloatSub:
  948. result_val = lhs_val - rhs_val;
  949. break;
  950. case SemIR::BuiltinFunctionKind::FloatMul:
  951. result_val = lhs_val * rhs_val;
  952. break;
  953. case SemIR::BuiltinFunctionKind::FloatDiv:
  954. result_val = lhs_val / rhs_val;
  955. break;
  956. default:
  957. CARBON_FATAL("Unexpected operation kind.");
  958. }
  959. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  960. }
  961. // Performs a builtin float comparison.
  962. static auto PerformBuiltinFloatComparison(
  963. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  964. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  965. -> SemIR::ConstantId {
  966. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  967. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  968. const auto& lhs_val = context.floats().Get(lhs.float_id);
  969. const auto& rhs_val = context.floats().Get(rhs.float_id);
  970. bool result;
  971. switch (builtin_kind) {
  972. case SemIR::BuiltinFunctionKind::FloatEq:
  973. result = (lhs_val == rhs_val);
  974. break;
  975. case SemIR::BuiltinFunctionKind::FloatNeq:
  976. result = (lhs_val != rhs_val);
  977. break;
  978. case SemIR::BuiltinFunctionKind::FloatLess:
  979. result = lhs_val < rhs_val;
  980. break;
  981. case SemIR::BuiltinFunctionKind::FloatLessEq:
  982. result = lhs_val <= rhs_val;
  983. break;
  984. case SemIR::BuiltinFunctionKind::FloatGreater:
  985. result = lhs_val > rhs_val;
  986. break;
  987. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  988. result = lhs_val >= rhs_val;
  989. break;
  990. default:
  991. CARBON_FATAL("Unexpected operation kind.");
  992. }
  993. return MakeBoolResult(context, bool_type_id, result);
  994. }
  995. // Performs a builtin boolean comparison.
  996. static auto PerformBuiltinBoolComparison(
  997. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  998. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id) {
  999. bool lhs = context.insts().GetAs<SemIR::BoolLiteral>(lhs_id).value.ToBool();
  1000. bool rhs = context.insts().GetAs<SemIR::BoolLiteral>(rhs_id).value.ToBool();
  1001. return MakeBoolResult(context, bool_type_id,
  1002. builtin_kind == SemIR::BuiltinFunctionKind::BoolEq
  1003. ? lhs == rhs
  1004. : lhs != rhs);
  1005. }
  1006. // Returns a constant for a call to a builtin function.
  1007. static auto MakeConstantForBuiltinCall(Context& context, SemIRLoc loc,
  1008. SemIR::Call call,
  1009. SemIR::BuiltinFunctionKind builtin_kind,
  1010. llvm::ArrayRef<SemIR::InstId> arg_ids,
  1011. Phase phase) -> SemIR::ConstantId {
  1012. switch (builtin_kind) {
  1013. case SemIR::BuiltinFunctionKind::None:
  1014. CARBON_FATAL("Not a builtin function.");
  1015. case SemIR::BuiltinFunctionKind::PrintChar:
  1016. case SemIR::BuiltinFunctionKind::PrintInt:
  1017. case SemIR::BuiltinFunctionKind::ReadChar: {
  1018. // These are runtime-only builtins.
  1019. // TODO: Consider tracking this on the `BuiltinFunctionKind`.
  1020. return SemIR::ConstantId::NotConstant;
  1021. }
  1022. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  1023. return context.constant_values().Get(
  1024. SemIR::IntLiteralType::SingletonInstId);
  1025. }
  1026. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  1027. return MakeIntTypeResult(context, loc, SemIR::IntKind::Signed, arg_ids[0],
  1028. phase);
  1029. }
  1030. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  1031. return MakeIntTypeResult(context, loc, SemIR::IntKind::Unsigned,
  1032. arg_ids[0], phase);
  1033. }
  1034. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  1035. // TODO: Support a symbolic constant width.
  1036. if (phase != Phase::Template) {
  1037. break;
  1038. }
  1039. if (!ValidateFloatBitWidth(context, loc, arg_ids[0])) {
  1040. return SemIR::ErrorInst::SingletonConstantId;
  1041. }
  1042. return context.constant_values().Get(
  1043. SemIR::LegacyFloatType::SingletonInstId);
  1044. }
  1045. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  1046. return context.constant_values().Get(SemIR::BoolType::SingletonInstId);
  1047. }
  1048. // Integer conversions.
  1049. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  1050. if (phase == Phase::Symbolic) {
  1051. return MakeConstantResult(context, call, phase);
  1052. }
  1053. return PerformCheckedIntConvert(context, loc, arg_ids[0], call.type_id);
  1054. }
  1055. // Unary integer -> integer operations.
  1056. case SemIR::BuiltinFunctionKind::IntSNegate:
  1057. case SemIR::BuiltinFunctionKind::IntUNegate:
  1058. case SemIR::BuiltinFunctionKind::IntComplement: {
  1059. if (phase != Phase::Template) {
  1060. break;
  1061. }
  1062. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  1063. }
  1064. // Binary integer -> integer operations.
  1065. case SemIR::BuiltinFunctionKind::IntSAdd:
  1066. case SemIR::BuiltinFunctionKind::IntSSub:
  1067. case SemIR::BuiltinFunctionKind::IntSMul:
  1068. case SemIR::BuiltinFunctionKind::IntSDiv:
  1069. case SemIR::BuiltinFunctionKind::IntSMod:
  1070. case SemIR::BuiltinFunctionKind::IntUAdd:
  1071. case SemIR::BuiltinFunctionKind::IntUSub:
  1072. case SemIR::BuiltinFunctionKind::IntUMul:
  1073. case SemIR::BuiltinFunctionKind::IntUDiv:
  1074. case SemIR::BuiltinFunctionKind::IntUMod:
  1075. case SemIR::BuiltinFunctionKind::IntAnd:
  1076. case SemIR::BuiltinFunctionKind::IntOr:
  1077. case SemIR::BuiltinFunctionKind::IntXor:
  1078. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1079. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1080. if (phase != Phase::Template) {
  1081. break;
  1082. }
  1083. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  1084. arg_ids[1]);
  1085. }
  1086. // Integer comparisons.
  1087. case SemIR::BuiltinFunctionKind::IntEq:
  1088. case SemIR::BuiltinFunctionKind::IntNeq:
  1089. case SemIR::BuiltinFunctionKind::IntLess:
  1090. case SemIR::BuiltinFunctionKind::IntLessEq:
  1091. case SemIR::BuiltinFunctionKind::IntGreater:
  1092. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1093. if (phase != Phase::Template) {
  1094. break;
  1095. }
  1096. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1097. arg_ids[1], call.type_id);
  1098. }
  1099. // Unary float -> float operations.
  1100. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1101. if (phase != Phase::Template) {
  1102. break;
  1103. }
  1104. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1105. }
  1106. // Binary float -> float operations.
  1107. case SemIR::BuiltinFunctionKind::FloatAdd:
  1108. case SemIR::BuiltinFunctionKind::FloatSub:
  1109. case SemIR::BuiltinFunctionKind::FloatMul:
  1110. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1111. if (phase != Phase::Template) {
  1112. break;
  1113. }
  1114. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1115. arg_ids[1]);
  1116. }
  1117. // Float comparisons.
  1118. case SemIR::BuiltinFunctionKind::FloatEq:
  1119. case SemIR::BuiltinFunctionKind::FloatNeq:
  1120. case SemIR::BuiltinFunctionKind::FloatLess:
  1121. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1122. case SemIR::BuiltinFunctionKind::FloatGreater:
  1123. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1124. if (phase != Phase::Template) {
  1125. break;
  1126. }
  1127. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1128. arg_ids[1], call.type_id);
  1129. }
  1130. // Bool comparisons.
  1131. case SemIR::BuiltinFunctionKind::BoolEq:
  1132. case SemIR::BuiltinFunctionKind::BoolNeq: {
  1133. if (phase != Phase::Template) {
  1134. break;
  1135. }
  1136. return PerformBuiltinBoolComparison(context, builtin_kind, arg_ids[0],
  1137. arg_ids[1], call.type_id);
  1138. }
  1139. }
  1140. return SemIR::ConstantId::NotConstant;
  1141. }
  1142. // Makes a constant for a call instruction.
  1143. static auto MakeConstantForCall(EvalContext& eval_context, SemIRLoc loc,
  1144. SemIR::Call call) -> SemIR::ConstantId {
  1145. Phase phase = Phase::Template;
  1146. // A call with an invalid argument list is used to represent an erroneous
  1147. // call.
  1148. //
  1149. // TODO: Use a better representation for this.
  1150. if (call.args_id == SemIR::InstBlockId::Invalid) {
  1151. return SemIR::ErrorInst::SingletonConstantId;
  1152. }
  1153. // Find the constant value of the callee.
  1154. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1155. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1156. auto callee_function =
  1157. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  1158. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1159. if (callee_function.function_id.is_valid()) {
  1160. // Calls to builtins might be constant.
  1161. builtin_kind = eval_context.functions()
  1162. .Get(callee_function.function_id)
  1163. .builtin_function_kind;
  1164. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  1165. // TODO: Eventually we'll want to treat some kinds of non-builtin
  1166. // functions as producing constants.
  1167. return SemIR::ConstantId::NotConstant;
  1168. }
  1169. } else {
  1170. // Calls to non-functions, such as calls to generic entity names, might be
  1171. // constant.
  1172. }
  1173. // Find the argument values and the return type.
  1174. bool has_constant_operands =
  1175. has_constant_callee &&
  1176. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::type_id,
  1177. &phase) &&
  1178. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1179. &phase);
  1180. if (phase == Phase::UnknownDueToError) {
  1181. return SemIR::ErrorInst::SingletonConstantId;
  1182. }
  1183. // If any operand of the call is non-constant, the call is non-constant.
  1184. // TODO: Some builtin calls might allow some operands to be non-constant.
  1185. if (!has_constant_operands) {
  1186. if (builtin_kind.IsCompTimeOnly()) {
  1187. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1188. "non-constant call to compile-time-only function");
  1189. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1190. "compile-time-only function declared here");
  1191. eval_context.emitter()
  1192. .Build(loc, NonConstantCallToCompTimeOnlyFunction)
  1193. .Note(eval_context.functions()
  1194. .Get(callee_function.function_id)
  1195. .latest_decl_id(),
  1196. CompTimeOnlyFunctionHere)
  1197. .Emit();
  1198. }
  1199. return SemIR::ConstantId::NotConstant;
  1200. }
  1201. // Handle calls to builtins.
  1202. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1203. return MakeConstantForBuiltinCall(
  1204. eval_context.context(), loc, call, builtin_kind,
  1205. eval_context.inst_blocks().Get(call.args_id), phase);
  1206. }
  1207. return SemIR::ConstantId::NotConstant;
  1208. }
  1209. // Creates a FacetType constant.
  1210. static auto MakeFacetTypeResult(Context& context,
  1211. const SemIR::FacetTypeInfo& info, Phase phase)
  1212. -> SemIR::ConstantId {
  1213. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  1214. return MakeConstantResult(
  1215. context,
  1216. SemIR::FacetType{.type_id = SemIR::TypeType::SingletonTypeId,
  1217. .facet_type_id = facet_type_id},
  1218. phase);
  1219. }
  1220. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1221. static auto TryEvalInstInContext(EvalContext& eval_context,
  1222. SemIR::InstId inst_id, SemIR::Inst inst)
  1223. -> SemIR::ConstantId {
  1224. // TODO: Ensure we have test coverage for each of these cases that can result
  1225. // in a constant, once those situations are all reachable.
  1226. CARBON_KIND_SWITCH(inst) {
  1227. // These cases are constants if their operands are.
  1228. case SemIR::AddrOf::Kind:
  1229. return RebuildIfFieldsAreConstant(eval_context, inst,
  1230. &SemIR::AddrOf::type_id,
  1231. &SemIR::AddrOf::lvalue_id);
  1232. case CARBON_KIND(SemIR::ArrayType array_type): {
  1233. return RebuildAndValidateIfFieldsAreConstant(
  1234. eval_context, inst,
  1235. [&](SemIR::ArrayType result) {
  1236. auto bound_id = array_type.bound_id;
  1237. auto int_bound =
  1238. eval_context.insts().TryGetAs<SemIR::IntValue>(result.bound_id);
  1239. if (!int_bound) {
  1240. // TODO: Permit symbolic array bounds. This will require fixing
  1241. // callers of `GetArrayBoundValue`.
  1242. eval_context.context().TODO(bound_id, "symbolic array bound");
  1243. return false;
  1244. }
  1245. // TODO: We should check that the size of the resulting array type
  1246. // fits in 64 bits, not just that the bound does. Should we use a
  1247. // 32-bit limit for 32-bit targets?
  1248. const auto& bound_val = eval_context.ints().Get(int_bound->int_id);
  1249. if (eval_context.types().IsSignedInt(int_bound->type_id) &&
  1250. bound_val.isNegative()) {
  1251. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  1252. "array bound of {0} is negative", TypedInt);
  1253. eval_context.emitter().Emit(
  1254. eval_context.GetDiagnosticLoc(bound_id), ArrayBoundNegative,
  1255. {.type = int_bound->type_id, .value = bound_val});
  1256. return false;
  1257. }
  1258. if (bound_val.getActiveBits() > 64) {
  1259. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  1260. "array bound of {0} is too large", TypedInt);
  1261. eval_context.emitter().Emit(
  1262. eval_context.GetDiagnosticLoc(bound_id), ArrayBoundTooLarge,
  1263. {.type = int_bound->type_id, .value = bound_val});
  1264. return false;
  1265. }
  1266. return true;
  1267. },
  1268. &SemIR::ArrayType::bound_id, &SemIR::ArrayType::element_type_id);
  1269. }
  1270. case SemIR::AssociatedEntity::Kind:
  1271. return RebuildIfFieldsAreConstant(eval_context, inst,
  1272. &SemIR::AssociatedEntity::type_id);
  1273. case SemIR::AssociatedEntityType::Kind:
  1274. return RebuildIfFieldsAreConstant(
  1275. eval_context, inst, &SemIR::AssociatedEntityType::interface_type_id,
  1276. &SemIR::AssociatedEntityType::entity_type_id);
  1277. case SemIR::BoundMethod::Kind:
  1278. return RebuildIfFieldsAreConstant(
  1279. eval_context, inst, &SemIR::BoundMethod::type_id,
  1280. &SemIR::BoundMethod::object_id, &SemIR::BoundMethod::function_id);
  1281. case SemIR::ClassType::Kind:
  1282. return RebuildIfFieldsAreConstant(eval_context, inst,
  1283. &SemIR::ClassType::specific_id);
  1284. case SemIR::CompleteTypeWitness::Kind:
  1285. return RebuildIfFieldsAreConstant(
  1286. eval_context, inst, &SemIR::CompleteTypeWitness::object_repr_id);
  1287. case SemIR::FacetValue::Kind:
  1288. return RebuildIfFieldsAreConstant(eval_context, inst,
  1289. &SemIR::FacetValue::type_id,
  1290. &SemIR::FacetValue::type_inst_id,
  1291. &SemIR::FacetValue::witness_inst_id);
  1292. case SemIR::FunctionType::Kind:
  1293. return RebuildIfFieldsAreConstant(eval_context, inst,
  1294. &SemIR::FunctionType::specific_id);
  1295. case SemIR::GenericClassType::Kind:
  1296. return RebuildIfFieldsAreConstant(
  1297. eval_context, inst, &SemIR::GenericClassType::enclosing_specific_id);
  1298. case SemIR::GenericInterfaceType::Kind:
  1299. return RebuildIfFieldsAreConstant(
  1300. eval_context, inst,
  1301. &SemIR::GenericInterfaceType::enclosing_specific_id);
  1302. case SemIR::InterfaceWitness::Kind:
  1303. return RebuildIfFieldsAreConstant(eval_context, inst,
  1304. &SemIR::InterfaceWitness::elements_id);
  1305. case CARBON_KIND(SemIR::IntType int_type): {
  1306. return RebuildAndValidateIfFieldsAreConstant(
  1307. eval_context, inst,
  1308. [&](SemIR::IntType result) {
  1309. return ValidateIntType(
  1310. eval_context.context(),
  1311. eval_context.GetDiagnosticLoc({inst_id, int_type.bit_width_id}),
  1312. result);
  1313. },
  1314. &SemIR::IntType::bit_width_id);
  1315. }
  1316. case SemIR::PointerType::Kind:
  1317. return RebuildIfFieldsAreConstant(eval_context, inst,
  1318. &SemIR::PointerType::pointee_id);
  1319. case CARBON_KIND(SemIR::FloatType float_type): {
  1320. return RebuildAndValidateIfFieldsAreConstant(
  1321. eval_context, inst,
  1322. [&](SemIR::FloatType result) {
  1323. return ValidateFloatType(eval_context.context(),
  1324. eval_context.GetDiagnosticLoc(
  1325. {inst_id, float_type.bit_width_id}),
  1326. result);
  1327. },
  1328. &SemIR::FloatType::bit_width_id);
  1329. }
  1330. case SemIR::SpecificFunction::Kind:
  1331. return RebuildIfFieldsAreConstant(eval_context, inst,
  1332. &SemIR::SpecificFunction::callee_id,
  1333. &SemIR::SpecificFunction::specific_id);
  1334. case SemIR::StructType::Kind:
  1335. return RebuildIfFieldsAreConstant(eval_context, inst,
  1336. &SemIR::StructType::fields_id);
  1337. case SemIR::StructValue::Kind:
  1338. return RebuildIfFieldsAreConstant(eval_context, inst,
  1339. &SemIR::StructValue::type_id,
  1340. &SemIR::StructValue::elements_id);
  1341. case SemIR::TupleType::Kind:
  1342. return RebuildIfFieldsAreConstant(eval_context, inst,
  1343. &SemIR::TupleType::elements_id);
  1344. case SemIR::TupleValue::Kind:
  1345. return RebuildIfFieldsAreConstant(eval_context, inst,
  1346. &SemIR::TupleValue::type_id,
  1347. &SemIR::TupleValue::elements_id);
  1348. case SemIR::UnboundElementType::Kind:
  1349. return RebuildIfFieldsAreConstant(
  1350. eval_context, inst, &SemIR::UnboundElementType::class_type_id,
  1351. &SemIR::UnboundElementType::element_type_id);
  1352. // Initializers evaluate to a value of the object representation.
  1353. case SemIR::ArrayInit::Kind:
  1354. // TODO: Add an `ArrayValue` to represent a constant array object
  1355. // representation instead of using a `TupleValue`.
  1356. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1357. case SemIR::ClassInit::Kind:
  1358. // TODO: Add a `ClassValue` to represent a constant class object
  1359. // representation instead of using a `StructValue`.
  1360. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1361. case SemIR::StructInit::Kind:
  1362. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1363. case SemIR::TupleInit::Kind:
  1364. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1365. case SemIR::AutoType::Kind:
  1366. case SemIR::BoolType::Kind:
  1367. case SemIR::BoundMethodType::Kind:
  1368. case SemIR::ErrorInst::Kind:
  1369. case SemIR::IntLiteralType::Kind:
  1370. case SemIR::LegacyFloatType::Kind:
  1371. case SemIR::NamespaceType::Kind:
  1372. case SemIR::SpecificFunctionType::Kind:
  1373. case SemIR::StringType::Kind:
  1374. case SemIR::TypeType::Kind:
  1375. case SemIR::VtableType::Kind:
  1376. case SemIR::WitnessType::Kind:
  1377. // Builtins are always template constants.
  1378. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1379. case CARBON_KIND(SemIR::FunctionDecl fn_decl): {
  1380. return TransformIfFieldsAreConstant(
  1381. eval_context, fn_decl,
  1382. [&](SemIR::FunctionDecl result) {
  1383. return SemIR::StructValue{.type_id = result.type_id,
  1384. .elements_id = SemIR::InstBlockId::Empty};
  1385. },
  1386. &SemIR::FunctionDecl::type_id);
  1387. }
  1388. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  1389. // If the class has generic parameters, we don't produce a class type, but
  1390. // a callable whose return value is a class type.
  1391. if (eval_context.classes().Get(class_decl.class_id).has_parameters()) {
  1392. return TransformIfFieldsAreConstant(
  1393. eval_context, class_decl,
  1394. [&](SemIR::ClassDecl result) {
  1395. return SemIR::StructValue{
  1396. .type_id = result.type_id,
  1397. .elements_id = SemIR::InstBlockId::Empty};
  1398. },
  1399. &SemIR::ClassDecl::type_id);
  1400. }
  1401. // A non-generic class declaration evaluates to the class type.
  1402. return MakeConstantResult(
  1403. eval_context.context(),
  1404. SemIR::ClassType{.type_id = SemIR::TypeType::SingletonTypeId,
  1405. .class_id = class_decl.class_id,
  1406. .specific_id = SemIR::SpecificId::Invalid},
  1407. Phase::Template);
  1408. }
  1409. case CARBON_KIND(SemIR::FacetType facet_type): {
  1410. Phase phase = Phase::Template;
  1411. SemIR::FacetTypeInfo info = GetConstantFacetTypeInfo(
  1412. eval_context, facet_type.facet_type_id, &phase);
  1413. info.Canonicalize();
  1414. // TODO: Reuse `inst` if we can detect that nothing has changed.
  1415. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1416. }
  1417. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  1418. // If the interface has generic parameters, we don't produce an interface
  1419. // type, but a callable whose return value is an interface type.
  1420. if (eval_context.interfaces()
  1421. .Get(interface_decl.interface_id)
  1422. .has_parameters()) {
  1423. return TransformIfFieldsAreConstant(
  1424. eval_context, interface_decl,
  1425. [&](SemIR::InterfaceDecl result) {
  1426. return SemIR::StructValue{
  1427. .type_id = result.type_id,
  1428. .elements_id = SemIR::InstBlockId::Empty};
  1429. },
  1430. &SemIR::InterfaceDecl::type_id);
  1431. }
  1432. // A non-generic interface declaration evaluates to a facet type.
  1433. return MakeConstantResult(
  1434. eval_context.context(),
  1435. eval_context.context().FacetTypeFromInterface(
  1436. interface_decl.interface_id, SemIR::SpecificId::Invalid),
  1437. Phase::Template);
  1438. }
  1439. case CARBON_KIND(SemIR::SpecificConstant specific): {
  1440. // Pull the constant value out of the specific.
  1441. return SemIR::GetConstantValueInSpecific(
  1442. eval_context.sem_ir(), specific.specific_id, specific.inst_id);
  1443. }
  1444. // These cases are treated as being the unique canonical definition of the
  1445. // corresponding constant value.
  1446. // TODO: This doesn't properly handle redeclarations. Consider adding a
  1447. // corresponding `Value` inst for each of these cases, or returning the
  1448. // first declaration.
  1449. case SemIR::AdaptDecl::Kind:
  1450. case SemIR::AssociatedConstantDecl::Kind:
  1451. case SemIR::BaseDecl::Kind:
  1452. case SemIR::FieldDecl::Kind:
  1453. case SemIR::ImplDecl::Kind:
  1454. case SemIR::Namespace::Kind:
  1455. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  1456. case SemIR::BoolLiteral::Kind:
  1457. case SemIR::FloatLiteral::Kind:
  1458. case SemIR::IntValue::Kind:
  1459. case SemIR::StringLiteral::Kind:
  1460. // Promote literals to the constant block.
  1461. // TODO: Convert literals into a canonical form. Currently we can form two
  1462. // different `i32` constants with the same value if they are represented
  1463. // by `APInt`s with different bit widths.
  1464. // TODO: Can the type of an IntValue or FloatLiteral be symbolic? If so,
  1465. // we may need to rebuild.
  1466. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1467. // The elements of a constant aggregate can be accessed.
  1468. case SemIR::ClassElementAccess::Kind:
  1469. case SemIR::InterfaceWitnessAccess::Kind:
  1470. case SemIR::StructAccess::Kind:
  1471. case SemIR::TupleAccess::Kind:
  1472. return PerformAggregateAccess(eval_context, inst);
  1473. case CARBON_KIND(SemIR::ArrayIndex index): {
  1474. return PerformArrayIndex(eval_context, index);
  1475. }
  1476. case CARBON_KIND(SemIR::Call call): {
  1477. return MakeConstantForCall(eval_context,
  1478. eval_context.GetDiagnosticLoc(inst_id), call);
  1479. }
  1480. // TODO: These need special handling.
  1481. case SemIR::BindValue::Kind:
  1482. case SemIR::Deref::Kind:
  1483. case SemIR::ImportRefLoaded::Kind:
  1484. case SemIR::ReturnSlot::Kind:
  1485. case SemIR::Temporary::Kind:
  1486. case SemIR::TemporaryStorage::Kind:
  1487. case SemIR::ValueAsRef::Kind:
  1488. case SemIR::VtablePtr::Kind:
  1489. break;
  1490. case CARBON_KIND(SemIR::SymbolicBindingPattern bind): {
  1491. // TODO: Disable constant evaluation of SymbolicBindingPattern once
  1492. // DeduceGenericCallArguments no longer needs implicit params to have
  1493. // constant values.
  1494. const auto& bind_name =
  1495. eval_context.entity_names().Get(bind.entity_name_id);
  1496. // If we know which specific we're evaluating within and this is an
  1497. // argument of that specific, its constant value is the corresponding
  1498. // argument value.
  1499. if (auto value =
  1500. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1501. value.is_valid()) {
  1502. return value;
  1503. }
  1504. // The constant form of a symbolic binding is an idealized form of the
  1505. // original, with no equivalent value.
  1506. bind.entity_name_id =
  1507. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1508. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1509. }
  1510. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  1511. const auto& bind_name =
  1512. eval_context.entity_names().Get(bind.entity_name_id);
  1513. Phase phase;
  1514. if (bind_name.name_id == SemIR::NameId::PeriodSelf) {
  1515. phase = Phase::PeriodSelfSymbolic;
  1516. } else {
  1517. // If we know which specific we're evaluating within and this is an
  1518. // argument of that specific, its constant value is the corresponding
  1519. // argument value.
  1520. if (auto value =
  1521. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1522. value.is_valid()) {
  1523. return value;
  1524. }
  1525. phase = Phase::Symbolic;
  1526. }
  1527. // The constant form of a symbolic binding is an idealized form of the
  1528. // original, with no equivalent value.
  1529. bind.entity_name_id =
  1530. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1531. bind.value_id = SemIR::InstId::Invalid;
  1532. if (!ReplaceFieldWithConstantValue(
  1533. eval_context, &bind, &SemIR::BindSymbolicName::type_id, &phase)) {
  1534. return MakeNonConstantResult(phase);
  1535. }
  1536. return MakeConstantResult(eval_context.context(), bind, phase);
  1537. }
  1538. // These semantic wrappers don't change the constant value.
  1539. case CARBON_KIND(SemIR::AsCompatible inst): {
  1540. return eval_context.GetConstantValue(inst.source_id);
  1541. }
  1542. case CARBON_KIND(SemIR::BindAlias typed_inst): {
  1543. return eval_context.GetConstantValue(typed_inst.value_id);
  1544. }
  1545. case CARBON_KIND(SemIR::ExportDecl typed_inst): {
  1546. return eval_context.GetConstantValue(typed_inst.value_id);
  1547. }
  1548. case CARBON_KIND(SemIR::NameRef typed_inst): {
  1549. return eval_context.GetConstantValue(typed_inst.value_id);
  1550. }
  1551. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  1552. // TODO: Treat this as a non-expression (here and in GetExprCategory)
  1553. // once generic deduction doesn't need patterns to have constant values.
  1554. return eval_context.GetConstantValue(param_pattern.subpattern_id);
  1555. }
  1556. case CARBON_KIND(SemIR::Converted typed_inst): {
  1557. return eval_context.GetConstantValue(typed_inst.result_id);
  1558. }
  1559. case CARBON_KIND(SemIR::InitializeFrom typed_inst): {
  1560. return eval_context.GetConstantValue(typed_inst.src_id);
  1561. }
  1562. case CARBON_KIND(SemIR::SpliceBlock typed_inst): {
  1563. return eval_context.GetConstantValue(typed_inst.result_id);
  1564. }
  1565. case CARBON_KIND(SemIR::ValueOfInitializer typed_inst): {
  1566. return eval_context.GetConstantValue(typed_inst.init_id);
  1567. }
  1568. case CARBON_KIND(SemIR::FacetAccessType typed_inst): {
  1569. Phase phase = Phase::Template;
  1570. if (ReplaceFieldWithConstantValue(
  1571. eval_context, &typed_inst,
  1572. &SemIR::FacetAccessType::facet_value_inst_id, &phase)) {
  1573. if (auto facet_value = eval_context.insts().TryGetAs<SemIR::FacetValue>(
  1574. typed_inst.facet_value_inst_id)) {
  1575. return eval_context.constant_values().Get(facet_value->type_inst_id);
  1576. }
  1577. return MakeConstantResult(eval_context.context(), typed_inst, phase);
  1578. } else {
  1579. return MakeNonConstantResult(phase);
  1580. }
  1581. }
  1582. case CARBON_KIND(SemIR::FacetAccessWitness typed_inst): {
  1583. Phase phase = Phase::Template;
  1584. if (ReplaceFieldWithConstantValue(
  1585. eval_context, &typed_inst,
  1586. &SemIR::FacetAccessWitness::facet_value_inst_id, &phase)) {
  1587. if (auto facet_value = eval_context.insts().TryGetAs<SemIR::FacetValue>(
  1588. typed_inst.facet_value_inst_id)) {
  1589. return eval_context.constant_values().Get(
  1590. facet_value->witness_inst_id);
  1591. }
  1592. return MakeConstantResult(eval_context.context(), typed_inst, phase);
  1593. } else {
  1594. return MakeNonConstantResult(phase);
  1595. }
  1596. }
  1597. case CARBON_KIND(SemIR::WhereExpr typed_inst): {
  1598. Phase phase = Phase::Template;
  1599. SemIR::TypeId base_facet_type_id =
  1600. eval_context.insts().Get(typed_inst.period_self_id).type_id();
  1601. SemIR::Inst base_facet_inst =
  1602. eval_context.GetConstantValueAsInst(base_facet_type_id);
  1603. SemIR::FacetTypeInfo info = {.other_requirements = false};
  1604. // `where` provides that the base facet is an error, `type`, or a facet
  1605. // type.
  1606. if (auto facet_type = base_facet_inst.TryAs<SemIR::FacetType>()) {
  1607. info = GetConstantFacetTypeInfo(eval_context, facet_type->facet_type_id,
  1608. &phase);
  1609. } else if (base_facet_type_id == SemIR::ErrorInst::SingletonTypeId) {
  1610. return SemIR::ErrorInst::SingletonConstantId;
  1611. } else {
  1612. CARBON_CHECK(base_facet_type_id == SemIR::TypeType::SingletonTypeId,
  1613. "Unexpected type_id: {0}, inst: {1}", base_facet_type_id,
  1614. base_facet_inst);
  1615. }
  1616. if (typed_inst.requirements_id.is_valid()) {
  1617. auto insts = eval_context.inst_blocks().Get(typed_inst.requirements_id);
  1618. for (auto inst_id : insts) {
  1619. if (auto rewrite =
  1620. eval_context.insts().TryGetAs<SemIR::RequirementRewrite>(
  1621. inst_id)) {
  1622. SemIR::ConstantId lhs =
  1623. eval_context.GetConstantValue(rewrite->lhs_id);
  1624. SemIR::ConstantId rhs =
  1625. eval_context.GetConstantValue(rewrite->rhs_id);
  1626. // `where` requirements using `.Self` should not be considered
  1627. // symbolic
  1628. UpdatePhaseIgnorePeriodSelf(eval_context, lhs, &phase);
  1629. UpdatePhaseIgnorePeriodSelf(eval_context, rhs, &phase);
  1630. info.rewrite_constraints.push_back(
  1631. {.lhs_const_id = lhs, .rhs_const_id = rhs});
  1632. } else {
  1633. // TODO: Handle other requirements
  1634. info.other_requirements = true;
  1635. }
  1636. }
  1637. }
  1638. info.Canonicalize();
  1639. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1640. }
  1641. // `not true` -> `false`, `not false` -> `true`.
  1642. // All other uses of unary `not` are non-constant.
  1643. case CARBON_KIND(SemIR::UnaryOperatorNot typed_inst): {
  1644. auto const_id = eval_context.GetConstantValue(typed_inst.operand_id);
  1645. auto phase = GetPhase(eval_context, const_id);
  1646. if (phase == Phase::Template) {
  1647. auto value = eval_context.insts().GetAs<SemIR::BoolLiteral>(
  1648. eval_context.constant_values().GetInstId(const_id));
  1649. return MakeBoolResult(eval_context.context(), value.type_id,
  1650. !value.value.ToBool());
  1651. }
  1652. if (phase == Phase::UnknownDueToError) {
  1653. return SemIR::ErrorInst::SingletonConstantId;
  1654. }
  1655. break;
  1656. }
  1657. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  1658. // to itself.
  1659. case CARBON_KIND(SemIR::ConstType typed_inst): {
  1660. auto phase = Phase::Template;
  1661. auto inner_id =
  1662. GetConstantValue(eval_context, typed_inst.inner_id, &phase);
  1663. if (eval_context.context().types().Is<SemIR::ConstType>(inner_id)) {
  1664. return eval_context.context().types().GetConstantId(inner_id);
  1665. }
  1666. typed_inst.inner_id = inner_id;
  1667. return MakeConstantResult(eval_context.context(), typed_inst, phase);
  1668. }
  1669. case CARBON_KIND(SemIR::RequireCompleteType require_complete): {
  1670. auto phase = Phase::Template;
  1671. auto witness_type_id = eval_context.context().GetSingletonType(
  1672. SemIR::WitnessType::SingletonInstId);
  1673. auto complete_type_id = GetConstantValue(
  1674. eval_context, require_complete.complete_type_id, &phase);
  1675. // If the type is a template constant, require it to be complete now.
  1676. if (phase == Phase::Template) {
  1677. if (!eval_context.context().TryToCompleteType(
  1678. complete_type_id, eval_context.GetDiagnosticLoc(inst_id), [&] {
  1679. CARBON_DIAGNOSTIC(IncompleteTypeInMonomorphization, Error,
  1680. "{0} evaluates to incomplete type {1}",
  1681. SemIR::TypeId, SemIR::TypeId);
  1682. return eval_context.emitter().Build(
  1683. eval_context.GetDiagnosticLoc(inst_id),
  1684. IncompleteTypeInMonomorphization,
  1685. require_complete.complete_type_id, complete_type_id);
  1686. })) {
  1687. return SemIR::ErrorInst::SingletonConstantId;
  1688. }
  1689. return MakeConstantResult(
  1690. eval_context.context(),
  1691. SemIR::CompleteTypeWitness{
  1692. .type_id = witness_type_id,
  1693. .object_repr_id =
  1694. eval_context.types().GetObjectRepr(complete_type_id)},
  1695. phase);
  1696. }
  1697. // If it's not a template constant, require it to be complete once it
  1698. // becomes one.
  1699. return MakeConstantResult(
  1700. eval_context.context(),
  1701. SemIR::RequireCompleteType{.type_id = witness_type_id,
  1702. .complete_type_id = complete_type_id},
  1703. phase);
  1704. }
  1705. // These cases are either not expressions or not constant.
  1706. case SemIR::AddrPattern::Kind:
  1707. case SemIR::Assign::Kind:
  1708. case SemIR::BindName::Kind:
  1709. case SemIR::BindingPattern::Kind:
  1710. case SemIR::BlockArg::Kind:
  1711. case SemIR::Branch::Kind:
  1712. case SemIR::BranchIf::Kind:
  1713. case SemIR::BranchWithArg::Kind:
  1714. case SemIR::ImportDecl::Kind:
  1715. case SemIR::OutParam::Kind:
  1716. case SemIR::OutParamPattern::Kind:
  1717. case SemIR::RequirementEquivalent::Kind:
  1718. case SemIR::RequirementImpls::Kind:
  1719. case SemIR::RequirementRewrite::Kind:
  1720. case SemIR::Return::Kind:
  1721. case SemIR::ReturnExpr::Kind:
  1722. case SemIR::ReturnSlotPattern::Kind:
  1723. case SemIR::StructLiteral::Kind:
  1724. case SemIR::TupleLiteral::Kind:
  1725. case SemIR::ValueParam::Kind:
  1726. case SemIR::VarStorage::Kind:
  1727. break;
  1728. case SemIR::ImportRefUnloaded::Kind:
  1729. CARBON_FATAL("ImportRefUnloaded should be loaded before TryEvalInst: {0}",
  1730. inst);
  1731. }
  1732. return SemIR::ConstantId::NotConstant;
  1733. }
  1734. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  1735. -> SemIR::ConstantId {
  1736. EvalContext eval_context(context, inst_id);
  1737. return TryEvalInstInContext(eval_context, inst_id, inst);
  1738. }
  1739. auto TryEvalBlockForSpecific(Context& context, SemIRLoc loc,
  1740. SemIR::SpecificId specific_id,
  1741. SemIR::GenericInstIndex::Region region)
  1742. -> SemIR::InstBlockId {
  1743. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1744. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1745. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1746. llvm::SmallVector<SemIR::InstId> result;
  1747. result.resize(eval_block.size(), SemIR::InstId::Invalid);
  1748. EvalContext eval_context(context, loc, specific_id,
  1749. SpecificEvalInfo{
  1750. .region = region,
  1751. .values = result,
  1752. });
  1753. DiagnosticAnnotationScope annotate_diagnostics(
  1754. &context.emitter(), [&](auto& builder) {
  1755. CARBON_DIAGNOSTIC(ResolvingSpecificHere, Note, "in {0} used here",
  1756. InstIdAsType);
  1757. if (loc.is_inst_id && !loc.inst_id.is_valid()) {
  1758. return;
  1759. }
  1760. builder.Note(loc, ResolvingSpecificHere,
  1761. GetInstForSpecific(context, specific_id));
  1762. });
  1763. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1764. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1765. context.insts().Get(inst_id));
  1766. result[i] = context.constant_values().GetInstId(const_id);
  1767. CARBON_CHECK(result[i].is_valid());
  1768. }
  1769. return context.inst_blocks().Add(result);
  1770. }
  1771. } // namespace Carbon::Check