eval.cpp 74 KB

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