eval.cpp 88 KB

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