eval.cpp 83 KB

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