eval.cpp 82 KB

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