eval.cpp 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  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/eval_inst.h"
  8. #include "toolchain/check/facet_type.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/check/import_ref.h"
  11. #include "toolchain/check/type.h"
  12. #include "toolchain/check/type_completion.h"
  13. #include "toolchain/diagnostics/diagnostic_emitter.h"
  14. #include "toolchain/diagnostics/format_providers.h"
  15. #include "toolchain/sem_ir/builtin_function_kind.h"
  16. #include "toolchain/sem_ir/function.h"
  17. #include "toolchain/sem_ir/generic.h"
  18. #include "toolchain/sem_ir/id_kind.h"
  19. #include "toolchain/sem_ir/ids.h"
  20. #include "toolchain/sem_ir/inst_kind.h"
  21. #include "toolchain/sem_ir/typed_insts.h"
  22. namespace Carbon::Check {
  23. namespace {
  24. // Information about an eval block of a specific that we are currently building.
  25. struct SpecificEvalInfo {
  26. // The region within the specific whose eval block we are building.
  27. SemIR::GenericInstIndex::Region region;
  28. // The work-in-progress contents of the eval block.
  29. llvm::ArrayRef<SemIR::InstId> values;
  30. };
  31. // Information about the context within which we are performing evaluation.
  32. class EvalContext {
  33. public:
  34. explicit EvalContext(
  35. Context& context, SemIRLoc fallback_loc,
  36. SemIR::SpecificId specific_id = SemIR::SpecificId::None,
  37. std::optional<SpecificEvalInfo> specific_eval_info = std::nullopt)
  38. : context_(context),
  39. fallback_loc_(fallback_loc),
  40. specific_id_(specific_id),
  41. specific_eval_info_(specific_eval_info) {}
  42. // Gets the location to use for diagnostics if a better location is
  43. // unavailable.
  44. // TODO: This is also sometimes unavailable.
  45. auto fallback_loc() const -> SemIRLoc { return fallback_loc_; }
  46. // Returns a location to use to point at an instruction in a diagnostic, given
  47. // a list of instructions that might have an attached location. This is the
  48. // location of the first instruction in the list that has a location if there
  49. // is one, and otherwise the fallback location.
  50. auto GetDiagnosticLoc(llvm::ArrayRef<SemIR::InstId> inst_ids) -> SemIRLoc {
  51. for (auto inst_id : inst_ids) {
  52. if (inst_id.has_value() &&
  53. context_.insts().GetLocId(inst_id).has_value()) {
  54. return inst_id;
  55. }
  56. }
  57. return fallback_loc_;
  58. }
  59. // Gets the value of the specified compile-time binding in this context.
  60. // Returns `None` if the value is not fixed in this context.
  61. auto GetCompileTimeBindValue(SemIR::CompileTimeBindIndex bind_index)
  62. -> SemIR::ConstantId {
  63. if (!bind_index.has_value() || !specific_id_.has_value()) {
  64. return SemIR::ConstantId::None;
  65. }
  66. const auto& specific = specifics().Get(specific_id_);
  67. auto args = inst_blocks().Get(specific.args_id);
  68. // Bindings past the ones with known arguments can appear as local
  69. // bindings of entities declared within this generic.
  70. if (static_cast<size_t>(bind_index.index) >= args.size()) {
  71. return SemIR::ConstantId::None;
  72. }
  73. return constant_values().Get(args[bind_index.index]);
  74. }
  75. // Given a constant value from the SemIR we're evaluating, finds the
  76. // corresponding constant value to use in the context of this evaluation.
  77. // This can be different if the original SemIR is for a generic and we are
  78. // evaluating with specific arguments for the generic parameters.
  79. auto GetInContext(SemIR::ConstantId const_id) -> SemIR::ConstantId {
  80. if (!const_id.is_symbolic()) {
  81. return const_id;
  82. }
  83. // While resolving a specific, map from previous instructions in the eval
  84. // block into their evaluated values. These values won't be present on the
  85. // specific itself yet, so `GetConstantInSpecific` won't be able to find
  86. // them.
  87. if (specific_eval_info_) {
  88. const auto& symbolic_info =
  89. constant_values().GetSymbolicConstant(const_id);
  90. if (symbolic_info.index.has_value() &&
  91. symbolic_info.generic_id ==
  92. specifics().Get(specific_id_).generic_id &&
  93. symbolic_info.index.region() == specific_eval_info_->region) {
  94. auto inst_id = specific_eval_info_->values[symbolic_info.index.index()];
  95. CARBON_CHECK(inst_id.has_value(),
  96. "Forward reference in eval block: index {0} referenced "
  97. "before evaluation",
  98. symbolic_info.index.index());
  99. return constant_values().Get(inst_id);
  100. }
  101. }
  102. // Map from a specific constant value to the canonical value.
  103. return GetConstantInSpecific(sem_ir(), specific_id_, const_id);
  104. }
  105. // Gets the constant value of the specified instruction in this context.
  106. auto GetConstantValue(SemIR::InstId inst_id) -> SemIR::ConstantId {
  107. return GetInContext(constant_values().Get(inst_id));
  108. }
  109. // Gets the constant value of the specified type in this context.
  110. auto GetConstantValue(SemIR::TypeId type_id) -> SemIR::ConstantId {
  111. return GetInContext(types().GetConstantId(type_id));
  112. }
  113. // Gets the constant value of the specified type in this context.
  114. auto GetConstantValueAsType(SemIR::TypeId id) -> SemIR::TypeId {
  115. return context().types().GetTypeIdForTypeConstantId(GetConstantValue(id));
  116. }
  117. // Gets the instruction describing the constant value of the specified type in
  118. // this context.
  119. auto GetConstantValueAsInst(SemIR::TypeId id) -> SemIR::Inst {
  120. return insts().Get(
  121. context().constant_values().GetInstId(GetConstantValue(id)));
  122. }
  123. auto ints() -> SharedValueStores::IntStore& { return sem_ir().ints(); }
  124. auto floats() -> SharedValueStores::FloatStore& { return sem_ir().floats(); }
  125. auto entity_names() -> SemIR::EntityNameStore& {
  126. return sem_ir().entity_names();
  127. }
  128. auto functions() -> const ValueStore<SemIR::FunctionId>& {
  129. return sem_ir().functions();
  130. }
  131. auto classes() -> const ValueStore<SemIR::ClassId>& {
  132. return sem_ir().classes();
  133. }
  134. auto interfaces() -> const ValueStore<SemIR::InterfaceId>& {
  135. return sem_ir().interfaces();
  136. }
  137. auto facet_types() -> CanonicalValueStore<SemIR::FacetTypeId>& {
  138. return sem_ir().facet_types();
  139. }
  140. auto specifics() -> const SemIR::SpecificStore& {
  141. return sem_ir().specifics();
  142. }
  143. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  144. return sem_ir().type_blocks();
  145. }
  146. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  147. auto inst_blocks() -> SemIR::InstBlockStore& {
  148. return sem_ir().inst_blocks();
  149. }
  150. // Gets the constant value store. Note that this does not provide the constant
  151. // values that should be used from this evaluation context, and so should be
  152. // used with caution.
  153. auto constant_values() -> const SemIR::ConstantValueStore& {
  154. return sem_ir().constant_values();
  155. }
  156. // Gets the types store. Note that this does not provide the type values that
  157. // should be used from this evaluation context, and so should be used with
  158. // caution.
  159. auto types() -> const SemIR::TypeStore& { return sem_ir().types(); }
  160. auto context() -> Context& { return context_; }
  161. auto sem_ir() -> SemIR::File& { return context().sem_ir(); }
  162. auto emitter() -> DiagnosticEmitter<SemIRLoc>& { return context().emitter(); }
  163. private:
  164. // The type-checking context in which we're performing evaluation.
  165. Context& context_;
  166. // The location to use for diagnostics when a better location isn't available.
  167. SemIRLoc fallback_loc_;
  168. // The specific that we are evaluating within.
  169. SemIR::SpecificId specific_id_;
  170. // If we are currently evaluating an eval block for `specific_id_`,
  171. // information about that evaluation.
  172. std::optional<SpecificEvalInfo> specific_eval_info_;
  173. };
  174. } // namespace
  175. namespace {
  176. // The evaluation phase for an expression, computed by evaluation. These are
  177. // ordered so that the phase of an expression is the numerically highest phase
  178. // of its constituent evaluations. Note that an expression with any runtime
  179. // component is known to have Runtime phase even if it involves an evaluation
  180. // with UnknownDueToError phase.
  181. enum class Phase : uint8_t {
  182. // Value could be entirely and concretely computed.
  183. Concrete,
  184. // Evaluation phase is symbolic because the expression involves specifically a
  185. // reference to `.Self`.
  186. PeriodSelfSymbolic,
  187. // Evaluation phase is symbolic because the expression involves a reference to
  188. // a non-template symbolic binding other than `.Self`.
  189. CheckedSymbolic,
  190. // Evaluation phase is symbolic because the expression involves a reference to
  191. // a template parameter, or otherwise depends on something template dependent.
  192. // The expression might also reference non-template symbolic bindings.
  193. TemplateSymbolic,
  194. // The evaluation phase is unknown because evaluation encountered an
  195. // already-diagnosed semantic or syntax error. This is treated as being
  196. // potentially constant, but with an unknown phase.
  197. UnknownDueToError,
  198. // The expression has runtime phase because of a non-constant subexpression.
  199. Runtime,
  200. };
  201. } // namespace
  202. // Returns whether the specified phase is a constant phase.
  203. static auto IsConstant(Phase phase) -> bool {
  204. return phase < Phase::UnknownDueToError;
  205. }
  206. // Gets the phase in which the value of a constant will become available.
  207. static auto GetPhase(const SemIR::ConstantValueStore& constant_values,
  208. SemIR::ConstantId constant_id) -> Phase {
  209. if (!constant_id.is_constant()) {
  210. return Phase::Runtime;
  211. } else if (constant_id == SemIR::ErrorInst::SingletonConstantId) {
  212. return Phase::UnknownDueToError;
  213. }
  214. switch (constant_values.GetDependence(constant_id)) {
  215. case SemIR::ConstantDependence::None:
  216. return Phase::Concrete;
  217. case SemIR::ConstantDependence::PeriodSelf:
  218. return Phase::PeriodSelfSymbolic;
  219. case SemIR::ConstantDependence::Checked:
  220. return Phase::CheckedSymbolic;
  221. case SemIR::ConstantDependence::Template:
  222. return Phase::TemplateSymbolic;
  223. }
  224. }
  225. // Returns the later of two phases.
  226. static auto LatestPhase(Phase a, Phase b) -> Phase {
  227. return static_cast<Phase>(
  228. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  229. }
  230. // `where` expressions using `.Self` should not be considered symbolic
  231. // - `Interface where .Self impls I and .A = bool` -> concrete
  232. // - `T:! type` ... `Interface where .A = T` -> symbolic, since uses `T` which
  233. // is symbolic and not due to `.Self`.
  234. static auto UpdatePhaseIgnorePeriodSelf(EvalContext& eval_context,
  235. SemIR::ConstantId constant_id,
  236. Phase* phase) {
  237. Phase constant_phase = GetPhase(eval_context.constant_values(), constant_id);
  238. // Since LatestPhase(x, Phase::Concrete) == x, this is equivalent to replacing
  239. // Phase::PeriodSelfSymbolic with Phase::Concrete.
  240. if (constant_phase != Phase::PeriodSelfSymbolic) {
  241. *phase = LatestPhase(*phase, constant_phase);
  242. }
  243. }
  244. // Forms a `constant_id` describing a given evaluation result.
  245. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  246. -> SemIR::ConstantId {
  247. switch (phase) {
  248. case Phase::Concrete:
  249. return context.constants().GetOrAdd(inst,
  250. SemIR::ConstantDependence::None);
  251. case Phase::PeriodSelfSymbolic:
  252. return context.constants().GetOrAdd(
  253. inst, SemIR::ConstantDependence::PeriodSelf);
  254. case Phase::CheckedSymbolic:
  255. return context.constants().GetOrAdd(inst,
  256. SemIR::ConstantDependence::Checked);
  257. case Phase::TemplateSymbolic:
  258. return context.constants().GetOrAdd(inst,
  259. SemIR::ConstantDependence::Template);
  260. case Phase::UnknownDueToError:
  261. return SemIR::ErrorInst::SingletonConstantId;
  262. case Phase::Runtime:
  263. return SemIR::ConstantId::NotConstant;
  264. }
  265. }
  266. // Forms a `constant_id` describing why an evaluation was not constant.
  267. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  268. return phase == Phase::UnknownDueToError
  269. ? SemIR::ErrorInst::SingletonConstantId
  270. : SemIR::ConstantId::NotConstant;
  271. }
  272. // Converts a bool value into a ConstantId.
  273. static auto MakeBoolResult(Context& context, SemIR::TypeId bool_type_id,
  274. bool result) -> SemIR::ConstantId {
  275. return MakeConstantResult(
  276. context,
  277. SemIR::BoolLiteral{.type_id = bool_type_id,
  278. .value = SemIR::BoolValue::From(result)},
  279. Phase::Concrete);
  280. }
  281. // Converts an APInt value into a ConstantId.
  282. static auto MakeIntResult(Context& context, SemIR::TypeId type_id,
  283. bool is_signed, llvm::APInt value)
  284. -> SemIR::ConstantId {
  285. CARBON_CHECK(is_signed == context.types().IsSignedInt(type_id));
  286. auto result = is_signed ? context.ints().AddSigned(std::move(value))
  287. : context.ints().AddUnsigned(std::move(value));
  288. return MakeConstantResult(
  289. context, SemIR::IntValue{.type_id = type_id, .int_id = result},
  290. Phase::Concrete);
  291. }
  292. // Converts an APFloat value into a ConstantId.
  293. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  294. llvm::APFloat value) -> SemIR::ConstantId {
  295. auto result = context.floats().Add(std::move(value));
  296. return MakeConstantResult(
  297. context, SemIR::FloatLiteral{.type_id = type_id, .float_id = result},
  298. Phase::Concrete);
  299. }
  300. // Creates a FacetType constant.
  301. static auto MakeFacetTypeResult(Context& context,
  302. const SemIR::FacetTypeInfo& info, Phase phase)
  303. -> SemIR::ConstantId {
  304. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  305. return MakeConstantResult(
  306. context,
  307. SemIR::FacetType{.type_id = SemIR::TypeType::SingletonTypeId,
  308. .facet_type_id = facet_type_id},
  309. phase);
  310. }
  311. // `GetConstantValue` checks to see whether the provided ID describes a value
  312. // with constant phase, and if so, returns the corresponding constant value.
  313. // Overloads are provided for different kinds of ID.
  314. // AbsoluteInstId can not have its values substituted, so this overload is
  315. // deleted. This prevents conversion to InstId.
  316. static auto GetConstantValue(EvalContext& eval_context,
  317. SemIR::AbsoluteInstId inst_id, Phase* phase)
  318. -> SemIR::InstId = delete;
  319. // If the given instruction is constant, returns its constant value.
  320. static auto GetConstantValue(EvalContext& eval_context, SemIR::InstId inst_id,
  321. Phase* phase) -> SemIR::InstId {
  322. auto const_id = eval_context.GetConstantValue(inst_id);
  323. *phase =
  324. LatestPhase(*phase, GetPhase(eval_context.constant_values(), const_id));
  325. return eval_context.constant_values().GetInstId(const_id);
  326. }
  327. // Explicitly discard a `DestInstId`, because we should not be using the
  328. // destination as part of evaluation.
  329. static auto GetConstantValue(EvalContext& /*eval_context*/,
  330. SemIR::DestInstId /*inst_id*/, Phase* /*phase*/)
  331. -> SemIR::DestInstId {
  332. return SemIR::InstId::None;
  333. }
  334. // Given a type which may refer to a generic parameter, returns the
  335. // corresponding type in the evaluation context.
  336. static auto GetConstantValue(EvalContext& eval_context, SemIR::TypeId type_id,
  337. Phase* phase) -> SemIR::TypeId {
  338. auto const_id = eval_context.GetConstantValue(type_id);
  339. *phase =
  340. LatestPhase(*phase, GetPhase(eval_context.constant_values(), const_id));
  341. return eval_context.context().types().GetTypeIdForTypeConstantId(const_id);
  342. }
  343. // AbsoluteInstBlockId can not have its values substituted, so this overload is
  344. // deleted. This prevents conversion to InstBlockId.
  345. static auto GetConstantValue(EvalContext& eval_context,
  346. SemIR::AbsoluteInstBlockId inst_block_id,
  347. Phase* phase) -> SemIR::InstBlockId = delete;
  348. // If the given instruction block contains only constants, returns a
  349. // corresponding block of those values.
  350. static auto GetConstantValue(EvalContext& eval_context,
  351. SemIR::InstBlockId inst_block_id, Phase* phase)
  352. -> SemIR::InstBlockId {
  353. if (!inst_block_id.has_value()) {
  354. return SemIR::InstBlockId::None;
  355. }
  356. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  357. llvm::SmallVector<SemIR::InstId> const_insts;
  358. for (auto inst_id : insts) {
  359. auto const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  360. if (!const_inst_id.has_value()) {
  361. return SemIR::InstBlockId::None;
  362. }
  363. // Once we leave the small buffer, we know the first few elements are all
  364. // constant, so it's likely that the entire block is constant. Resize to the
  365. // target size given that we're going to allocate memory now anyway.
  366. if (const_insts.size() == const_insts.capacity()) {
  367. const_insts.reserve(insts.size());
  368. }
  369. const_insts.push_back(const_inst_id);
  370. }
  371. // TODO: If the new block is identical to the original block, and we know the
  372. // old ID was canonical, return the original ID.
  373. return eval_context.inst_blocks().AddCanonical(const_insts);
  374. }
  375. // Compute the constant value of a type block. This may be different from the
  376. // input type block if we have known generic arguments.
  377. static auto GetConstantValue(EvalContext& eval_context,
  378. SemIR::StructTypeFieldsId fields_id, Phase* phase)
  379. -> SemIR::StructTypeFieldsId {
  380. if (!fields_id.has_value()) {
  381. return SemIR::StructTypeFieldsId::None;
  382. }
  383. auto fields = eval_context.context().struct_type_fields().Get(fields_id);
  384. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  385. for (auto field : fields) {
  386. auto new_type_id = GetConstantValue(eval_context, field.type_id, phase);
  387. if (!new_type_id.has_value()) {
  388. return SemIR::StructTypeFieldsId::None;
  389. }
  390. // Once we leave the small buffer, we know the first few elements are all
  391. // constant, so it's likely that the entire block is constant. Resize to the
  392. // target size given that we're going to allocate memory now anyway.
  393. if (new_fields.size() == new_fields.capacity()) {
  394. new_fields.reserve(fields.size());
  395. }
  396. new_fields.push_back({.name_id = field.name_id, .type_id = new_type_id});
  397. }
  398. // TODO: If the new block is identical to the original block, and we know the
  399. // old ID was canonical, return the original ID.
  400. return eval_context.context().struct_type_fields().AddCanonical(new_fields);
  401. }
  402. // Compute the constant value of a type block. This may be different from the
  403. // input type block if we have known generic arguments.
  404. static auto GetConstantValue(EvalContext& eval_context,
  405. SemIR::TypeBlockId type_block_id, Phase* phase)
  406. -> SemIR::TypeBlockId {
  407. if (!type_block_id.has_value()) {
  408. return SemIR::TypeBlockId::None;
  409. }
  410. auto types = eval_context.type_blocks().Get(type_block_id);
  411. llvm::SmallVector<SemIR::TypeId> new_types;
  412. for (auto type_id : types) {
  413. auto new_type_id = GetConstantValue(eval_context, type_id, phase);
  414. if (!new_type_id.has_value()) {
  415. return SemIR::TypeBlockId::None;
  416. }
  417. // Once we leave the small buffer, we know the first few elements are all
  418. // constant, so it's likely that the entire block is constant. Resize to the
  419. // target size given that we're going to allocate memory now anyway.
  420. if (new_types.size() == new_types.capacity()) {
  421. new_types.reserve(types.size());
  422. }
  423. new_types.push_back(new_type_id);
  424. }
  425. // TODO: If the new block is identical to the original block, and we know the
  426. // old ID was canonical, return the original ID.
  427. return eval_context.type_blocks().AddCanonical(new_types);
  428. }
  429. // The constant value of a specific is the specific with the corresponding
  430. // constant values for its arguments.
  431. static auto GetConstantValue(EvalContext& eval_context,
  432. SemIR::SpecificId specific_id, Phase* phase)
  433. -> SemIR::SpecificId {
  434. if (!specific_id.has_value()) {
  435. return SemIR::SpecificId::None;
  436. }
  437. const auto& specific = eval_context.specifics().Get(specific_id);
  438. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  439. if (!args_id.has_value()) {
  440. return SemIR::SpecificId::None;
  441. }
  442. if (args_id == specific.args_id) {
  443. const auto& specific = eval_context.specifics().Get(specific_id);
  444. // A constant specific_id should always have a resolved declaration. The
  445. // specific_id from the instruction may coincidentally be canonical, and so
  446. // constant evaluation gives the same value. In that case, we still need to
  447. // ensure its declaration is resolved.
  448. //
  449. // However, don't resolve the declaration if the generic's eval block hasn't
  450. // been set yet. This happens when building the eval block during import.
  451. //
  452. // TODO: Change importing of generic eval blocks to be less fragile and
  453. // remove this `if` so we unconditionally call `ResolveSpecificDeclaration`.
  454. if (!specific.decl_block_id.has_value() && eval_context.context()
  455. .generics()
  456. .Get(specific.generic_id)
  457. .decl_block_id.has_value()) {
  458. ResolveSpecificDeclaration(eval_context.context(),
  459. eval_context.fallback_loc(), specific_id);
  460. }
  461. return specific_id;
  462. }
  463. return MakeSpecific(eval_context.context(), eval_context.fallback_loc(),
  464. specific.generic_id, args_id);
  465. }
  466. // Like `GetConstantValue` but does a `FacetTypeId` -> `FacetTypeInfo`
  467. // conversion. Does not perform canonicalization.
  468. static auto GetConstantFacetTypeInfo(EvalContext& eval_context,
  469. SemIR::FacetTypeId facet_type_id,
  470. Phase* phase) -> SemIR::FacetTypeInfo {
  471. const auto& orig = eval_context.facet_types().Get(facet_type_id);
  472. SemIR::FacetTypeInfo info;
  473. info.impls_constraints.reserve(orig.impls_constraints.size());
  474. for (const auto& interface : orig.impls_constraints) {
  475. info.impls_constraints.push_back(
  476. {.interface_id = interface.interface_id,
  477. .specific_id =
  478. GetConstantValue(eval_context, interface.specific_id, phase)});
  479. }
  480. info.rewrite_constraints.reserve(orig.rewrite_constraints.size());
  481. for (const auto& rewrite : orig.rewrite_constraints) {
  482. auto lhs_const_id = eval_context.GetInContext(rewrite.lhs_const_id);
  483. auto rhs_const_id = eval_context.GetInContext(rewrite.rhs_const_id);
  484. // `where` requirements using `.Self` should not be considered symbolic
  485. UpdatePhaseIgnorePeriodSelf(eval_context, lhs_const_id, phase);
  486. UpdatePhaseIgnorePeriodSelf(eval_context, rhs_const_id, phase);
  487. info.rewrite_constraints.push_back(
  488. {.lhs_const_id = lhs_const_id, .rhs_const_id = rhs_const_id});
  489. }
  490. // TODO: Process other requirements.
  491. info.other_requirements = orig.other_requirements;
  492. return info;
  493. }
  494. static auto GetConstantValue(EvalContext& eval_context,
  495. SemIR::FacetTypeId facet_type_id, Phase* phase)
  496. -> SemIR::FacetTypeId {
  497. SemIR::FacetTypeInfo info =
  498. GetConstantFacetTypeInfo(eval_context, facet_type_id, phase);
  499. info.Canonicalize();
  500. // TODO: Return `facet_type_id` if we can detect nothing has changed.
  501. return eval_context.facet_types().Add(info);
  502. }
  503. // Replaces the specified field of the given typed instruction with its constant
  504. // value, if it has constant phase. Returns true on success, false if the value
  505. // has runtime phase.
  506. template <typename InstT, typename FieldIdT>
  507. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  508. InstT* inst, FieldIdT InstT::*field,
  509. Phase* phase) -> bool {
  510. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  511. if (!unwrapped.has_value() && (inst->*field).has_value()) {
  512. return false;
  513. }
  514. inst->*field = unwrapped;
  515. return true;
  516. }
  517. // Function template that can be called with an argument of type `T`. Used below
  518. // to detect which overloads of `GetConstantValue` exist.
  519. template <typename T>
  520. static void Accept(T /*arg*/) {}
  521. // Determines whether a `GetConstantValue` overload exists for a given ID type.
  522. // Note that we do not check whether `GetConstantValue` is *callable* with a
  523. // given ID type, because that would use the `InstId` overload for
  524. // `AbsoluteInstId` and similar wrapper types, which should be left alone.
  525. template <typename IdT>
  526. static constexpr bool HasGetConstantValueOverload = requires {
  527. Accept<auto (*)(EvalContext&, IdT, Phase*)->IdT>(GetConstantValue);
  528. };
  529. // Given the stored value `arg` of an instruction field and its corresponding
  530. // kind `kind`, returns the constant value to use for that field, if it has a
  531. // constant phase. `*phase` is updated to include the new constant value. If
  532. // the resulting phase is not constant, the returned value is not useful and
  533. // will typically be `NoneIndex`.
  534. template <typename... Type>
  535. static auto GetConstantValueForArg(EvalContext& eval_context,
  536. SemIR::TypeEnum<Type...> kind, int32_t arg,
  537. Phase* phase) -> int32_t {
  538. using Handler = auto(EvalContext&, int32_t arg, Phase * phase)->int32_t;
  539. static constexpr Handler* Handlers[] = {
  540. [](EvalContext& eval_context, int32_t arg, Phase* phase) -> int32_t {
  541. auto id = SemIR::Inst::FromRaw<Type>(arg);
  542. if constexpr (HasGetConstantValueOverload<Type>) {
  543. // If we have a custom `GetConstantValue` overload, call it.
  544. return SemIR::Inst::ToRaw(GetConstantValue(eval_context, id, phase));
  545. } else {
  546. // Otherwise, we assume the value is already constant.
  547. return arg;
  548. }
  549. }...,
  550. [](EvalContext&, int32_t, Phase*) -> int32_t {
  551. // Handler for IdKind::Invalid is next.
  552. CARBON_FATAL("Instruction has argument with invalid IdKind");
  553. },
  554. [](EvalContext&, int32_t arg, Phase*) -> int32_t {
  555. // Handler for IdKind::None is last.
  556. return arg;
  557. }};
  558. return Handlers[kind.ToIndex()](eval_context, arg, phase);
  559. }
  560. // Given an instruction, replaces its type and operands with their constant
  561. // values from the specified evaluation context. `*phase` is updated to describe
  562. // the constant phase of the result. Returns whether `*phase` is a constant
  563. // phase; if not, `inst` may not be fully updated and should not be used.
  564. static auto ReplaceAllFieldsWithConstantValues(EvalContext& eval_context,
  565. SemIR::Inst* inst, Phase* phase)
  566. -> bool {
  567. auto type_id = SemIR::TypeId(
  568. GetConstantValueForArg(eval_context, SemIR::IdKind::For<SemIR::TypeId>,
  569. inst->type_id().index, phase));
  570. inst->SetType(type_id);
  571. if (!IsConstant(*phase)) {
  572. return false;
  573. }
  574. auto kinds = inst->ArgKinds();
  575. auto arg0 =
  576. GetConstantValueForArg(eval_context, kinds.first, inst->arg0(), phase);
  577. if (!IsConstant(*phase)) {
  578. return false;
  579. }
  580. auto arg1 =
  581. GetConstantValueForArg(eval_context, kinds.second, inst->arg1(), phase);
  582. if (!IsConstant(*phase)) {
  583. return false;
  584. }
  585. inst->SetArgs(arg0, arg1);
  586. return true;
  587. }
  588. // Performs an index into a homogeneous aggregate, retrieving the specified
  589. // element.
  590. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  591. -> SemIR::ConstantId {
  592. Phase phase = Phase::Concrete;
  593. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  594. if (!index_id.has_value()) {
  595. return MakeNonConstantResult(phase);
  596. }
  597. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  598. if (!index) {
  599. CARBON_CHECK(phase != Phase::Concrete,
  600. "Concrete constant integer should be a literal");
  601. return MakeNonConstantResult(phase);
  602. }
  603. // Array indexing is invalid if the index is constant and out of range,
  604. // regardless of whether the array itself is constant.
  605. const auto& index_val = eval_context.ints().Get(index->int_id);
  606. auto aggregate_type_id = eval_context.GetConstantValueAsType(
  607. eval_context.insts().Get(inst.array_id).type_id());
  608. if (auto array_type =
  609. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  610. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  611. array_type->bound_id)) {
  612. // This awkward call to `getZExtValue` is a workaround for APInt not
  613. // supporting comparisons between integers of different bit widths.
  614. if (index_val.getActiveBits() > 64 ||
  615. eval_context.ints()
  616. .Get(bound->int_id)
  617. .ule(index_val.getZExtValue())) {
  618. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  619. "array index `{0}` is past the end of type {1}",
  620. TypedInt, SemIR::TypeId);
  621. eval_context.emitter().Emit(
  622. eval_context.GetDiagnosticLoc(inst.index_id), ArrayIndexOutOfBounds,
  623. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  624. return SemIR::ErrorInst::SingletonConstantId;
  625. }
  626. }
  627. }
  628. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  629. if (!aggregate_id.has_value()) {
  630. return MakeNonConstantResult(phase);
  631. }
  632. auto aggregate =
  633. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  634. if (!aggregate) {
  635. CARBON_CHECK(phase != Phase::Concrete,
  636. "Unexpected representation for template constant aggregate");
  637. return MakeNonConstantResult(phase);
  638. }
  639. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  640. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  641. }
  642. // Forms a constant int type as an evaluation result. Requires that width_id is
  643. // constant.
  644. static auto MakeIntTypeResult(Context& context, SemIRLoc loc,
  645. SemIR::IntKind int_kind, SemIR::InstId width_id,
  646. Phase phase) -> SemIR::ConstantId {
  647. auto result = SemIR::IntType{
  648. .type_id = GetSingletonType(context, SemIR::TypeType::SingletonInstId),
  649. .int_kind = int_kind,
  650. .bit_width_id = width_id};
  651. if (!ValidateIntType(context, loc, result)) {
  652. return SemIR::ErrorInst::SingletonConstantId;
  653. }
  654. return MakeConstantResult(context, result, phase);
  655. }
  656. // Performs a conversion between integer types, truncating if the value doesn't
  657. // fit in the destination type.
  658. static auto PerformIntConvert(Context& context, SemIR::InstId arg_id,
  659. SemIR::TypeId dest_type_id) -> SemIR::ConstantId {
  660. auto arg_val =
  661. context.ints().Get(context.insts().GetAs<SemIR::IntValue>(arg_id).int_id);
  662. auto [dest_is_signed, bit_width_id] =
  663. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  664. if (bit_width_id.has_value()) {
  665. // TODO: If the value fits in the destination type, reuse the existing
  666. // int_id rather than recomputing it. This is probably the most common case.
  667. bool src_is_signed = context.sem_ir().types().IsSignedInt(
  668. context.insts().Get(arg_id).type_id());
  669. unsigned width = context.ints().Get(bit_width_id).getZExtValue();
  670. arg_val =
  671. src_is_signed ? arg_val.sextOrTrunc(width) : arg_val.zextOrTrunc(width);
  672. }
  673. return MakeIntResult(context, dest_type_id, dest_is_signed, arg_val);
  674. }
  675. // Performs a conversion between integer types, diagnosing if the value doesn't
  676. // fit in the destination type.
  677. static auto PerformCheckedIntConvert(Context& context, SemIRLoc loc,
  678. SemIR::InstId arg_id,
  679. SemIR::TypeId dest_type_id)
  680. -> SemIR::ConstantId {
  681. auto arg = context.insts().GetAs<SemIR::IntValue>(arg_id);
  682. auto arg_val = context.ints().Get(arg.int_id);
  683. auto [is_signed, bit_width_id] =
  684. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  685. auto width = bit_width_id.has_value()
  686. ? context.ints().Get(bit_width_id).getZExtValue()
  687. : arg_val.getBitWidth();
  688. if (!is_signed && arg_val.isNegative()) {
  689. CARBON_DIAGNOSTIC(
  690. NegativeIntInUnsignedType, Error,
  691. "negative integer value {0} converted to unsigned type {1}", TypedInt,
  692. SemIR::TypeId);
  693. context.emitter().Emit(loc, NegativeIntInUnsignedType,
  694. {.type = arg.type_id, .value = arg_val},
  695. dest_type_id);
  696. }
  697. unsigned arg_non_sign_bits = arg_val.getSignificantBits() - 1;
  698. if (arg_non_sign_bits + is_signed > width) {
  699. CARBON_DIAGNOSTIC(IntTooLargeForType, Error,
  700. "integer value {0} too large for type {1}", TypedInt,
  701. SemIR::TypeId);
  702. context.emitter().Emit(loc, IntTooLargeForType,
  703. {.type = arg.type_id, .value = arg_val},
  704. dest_type_id);
  705. }
  706. return MakeConstantResult(
  707. context, SemIR::IntValue{.type_id = dest_type_id, .int_id = arg.int_id},
  708. Phase::Concrete);
  709. }
  710. // Issues a diagnostic for a compile-time division by zero.
  711. static auto DiagnoseDivisionByZero(Context& context, SemIRLoc loc) -> void {
  712. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  713. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  714. }
  715. // Get an integer at a suitable bit-width: either `bit_width_id` if it has a
  716. // value, or the canonical width from the value store if not.
  717. static auto GetIntAtSuitableWidth(Context& context, IntId int_id,
  718. IntId bit_width_id) -> llvm::APInt {
  719. return bit_width_id.has_value()
  720. ? context.ints().GetAtWidth(int_id, bit_width_id)
  721. : context.ints().Get(int_id);
  722. }
  723. // Performs a builtin unary integer -> integer operation.
  724. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLoc loc,
  725. SemIR::BuiltinFunctionKind builtin_kind,
  726. SemIR::InstId arg_id)
  727. -> SemIR::ConstantId {
  728. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  729. auto [is_signed, bit_width_id] =
  730. context.sem_ir().types().GetIntTypeInfo(op.type_id);
  731. llvm::APInt op_val = GetIntAtSuitableWidth(context, op.int_id, bit_width_id);
  732. switch (builtin_kind) {
  733. case SemIR::BuiltinFunctionKind::IntSNegate:
  734. if (op_val.isMinSignedValue()) {
  735. if (bit_width_id.has_value()) {
  736. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  737. "integer overflow in negation of {0}", TypedInt);
  738. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  739. {.type = op.type_id, .value = op_val});
  740. } else {
  741. // Widen the integer so we don't overflow into the sign bit.
  742. op_val = op_val.sext(op_val.getBitWidth() +
  743. llvm::APInt::APINT_BITS_PER_WORD);
  744. }
  745. }
  746. op_val.negate();
  747. break;
  748. case SemIR::BuiltinFunctionKind::IntUNegate:
  749. CARBON_CHECK(bit_width_id.has_value(), "Unsigned negate on unsized int");
  750. op_val.negate();
  751. break;
  752. case SemIR::BuiltinFunctionKind::IntComplement:
  753. // TODO: Should we have separate builtins for signed and unsigned
  754. // complement? Like with signed/unsigned negate, these operations do
  755. // different things to the integer value, even though they do the same
  756. // thing to the bits. We treat IntLiteral complement as signed complement,
  757. // given that the result of unsigned complement depends on the bit width.
  758. op_val.flipAllBits();
  759. break;
  760. default:
  761. CARBON_FATAL("Unexpected builtin kind");
  762. }
  763. return MakeIntResult(context, op.type_id, is_signed, std::move(op_val));
  764. }
  765. namespace {
  766. // A pair of APInts that are the operands of a binary operator. We use an
  767. // aggregate rather than `std::pair` to allow RVO of the individual ints.
  768. struct APIntBinaryOperands {
  769. llvm::APInt lhs;
  770. llvm::APInt rhs;
  771. };
  772. } // namespace
  773. // Get a pair of integers at the same suitable bit-width: either their actual
  774. // width if they have a fixed width, or the smallest canonical width in which
  775. // they both fit otherwise.
  776. static auto GetIntsAtSuitableWidth(Context& context, IntId lhs_id, IntId rhs_id,
  777. IntId bit_width_id) -> APIntBinaryOperands {
  778. // Unsized operands: take the wider of the bit widths.
  779. if (!bit_width_id.has_value()) {
  780. APIntBinaryOperands result = {.lhs = context.ints().Get(lhs_id),
  781. .rhs = context.ints().Get(rhs_id)};
  782. if (result.lhs.getBitWidth() != result.rhs.getBitWidth()) {
  783. if (result.lhs.getBitWidth() > result.rhs.getBitWidth()) {
  784. result.rhs = result.rhs.sext(result.lhs.getBitWidth());
  785. } else {
  786. result.lhs = result.lhs.sext(result.rhs.getBitWidth());
  787. }
  788. }
  789. return result;
  790. }
  791. return {.lhs = context.ints().GetAtWidth(lhs_id, bit_width_id),
  792. .rhs = context.ints().GetAtWidth(rhs_id, bit_width_id)};
  793. }
  794. namespace {
  795. // The result of performing a binary int operation.
  796. struct BinaryIntOpResult {
  797. llvm::APInt result_val;
  798. bool overflow;
  799. Lex::TokenKind op_token;
  800. };
  801. } // namespace
  802. // Computes the result of a homogeneous binary (int, int) -> int operation.
  803. static auto ComputeBinaryIntOpResult(SemIR::BuiltinFunctionKind builtin_kind,
  804. const llvm::APInt& lhs_val,
  805. const llvm::APInt& rhs_val)
  806. -> BinaryIntOpResult {
  807. llvm::APInt result_val;
  808. bool overflow = false;
  809. Lex::TokenKind op_token = Lex::TokenKind::Not;
  810. switch (builtin_kind) {
  811. // Arithmetic.
  812. case SemIR::BuiltinFunctionKind::IntSAdd:
  813. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  814. op_token = Lex::TokenKind::Plus;
  815. break;
  816. case SemIR::BuiltinFunctionKind::IntSSub:
  817. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  818. op_token = Lex::TokenKind::Minus;
  819. break;
  820. case SemIR::BuiltinFunctionKind::IntSMul:
  821. result_val = lhs_val.smul_ov(rhs_val, overflow);
  822. op_token = Lex::TokenKind::Star;
  823. break;
  824. case SemIR::BuiltinFunctionKind::IntSDiv:
  825. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  826. op_token = Lex::TokenKind::Slash;
  827. break;
  828. case SemIR::BuiltinFunctionKind::IntSMod:
  829. result_val = lhs_val.srem(rhs_val);
  830. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  831. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  832. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  833. op_token = Lex::TokenKind::Percent;
  834. break;
  835. case SemIR::BuiltinFunctionKind::IntUAdd:
  836. result_val = lhs_val + rhs_val;
  837. op_token = Lex::TokenKind::Plus;
  838. break;
  839. case SemIR::BuiltinFunctionKind::IntUSub:
  840. result_val = lhs_val - rhs_val;
  841. op_token = Lex::TokenKind::Minus;
  842. break;
  843. case SemIR::BuiltinFunctionKind::IntUMul:
  844. result_val = lhs_val * rhs_val;
  845. op_token = Lex::TokenKind::Star;
  846. break;
  847. case SemIR::BuiltinFunctionKind::IntUDiv:
  848. result_val = lhs_val.udiv(rhs_val);
  849. op_token = Lex::TokenKind::Slash;
  850. break;
  851. case SemIR::BuiltinFunctionKind::IntUMod:
  852. result_val = lhs_val.urem(rhs_val);
  853. op_token = Lex::TokenKind::Percent;
  854. break;
  855. // Bitwise.
  856. case SemIR::BuiltinFunctionKind::IntAnd:
  857. result_val = lhs_val & rhs_val;
  858. op_token = Lex::TokenKind::And;
  859. break;
  860. case SemIR::BuiltinFunctionKind::IntOr:
  861. result_val = lhs_val | rhs_val;
  862. op_token = Lex::TokenKind::Pipe;
  863. break;
  864. case SemIR::BuiltinFunctionKind::IntXor:
  865. result_val = lhs_val ^ rhs_val;
  866. op_token = Lex::TokenKind::Caret;
  867. break;
  868. case SemIR::BuiltinFunctionKind::IntLeftShift:
  869. case SemIR::BuiltinFunctionKind::IntRightShift:
  870. CARBON_FATAL("Non-homogeneous operation handled separately.");
  871. default:
  872. CARBON_FATAL("Unexpected operation kind.");
  873. }
  874. return {.result_val = std::move(result_val),
  875. .overflow = overflow,
  876. .op_token = op_token};
  877. }
  878. // Performs a builtin integer bit shift operation.
  879. static auto PerformBuiltinIntShiftOp(Context& context, SemIRLoc loc,
  880. SemIR::BuiltinFunctionKind builtin_kind,
  881. SemIR::InstId lhs_id, SemIR::InstId rhs_id)
  882. -> SemIR::ConstantId {
  883. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  884. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  885. auto [lhs_is_signed, lhs_bit_width_id] =
  886. context.sem_ir().types().GetIntTypeInfo(lhs.type_id);
  887. llvm::APInt lhs_val =
  888. GetIntAtSuitableWidth(context, lhs.int_id, lhs_bit_width_id);
  889. const auto& rhs_orig_val = context.ints().Get(rhs.int_id);
  890. if (lhs_bit_width_id.has_value() && rhs_orig_val.uge(lhs_val.getBitWidth())) {
  891. CARBON_DIAGNOSTIC(
  892. CompileTimeShiftOutOfRange, Error,
  893. "shift distance >= type width of {0} in `{1} {2:<<|>>} {3}`", unsigned,
  894. TypedInt, BoolAsSelect, TypedInt);
  895. context.emitter().Emit(
  896. loc, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  897. {.type = lhs.type_id, .value = lhs_val},
  898. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  899. {.type = rhs.type_id, .value = rhs_orig_val});
  900. // TODO: Is it useful to recover by returning 0 or -1?
  901. return SemIR::ErrorInst::SingletonConstantId;
  902. }
  903. if (rhs_orig_val.isNegative() &&
  904. context.sem_ir().types().IsSignedInt(rhs.type_id)) {
  905. CARBON_DIAGNOSTIC(CompileTimeShiftNegative, Error,
  906. "shift distance negative in `{0} {1:<<|>>} {2}`",
  907. TypedInt, BoolAsSelect, TypedInt);
  908. context.emitter().Emit(
  909. loc, CompileTimeShiftNegative, {.type = lhs.type_id, .value = lhs_val},
  910. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  911. {.type = rhs.type_id, .value = rhs_orig_val});
  912. // TODO: Is it useful to recover by returning 0 or -1?
  913. return SemIR::ErrorInst::SingletonConstantId;
  914. }
  915. llvm::APInt result_val;
  916. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  917. if (!lhs_bit_width_id.has_value() && !lhs_val.isZero()) {
  918. // Ensure we don't generate a ridiculously large integer through a bit
  919. // shift.
  920. auto width = rhs_orig_val.trySExtValue();
  921. if (!width ||
  922. *width > IntStore::MaxIntWidth - lhs_val.getSignificantBits()) {
  923. CARBON_DIAGNOSTIC(CompileTimeUnsizedShiftOutOfRange, Error,
  924. "shift distance of {0} would result in an "
  925. "integer whose width is greater than the "
  926. "maximum supported width of {1}",
  927. TypedInt, int);
  928. context.emitter().Emit(loc, CompileTimeUnsizedShiftOutOfRange,
  929. {.type = rhs.type_id, .value = rhs_orig_val},
  930. IntStore::MaxIntWidth);
  931. return SemIR::ErrorInst::SingletonConstantId;
  932. }
  933. lhs_val = lhs_val.sext(
  934. IntStore::CanonicalBitWidth(lhs_val.getSignificantBits() + *width));
  935. }
  936. result_val =
  937. lhs_val.shl(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  938. } else if (lhs_is_signed) {
  939. result_val =
  940. lhs_val.ashr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  941. } else {
  942. CARBON_CHECK(lhs_bit_width_id.has_value(), "Logical shift on unsized int");
  943. result_val =
  944. lhs_val.lshr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  945. }
  946. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  947. std::move(result_val));
  948. }
  949. // Performs a homogeneous builtin binary integer -> integer operation.
  950. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLoc loc,
  951. SemIR::BuiltinFunctionKind builtin_kind,
  952. SemIR::InstId lhs_id,
  953. SemIR::InstId rhs_id)
  954. -> SemIR::ConstantId {
  955. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  956. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  957. CARBON_CHECK(rhs.type_id == lhs.type_id, "Heterogeneous builtin integer op!");
  958. auto type_id = lhs.type_id;
  959. auto [is_signed, bit_width_id] =
  960. context.sem_ir().types().GetIntTypeInfo(type_id);
  961. auto [lhs_val, rhs_val] =
  962. GetIntsAtSuitableWidth(context, lhs.int_id, rhs.int_id, bit_width_id);
  963. // Check for division by zero.
  964. switch (builtin_kind) {
  965. case SemIR::BuiltinFunctionKind::IntSDiv:
  966. case SemIR::BuiltinFunctionKind::IntSMod:
  967. case SemIR::BuiltinFunctionKind::IntUDiv:
  968. case SemIR::BuiltinFunctionKind::IntUMod:
  969. if (rhs_val.isZero()) {
  970. DiagnoseDivisionByZero(context, loc);
  971. return SemIR::ErrorInst::SingletonConstantId;
  972. }
  973. break;
  974. default:
  975. break;
  976. }
  977. BinaryIntOpResult result =
  978. ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  979. if (result.overflow && !bit_width_id.has_value()) {
  980. // Retry with a larger bit width. Most operations can only overflow by one
  981. // bit, but signed n-bit multiplication can overflow to 2n-1 bits. We don't
  982. // need to handle unsigned multiplication here because it's not permitted
  983. // for unsized integers.
  984. //
  985. // Note that we speculatively first perform the calculation in the width of
  986. // the wider operand: smaller operations are faster and overflow to a wider
  987. // integer is unlikely to be needed, especially given that the width will
  988. // have been rounded up to a multiple of 64 bits by the int store.
  989. CARBON_CHECK(builtin_kind != SemIR::BuiltinFunctionKind::IntUMul,
  990. "Unsigned arithmetic requires a fixed bitwidth");
  991. int new_width =
  992. builtin_kind == SemIR::BuiltinFunctionKind::IntSMul
  993. ? lhs_val.getBitWidth() * 2
  994. : IntStore::CanonicalBitWidth(lhs_val.getBitWidth() + 1);
  995. new_width = std::min(new_width, IntStore::MaxIntWidth);
  996. lhs_val = context.ints().GetAtWidth(lhs.int_id, new_width);
  997. rhs_val = context.ints().GetAtWidth(rhs.int_id, new_width);
  998. // Note that this can in theory still overflow if we limited `new_width` to
  999. // `MaxIntWidth`. In that case we fall through to the signed overflow
  1000. // diagnostic below.
  1001. result = ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1002. CARBON_CHECK(!result.overflow || new_width == IntStore::MaxIntWidth);
  1003. }
  1004. if (result.overflow) {
  1005. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  1006. "integer overflow in calculation `{0} {1} {2}`", TypedInt,
  1007. Lex::TokenKind, TypedInt);
  1008. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  1009. {.type = type_id, .value = lhs_val}, result.op_token,
  1010. {.type = type_id, .value = rhs_val});
  1011. }
  1012. return MakeIntResult(context, type_id, is_signed,
  1013. std::move(result.result_val));
  1014. }
  1015. // Performs a builtin integer comparison.
  1016. static auto PerformBuiltinIntComparison(Context& context,
  1017. SemIR::BuiltinFunctionKind builtin_kind,
  1018. SemIR::InstId lhs_id,
  1019. SemIR::InstId rhs_id,
  1020. SemIR::TypeId bool_type_id)
  1021. -> SemIR::ConstantId {
  1022. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1023. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1024. llvm::APInt lhs_val = context.ints().Get(lhs.int_id);
  1025. llvm::APInt rhs_val = context.ints().Get(rhs.int_id);
  1026. bool result;
  1027. switch (builtin_kind) {
  1028. case SemIR::BuiltinFunctionKind::IntEq:
  1029. result = (lhs_val == rhs_val);
  1030. break;
  1031. case SemIR::BuiltinFunctionKind::IntNeq:
  1032. result = (lhs_val != rhs_val);
  1033. break;
  1034. case SemIR::BuiltinFunctionKind::IntLess:
  1035. result = lhs_val.slt(rhs_val);
  1036. break;
  1037. case SemIR::BuiltinFunctionKind::IntLessEq:
  1038. result = lhs_val.sle(rhs_val);
  1039. break;
  1040. case SemIR::BuiltinFunctionKind::IntGreater:
  1041. result = lhs_val.sgt(rhs_val);
  1042. break;
  1043. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  1044. result = lhs_val.sge(rhs_val);
  1045. break;
  1046. default:
  1047. CARBON_FATAL("Unexpected operation kind.");
  1048. }
  1049. return MakeBoolResult(context, bool_type_id, result);
  1050. }
  1051. // Performs a builtin unary float -> float operation.
  1052. static auto PerformBuiltinUnaryFloatOp(Context& context,
  1053. SemIR::BuiltinFunctionKind builtin_kind,
  1054. SemIR::InstId arg_id)
  1055. -> SemIR::ConstantId {
  1056. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  1057. auto op_val = context.floats().Get(op.float_id);
  1058. switch (builtin_kind) {
  1059. case SemIR::BuiltinFunctionKind::FloatNegate:
  1060. op_val.changeSign();
  1061. break;
  1062. default:
  1063. CARBON_FATAL("Unexpected builtin kind");
  1064. }
  1065. return MakeFloatResult(context, op.type_id, std::move(op_val));
  1066. }
  1067. // Performs a builtin binary float -> float operation.
  1068. static auto PerformBuiltinBinaryFloatOp(Context& context,
  1069. SemIR::BuiltinFunctionKind builtin_kind,
  1070. SemIR::InstId lhs_id,
  1071. SemIR::InstId rhs_id)
  1072. -> SemIR::ConstantId {
  1073. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  1074. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  1075. auto lhs_val = context.floats().Get(lhs.float_id);
  1076. auto rhs_val = context.floats().Get(rhs.float_id);
  1077. llvm::APFloat result_val(lhs_val.getSemantics());
  1078. switch (builtin_kind) {
  1079. case SemIR::BuiltinFunctionKind::FloatAdd:
  1080. result_val = lhs_val + rhs_val;
  1081. break;
  1082. case SemIR::BuiltinFunctionKind::FloatSub:
  1083. result_val = lhs_val - rhs_val;
  1084. break;
  1085. case SemIR::BuiltinFunctionKind::FloatMul:
  1086. result_val = lhs_val * rhs_val;
  1087. break;
  1088. case SemIR::BuiltinFunctionKind::FloatDiv:
  1089. result_val = lhs_val / rhs_val;
  1090. break;
  1091. default:
  1092. CARBON_FATAL("Unexpected operation kind.");
  1093. }
  1094. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  1095. }
  1096. // Performs a builtin float comparison.
  1097. static auto PerformBuiltinFloatComparison(
  1098. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1099. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  1100. -> SemIR::ConstantId {
  1101. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  1102. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  1103. const auto& lhs_val = context.floats().Get(lhs.float_id);
  1104. const auto& rhs_val = context.floats().Get(rhs.float_id);
  1105. bool result;
  1106. switch (builtin_kind) {
  1107. case SemIR::BuiltinFunctionKind::FloatEq:
  1108. result = (lhs_val == rhs_val);
  1109. break;
  1110. case SemIR::BuiltinFunctionKind::FloatNeq:
  1111. result = (lhs_val != rhs_val);
  1112. break;
  1113. case SemIR::BuiltinFunctionKind::FloatLess:
  1114. result = lhs_val < rhs_val;
  1115. break;
  1116. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1117. result = lhs_val <= rhs_val;
  1118. break;
  1119. case SemIR::BuiltinFunctionKind::FloatGreater:
  1120. result = lhs_val > rhs_val;
  1121. break;
  1122. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  1123. result = lhs_val >= rhs_val;
  1124. break;
  1125. default:
  1126. CARBON_FATAL("Unexpected operation kind.");
  1127. }
  1128. return MakeBoolResult(context, bool_type_id, result);
  1129. }
  1130. // Performs a builtin boolean comparison.
  1131. static auto PerformBuiltinBoolComparison(
  1132. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1133. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id) {
  1134. bool lhs = context.insts().GetAs<SemIR::BoolLiteral>(lhs_id).value.ToBool();
  1135. bool rhs = context.insts().GetAs<SemIR::BoolLiteral>(rhs_id).value.ToBool();
  1136. return MakeBoolResult(context, bool_type_id,
  1137. builtin_kind == SemIR::BuiltinFunctionKind::BoolEq
  1138. ? lhs == rhs
  1139. : lhs != rhs);
  1140. }
  1141. // Returns a constant for a call to a builtin function.
  1142. static auto MakeConstantForBuiltinCall(EvalContext& eval_context, SemIRLoc loc,
  1143. SemIR::Call call,
  1144. SemIR::BuiltinFunctionKind builtin_kind,
  1145. llvm::ArrayRef<SemIR::InstId> arg_ids,
  1146. Phase phase) -> SemIR::ConstantId {
  1147. auto& context = eval_context.context();
  1148. switch (builtin_kind) {
  1149. case SemIR::BuiltinFunctionKind::None:
  1150. CARBON_FATAL("Not a builtin function.");
  1151. case SemIR::BuiltinFunctionKind::PrintChar:
  1152. case SemIR::BuiltinFunctionKind::PrintInt:
  1153. case SemIR::BuiltinFunctionKind::ReadChar: {
  1154. // These are runtime-only builtins.
  1155. // TODO: Consider tracking this on the `BuiltinFunctionKind`.
  1156. return SemIR::ConstantId::NotConstant;
  1157. }
  1158. case SemIR::BuiltinFunctionKind::TypeAnd: {
  1159. CARBON_CHECK(arg_ids.size() == 2);
  1160. auto lhs_facet_type_id = SemIR::FacetTypeId::None;
  1161. auto rhs_facet_type_id = SemIR::FacetTypeId::None;
  1162. for (auto [facet_type_id, arg_id] :
  1163. llvm::zip(std::to_array({&lhs_facet_type_id, &rhs_facet_type_id}),
  1164. arg_ids)) {
  1165. if (auto facet_type =
  1166. context.insts().TryGetAs<SemIR::FacetType>(arg_id)) {
  1167. *facet_type_id = facet_type->facet_type_id;
  1168. } else {
  1169. CARBON_DIAGNOSTIC(FacetTypeRequiredForTypeAndOperator, Error,
  1170. "non-facet type {0} combined with `&` operator",
  1171. SemIR::TypeId);
  1172. // TODO: Find a location for the lhs or rhs specifically, instead of
  1173. // the whole thing. If that's not possible we can change the text to
  1174. // say if it's referring to the left or the right side for the error.
  1175. // The `arg_id` instruction has no location in it for some reason.
  1176. context.emitter().Emit(
  1177. loc, FacetTypeRequiredForTypeAndOperator,
  1178. context.types().GetTypeIdForTypeInstId(arg_id));
  1179. }
  1180. }
  1181. // Allow errors to be diagnosed for both sides of the operator before
  1182. // returning here if any error occurred on either side.
  1183. if (!lhs_facet_type_id.has_value() || !rhs_facet_type_id.has_value()) {
  1184. return SemIR::ErrorInst::SingletonConstantId;
  1185. }
  1186. // Reuse one of the argument instructions if nothing has changed.
  1187. if (lhs_facet_type_id == rhs_facet_type_id) {
  1188. return context.types().GetConstantId(
  1189. context.types().GetTypeIdForTypeInstId(arg_ids[0]));
  1190. }
  1191. auto info = SemIR::FacetTypeInfo::Combine(
  1192. context.facet_types().Get(lhs_facet_type_id),
  1193. context.facet_types().Get(rhs_facet_type_id));
  1194. info.Canonicalize();
  1195. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1196. }
  1197. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  1198. return context.constant_values().Get(
  1199. SemIR::IntLiteralType::SingletonInstId);
  1200. }
  1201. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  1202. return MakeIntTypeResult(context, loc, SemIR::IntKind::Signed, arg_ids[0],
  1203. phase);
  1204. }
  1205. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  1206. return MakeIntTypeResult(context, loc, SemIR::IntKind::Unsigned,
  1207. arg_ids[0], phase);
  1208. }
  1209. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  1210. // TODO: Support a symbolic constant width.
  1211. if (phase != Phase::Concrete) {
  1212. break;
  1213. }
  1214. if (!ValidateFloatBitWidth(context, loc, arg_ids[0])) {
  1215. return SemIR::ErrorInst::SingletonConstantId;
  1216. }
  1217. return context.constant_values().Get(
  1218. SemIR::LegacyFloatType::SingletonInstId);
  1219. }
  1220. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  1221. return context.constant_values().Get(SemIR::BoolType::SingletonInstId);
  1222. }
  1223. // Integer conversions.
  1224. case SemIR::BuiltinFunctionKind::IntConvert: {
  1225. if (phase != Phase::Concrete) {
  1226. return MakeConstantResult(context, call, phase);
  1227. }
  1228. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1229. }
  1230. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  1231. if (phase != Phase::Concrete) {
  1232. return MakeConstantResult(context, call, phase);
  1233. }
  1234. return PerformCheckedIntConvert(context, loc, arg_ids[0], call.type_id);
  1235. }
  1236. // Unary integer -> integer operations.
  1237. case SemIR::BuiltinFunctionKind::IntSNegate:
  1238. case SemIR::BuiltinFunctionKind::IntUNegate:
  1239. case SemIR::BuiltinFunctionKind::IntComplement: {
  1240. if (phase != Phase::Concrete) {
  1241. break;
  1242. }
  1243. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  1244. }
  1245. // Homogeneous binary integer -> integer operations.
  1246. case SemIR::BuiltinFunctionKind::IntSAdd:
  1247. case SemIR::BuiltinFunctionKind::IntSSub:
  1248. case SemIR::BuiltinFunctionKind::IntSMul:
  1249. case SemIR::BuiltinFunctionKind::IntSDiv:
  1250. case SemIR::BuiltinFunctionKind::IntSMod:
  1251. case SemIR::BuiltinFunctionKind::IntUAdd:
  1252. case SemIR::BuiltinFunctionKind::IntUSub:
  1253. case SemIR::BuiltinFunctionKind::IntUMul:
  1254. case SemIR::BuiltinFunctionKind::IntUDiv:
  1255. case SemIR::BuiltinFunctionKind::IntUMod:
  1256. case SemIR::BuiltinFunctionKind::IntAnd:
  1257. case SemIR::BuiltinFunctionKind::IntOr:
  1258. case SemIR::BuiltinFunctionKind::IntXor: {
  1259. if (phase != Phase::Concrete) {
  1260. break;
  1261. }
  1262. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  1263. arg_ids[1]);
  1264. }
  1265. // Bit shift operations.
  1266. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1267. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1268. if (phase != Phase::Concrete) {
  1269. break;
  1270. }
  1271. return PerformBuiltinIntShiftOp(context, loc, builtin_kind, arg_ids[0],
  1272. arg_ids[1]);
  1273. }
  1274. // Integer comparisons.
  1275. case SemIR::BuiltinFunctionKind::IntEq:
  1276. case SemIR::BuiltinFunctionKind::IntNeq:
  1277. case SemIR::BuiltinFunctionKind::IntLess:
  1278. case SemIR::BuiltinFunctionKind::IntLessEq:
  1279. case SemIR::BuiltinFunctionKind::IntGreater:
  1280. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1281. if (phase != Phase::Concrete) {
  1282. break;
  1283. }
  1284. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1285. arg_ids[1], call.type_id);
  1286. }
  1287. // Unary float -> float operations.
  1288. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1289. if (phase != Phase::Concrete) {
  1290. break;
  1291. }
  1292. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1293. }
  1294. // Binary float -> float operations.
  1295. case SemIR::BuiltinFunctionKind::FloatAdd:
  1296. case SemIR::BuiltinFunctionKind::FloatSub:
  1297. case SemIR::BuiltinFunctionKind::FloatMul:
  1298. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1299. if (phase != Phase::Concrete) {
  1300. break;
  1301. }
  1302. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1303. arg_ids[1]);
  1304. }
  1305. // Float comparisons.
  1306. case SemIR::BuiltinFunctionKind::FloatEq:
  1307. case SemIR::BuiltinFunctionKind::FloatNeq:
  1308. case SemIR::BuiltinFunctionKind::FloatLess:
  1309. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1310. case SemIR::BuiltinFunctionKind::FloatGreater:
  1311. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1312. if (phase != Phase::Concrete) {
  1313. break;
  1314. }
  1315. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1316. arg_ids[1], call.type_id);
  1317. }
  1318. // Bool comparisons.
  1319. case SemIR::BuiltinFunctionKind::BoolEq:
  1320. case SemIR::BuiltinFunctionKind::BoolNeq: {
  1321. if (phase != Phase::Concrete) {
  1322. break;
  1323. }
  1324. return PerformBuiltinBoolComparison(context, builtin_kind, arg_ids[0],
  1325. arg_ids[1], call.type_id);
  1326. }
  1327. }
  1328. return SemIR::ConstantId::NotConstant;
  1329. }
  1330. // Makes a constant for a call instruction.
  1331. static auto MakeConstantForCall(EvalContext& eval_context, SemIRLoc loc,
  1332. SemIR::Call call) -> SemIR::ConstantId {
  1333. Phase phase = Phase::Concrete;
  1334. // A call with an invalid argument list is used to represent an erroneous
  1335. // call.
  1336. //
  1337. // TODO: Use a better representation for this.
  1338. if (call.args_id == SemIR::InstBlockId::None) {
  1339. return SemIR::ErrorInst::SingletonConstantId;
  1340. }
  1341. // Find the constant value of the callee.
  1342. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1343. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1344. auto callee_function =
  1345. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  1346. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1347. if (callee_function.function_id.has_value()) {
  1348. // Calls to builtins might be constant.
  1349. builtin_kind = eval_context.functions()
  1350. .Get(callee_function.function_id)
  1351. .builtin_function_kind;
  1352. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  1353. // TODO: Eventually we'll want to treat some kinds of non-builtin
  1354. // functions as producing constants.
  1355. return SemIR::ConstantId::NotConstant;
  1356. }
  1357. } else {
  1358. // Calls to non-functions, such as calls to generic entity names, might be
  1359. // constant.
  1360. }
  1361. // Find the argument values and the return type.
  1362. bool has_constant_operands =
  1363. has_constant_callee &&
  1364. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::type_id,
  1365. &phase) &&
  1366. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1367. &phase);
  1368. if (phase == Phase::UnknownDueToError) {
  1369. return SemIR::ErrorInst::SingletonConstantId;
  1370. }
  1371. // If any operand of the call is non-constant, the call is non-constant.
  1372. // TODO: Some builtin calls might allow some operands to be non-constant.
  1373. if (!has_constant_operands) {
  1374. if (builtin_kind.IsCompTimeOnly(
  1375. eval_context.sem_ir(), eval_context.inst_blocks().Get(call.args_id),
  1376. call.type_id)) {
  1377. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1378. "non-constant call to compile-time-only function");
  1379. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1380. "compile-time-only function declared here");
  1381. eval_context.emitter()
  1382. .Build(loc, NonConstantCallToCompTimeOnlyFunction)
  1383. .Note(eval_context.functions()
  1384. .Get(callee_function.function_id)
  1385. .latest_decl_id(),
  1386. CompTimeOnlyFunctionHere)
  1387. .Emit();
  1388. }
  1389. return SemIR::ConstantId::NotConstant;
  1390. }
  1391. // Handle calls to builtins.
  1392. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1393. return MakeConstantForBuiltinCall(
  1394. eval_context, loc, call, builtin_kind,
  1395. eval_context.inst_blocks().Get(call.args_id), phase);
  1396. }
  1397. return SemIR::ConstantId::NotConstant;
  1398. }
  1399. // Given an instruction, compute its phase based on its operands.
  1400. static auto ComputeInstPhase(Context& context, SemIR::Inst inst) -> Phase {
  1401. EvalContext eval_context(context, SemIR::InstId::None);
  1402. auto phase = GetPhase(context.constant_values(),
  1403. context.types().GetConstantId(inst.type_id()));
  1404. auto kinds = inst.ArgKinds();
  1405. GetConstantValueForArg(eval_context, kinds.first, inst.arg0(), &phase);
  1406. GetConstantValueForArg(eval_context, kinds.second, inst.arg1(), &phase);
  1407. CARBON_CHECK(IsConstant(phase));
  1408. return phase;
  1409. }
  1410. // Convert a ConstantEvalResult to a ConstantId. Factored out of
  1411. // TryEvalTypedInst to avoid repeated instantiation of common code.
  1412. static auto ConvertEvalResultToConstantId(Context& context,
  1413. ConstantEvalResult result,
  1414. Phase orig_phase)
  1415. -> SemIR::ConstantId {
  1416. if (result.is_new()) {
  1417. return MakeConstantResult(
  1418. context, result.new_inst(),
  1419. result.same_phase_as_inst()
  1420. ? orig_phase
  1421. : ComputeInstPhase(context, result.new_inst()));
  1422. }
  1423. return result.existing();
  1424. }
  1425. // Evaluates an instruction of a known type in an evaluation context. The
  1426. // default behavior of this function depends on the constant kind of the
  1427. // instruction:
  1428. //
  1429. // - InstConstantKind::Never: returns ConstantId::NotConstant.
  1430. // - InstConstantKind::Indirect, SymbolicOnly, Conditional: evaluates all the
  1431. // operands of the instruction, and calls `EvalConstantInst` to evaluate the
  1432. // resulting constant instruction.
  1433. // - InstConstantKind::WheneverPossible, Always: evaluates all the operands of
  1434. // the instruction, and produces the resulting constant instruction as the
  1435. // result.
  1436. // - InstConstantKind::Unique: returns the `inst_id` as the resulting
  1437. // constant.
  1438. //
  1439. // Returns an error constant ID if any of the nested evaluations fail, and
  1440. // returns NotConstant if any of the nested evaluations is non-constant.
  1441. //
  1442. // This template is explicitly specialized for instructions that need special
  1443. // handling.
  1444. template <typename InstT>
  1445. static auto TryEvalTypedInst(EvalContext& eval_context, SemIR::InstId inst_id,
  1446. SemIR::Inst inst) -> SemIR::ConstantId {
  1447. constexpr auto ConstantKind = InstT::Kind.constant_kind();
  1448. if constexpr (ConstantKind == SemIR::InstConstantKind::Never) {
  1449. return SemIR::ConstantId::NotConstant;
  1450. } else if constexpr (ConstantKind == SemIR::InstConstantKind::Unique) {
  1451. CARBON_CHECK(inst_id.has_value());
  1452. return SemIR::ConstantId::ForConcreteConstant(inst_id);
  1453. } else {
  1454. // Build a constant instruction by replacing each non-constant operand with
  1455. // its constant value.
  1456. Phase phase = Phase::Concrete;
  1457. if (!ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  1458. if constexpr (ConstantKind == SemIR::InstConstantKind::Always) {
  1459. CARBON_CHECK(phase == Phase::UnknownDueToError,
  1460. "{0} should always be constant", InstT::Kind);
  1461. }
  1462. return MakeNonConstantResult(phase);
  1463. }
  1464. if constexpr (ConstantKind == SemIR::InstConstantKind::Always ||
  1465. ConstantKind == SemIR::InstConstantKind::WheneverPossible) {
  1466. return MakeConstantResult(eval_context.context(), inst, phase);
  1467. } else {
  1468. return ConvertEvalResultToConstantId(
  1469. eval_context.context(),
  1470. EvalConstantInst(eval_context.context(),
  1471. eval_context.GetDiagnosticLoc({inst_id}),
  1472. inst.As<InstT>()),
  1473. phase);
  1474. }
  1475. }
  1476. }
  1477. // Specialize evaluation for array indexing because we want to check the index
  1478. // expression even if the array expression is non-constant.
  1479. template <>
  1480. auto TryEvalTypedInst<SemIR::ArrayIndex>(EvalContext& eval_context,
  1481. SemIR::InstId /*inst_id*/,
  1482. SemIR::Inst inst)
  1483. -> SemIR::ConstantId {
  1484. return PerformArrayIndex(eval_context, inst.As<SemIR::ArrayIndex>());
  1485. }
  1486. // Specialize evaluation for function calls because we want to check the callee
  1487. // expression even if an argument expression is non-constant, and because we
  1488. // will eventually want to perform control flow handling here.
  1489. template <>
  1490. auto TryEvalTypedInst<SemIR::Call>(EvalContext& eval_context,
  1491. SemIR::InstId inst_id, SemIR::Inst inst)
  1492. -> SemIR::ConstantId {
  1493. return MakeConstantForCall(eval_context,
  1494. eval_context.GetDiagnosticLoc(inst_id),
  1495. inst.As<SemIR::Call>());
  1496. }
  1497. // ImportRefLoaded can have a constant value, but it's owned and maintained by
  1498. // `import_ref.cpp`, not by us.
  1499. // TODO: Rearrange how `ImportRefLoaded` instructions are created so we never
  1500. // call this.
  1501. template <>
  1502. auto TryEvalTypedInst<SemIR::ImportRefLoaded>(EvalContext& /*eval_context*/,
  1503. SemIR::InstId /*inst_id*/,
  1504. SemIR::Inst /*inst*/)
  1505. -> SemIR::ConstantId {
  1506. return SemIR::ConstantId::NotConstant;
  1507. }
  1508. // TODO: Disable constant evaluation of SymbolicBindingPattern once
  1509. // DeduceGenericCallArguments no longer needs implicit params to have constant
  1510. // values.
  1511. template <>
  1512. auto TryEvalTypedInst<SemIR::SymbolicBindingPattern>(EvalContext& eval_context,
  1513. SemIR::InstId /*inst_id*/,
  1514. SemIR::Inst inst)
  1515. -> SemIR::ConstantId {
  1516. auto bind = inst.As<SemIR::SymbolicBindingPattern>();
  1517. const auto& bind_name = eval_context.entity_names().Get(bind.entity_name_id);
  1518. // If we know which specific we're evaluating within and this is an
  1519. // argument of that specific, its constant value is the corresponding
  1520. // argument value.
  1521. if (auto value = eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  1522. value.has_value()) {
  1523. // TODO: This seems incorrect: patterns don't typically evaluate to the
  1524. // value matched by the pattern.
  1525. return value;
  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. return MakeConstantResult(
  1532. eval_context.context(), bind,
  1533. bind_name.is_template ? Phase::TemplateSymbolic : Phase::CheckedSymbolic);
  1534. }
  1535. // Symbolic bindings are a special case because they can reach into the eval
  1536. // context and produce a context-specific value.
  1537. template <>
  1538. auto TryEvalTypedInst<SemIR::BindSymbolicName>(EvalContext& eval_context,
  1539. SemIR::InstId /*inst_id*/,
  1540. SemIR::Inst inst)
  1541. -> SemIR::ConstantId {
  1542. auto bind = inst.As<SemIR::BindSymbolicName>();
  1543. const auto& bind_name = eval_context.entity_names().Get(bind.entity_name_id);
  1544. Phase phase;
  1545. if (bind_name.name_id == SemIR::NameId::PeriodSelf) {
  1546. phase = Phase::PeriodSelfSymbolic;
  1547. } else {
  1548. // If we know which specific we're evaluating within and this is an
  1549. // argument of that specific, its constant value is the corresponding
  1550. // argument value.
  1551. if (auto value =
  1552. eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  1553. value.has_value()) {
  1554. return value;
  1555. }
  1556. phase = bind_name.is_template ? Phase::TemplateSymbolic
  1557. : Phase::CheckedSymbolic;
  1558. }
  1559. // The constant form of a symbolic binding is an idealized form of the
  1560. // original, with no equivalent value.
  1561. bind.entity_name_id =
  1562. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1563. bind.value_id = SemIR::InstId::None;
  1564. if (!ReplaceFieldWithConstantValue(
  1565. eval_context, &bind, &SemIR::BindSymbolicName::type_id, &phase)) {
  1566. return MakeNonConstantResult(phase);
  1567. }
  1568. return MakeConstantResult(eval_context.context(), bind, phase);
  1569. }
  1570. // TODO: Convert this to an EvalConstantInst instruction. This will require
  1571. // providing a `GetConstantValue` overload for a requirement block.
  1572. template <>
  1573. auto TryEvalTypedInst<SemIR::WhereExpr>(EvalContext& eval_context,
  1574. SemIR::InstId /*inst_id*/,
  1575. SemIR::Inst inst) -> SemIR::ConstantId {
  1576. auto typed_inst = inst.As<SemIR::WhereExpr>();
  1577. Phase phase = Phase::Concrete;
  1578. SemIR::TypeId base_facet_type_id =
  1579. eval_context.insts().Get(typed_inst.period_self_id).type_id();
  1580. SemIR::Inst base_facet_inst =
  1581. eval_context.GetConstantValueAsInst(base_facet_type_id);
  1582. SemIR::FacetTypeInfo info = {.other_requirements = false};
  1583. // `where` provides that the base facet is an error, `type`, or a facet
  1584. // type.
  1585. if (auto facet_type = base_facet_inst.TryAs<SemIR::FacetType>()) {
  1586. info = GetConstantFacetTypeInfo(eval_context, facet_type->facet_type_id,
  1587. &phase);
  1588. } else if (base_facet_type_id == SemIR::ErrorInst::SingletonTypeId) {
  1589. return SemIR::ErrorInst::SingletonConstantId;
  1590. } else {
  1591. CARBON_CHECK(base_facet_type_id == SemIR::TypeType::SingletonTypeId,
  1592. "Unexpected type_id: {0}, inst: {1}", base_facet_type_id,
  1593. base_facet_inst);
  1594. }
  1595. if (typed_inst.requirements_id.has_value()) {
  1596. auto insts = eval_context.inst_blocks().Get(typed_inst.requirements_id);
  1597. for (auto inst_id : insts) {
  1598. if (auto rewrite =
  1599. eval_context.insts().TryGetAs<SemIR::RequirementRewrite>(
  1600. inst_id)) {
  1601. SemIR::ConstantId lhs = eval_context.GetConstantValue(rewrite->lhs_id);
  1602. SemIR::ConstantId rhs = eval_context.GetConstantValue(rewrite->rhs_id);
  1603. // `where` requirements using `.Self` should not be considered
  1604. // symbolic
  1605. UpdatePhaseIgnorePeriodSelf(eval_context, lhs, &phase);
  1606. UpdatePhaseIgnorePeriodSelf(eval_context, rhs, &phase);
  1607. info.rewrite_constraints.push_back(
  1608. {.lhs_const_id = lhs, .rhs_const_id = rhs});
  1609. } else {
  1610. // TODO: Handle other requirements
  1611. info.other_requirements = true;
  1612. }
  1613. }
  1614. }
  1615. info.Canonicalize();
  1616. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1617. }
  1618. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1619. static auto TryEvalInstInContext(EvalContext& eval_context,
  1620. SemIR::InstId inst_id, SemIR::Inst inst)
  1621. -> SemIR::ConstantId {
  1622. using EvalInstFn =
  1623. auto(EvalContext & eval_context, SemIR::InstId inst_id, SemIR::Inst inst)
  1624. ->SemIR::ConstantId;
  1625. static constexpr EvalInstFn* EvalInstFns[] = {
  1626. #define CARBON_SEM_IR_INST_KIND(Kind) &TryEvalTypedInst<SemIR::Kind>,
  1627. #include "toolchain/sem_ir/inst_kind.def"
  1628. };
  1629. [[clang::musttail]] return EvalInstFns[inst.kind().AsInt()](eval_context,
  1630. inst_id, inst);
  1631. }
  1632. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  1633. -> SemIR::ConstantId {
  1634. EvalContext eval_context(context, inst_id);
  1635. return TryEvalInstInContext(eval_context, inst_id, inst);
  1636. }
  1637. auto TryEvalBlockForSpecific(Context& context, SemIRLoc loc,
  1638. SemIR::SpecificId specific_id,
  1639. SemIR::GenericInstIndex::Region region)
  1640. -> SemIR::InstBlockId {
  1641. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1642. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1643. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1644. llvm::SmallVector<SemIR::InstId> result;
  1645. result.resize(eval_block.size(), SemIR::InstId::None);
  1646. EvalContext eval_context(context, loc, specific_id,
  1647. SpecificEvalInfo{
  1648. .region = region,
  1649. .values = result,
  1650. });
  1651. DiagnosticAnnotationScope annotate_diagnostics(
  1652. &context.emitter(), [&](auto& builder) {
  1653. CARBON_DIAGNOSTIC(ResolvingSpecificHere, Note, "in {0} used here",
  1654. InstIdAsType);
  1655. builder.Note(loc, ResolvingSpecificHere,
  1656. GetInstForSpecific(context, specific_id));
  1657. });
  1658. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1659. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1660. context.insts().Get(inst_id));
  1661. result[i] = context.constant_values().GetInstId(const_id);
  1662. CARBON_CHECK(result[i].has_value());
  1663. }
  1664. return context.inst_blocks().Add(result);
  1665. }
  1666. } // namespace Carbon::Check