eval.cpp 83 KB

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