eval.cpp 86 KB

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