eval.cpp 92 KB

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