eval.cpp 91 KB

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