eval.cpp 81 KB

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