eval.cpp 77 KB

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