eval.cpp 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148
  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.
  575. info.rewrite_constraints = orig.rewrite_constraints;
  576. if (!ResolveFacetTypeRewriteConstraints(eval_context.context(), loc_id,
  577. info.rewrite_constraints)) {
  578. *phase = Phase::UnknownDueToError;
  579. }
  580. for (auto& rewrite : info.rewrite_constraints) {
  581. // `where` requirements using `.Self` should not be considered symbolic.
  582. auto lhs_id = RequireConstantValueIgnoringPeriodSelf(eval_context,
  583. rewrite.lhs_id, phase);
  584. auto rhs_id = RequireConstantValueIgnoringPeriodSelf(eval_context,
  585. rewrite.rhs_id, phase);
  586. rewrite = {.lhs_id = lhs_id, .rhs_id = rhs_id};
  587. }
  588. // TODO: Process other requirements.
  589. info.other_requirements = orig.other_requirements;
  590. info.Canonicalize();
  591. return info;
  592. }
  593. static auto GetConstantValue(EvalContext& eval_context,
  594. SemIR::FacetTypeId facet_type_id, Phase* phase)
  595. -> SemIR::FacetTypeId {
  596. SemIR::FacetTypeInfo info = GetConstantFacetTypeInfo(
  597. eval_context, SemIR::LocId::None,
  598. eval_context.facet_types().Get(facet_type_id), phase);
  599. // TODO: Return `facet_type_id` if we can detect nothing has changed.
  600. return eval_context.facet_types().Add(info);
  601. }
  602. static auto GetConstantValue(EvalContext& eval_context,
  603. SemIR::EntityNameId entity_name_id, Phase* phase)
  604. -> SemIR::EntityNameId {
  605. const auto& bind_name = eval_context.entity_names().Get(entity_name_id);
  606. Phase name_phase;
  607. if (bind_name.name_id == SemIR::NameId::PeriodSelf) {
  608. name_phase = Phase::PeriodSelfSymbolic;
  609. } else if (!bind_name.bind_index().has_value()) {
  610. name_phase = Phase::Concrete;
  611. } else if (bind_name.is_template) {
  612. name_phase = Phase::TemplateSymbolic;
  613. } else {
  614. name_phase = Phase::CheckedSymbolic;
  615. }
  616. *phase = LatestPhase(*phase, name_phase);
  617. return eval_context.entity_names().MakeCanonical(entity_name_id);
  618. }
  619. // Replaces the specified field of the given typed instruction with its constant
  620. // value, if it has constant phase. Returns true on success, false if the value
  621. // has runtime phase.
  622. template <typename InstT, typename FieldIdT>
  623. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  624. InstT* inst, FieldIdT InstT::* field,
  625. Phase* phase) -> bool {
  626. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  627. if (!unwrapped.has_value() && (inst->*field).has_value()) {
  628. return false;
  629. }
  630. inst->*field = unwrapped;
  631. return IsConstantOrError(*phase);
  632. }
  633. // Function template that can be called with an argument of type `T`. Used below
  634. // to detect which overloads of `GetConstantValue` exist.
  635. template <typename T>
  636. static void Accept(T /*arg*/) {}
  637. // Determines whether a `GetConstantValue` overload exists for a given ID type.
  638. // Note that we do not check whether `GetConstantValue` is *callable* with a
  639. // given ID type, because that would use the `InstId` overload for
  640. // `AbsoluteInstId` and similar wrapper types, which should be left alone.
  641. template <typename IdT>
  642. static constexpr bool HasGetConstantValueOverload = requires {
  643. Accept<auto (*)(EvalContext&, IdT, Phase*)->IdT>(GetConstantValue);
  644. };
  645. using ArgHandlerFnT = auto(EvalContext& context, int32_t arg, Phase* phase)
  646. -> int32_t;
  647. // Returns the arg handler for an `IdKind`.
  648. template <typename... Types>
  649. static auto GetArgHandlerFn(TypeEnum<Types...> id_kind) -> ArgHandlerFnT* {
  650. static constexpr std::array<ArgHandlerFnT*, SemIR::IdKind::NumValues> Table =
  651. {
  652. [](EvalContext& eval_context, int32_t arg, Phase* phase) -> int32_t {
  653. auto id = SemIR::Inst::FromRaw<Types>(arg);
  654. if constexpr (HasGetConstantValueOverload<Types>) {
  655. // If we have a custom `GetConstantValue` overload, call it.
  656. return SemIR::Inst::ToRaw(
  657. GetConstantValue(eval_context, id, phase));
  658. } else {
  659. // Otherwise, we assume the value is already constant.
  660. return arg;
  661. }
  662. }...,
  663. // Invalid and None handling (ordering-sensitive).
  664. [](auto...) -> int32_t { CARBON_FATAL("Unexpected invalid IdKind"); },
  665. [](EvalContext& /*context*/, int32_t arg,
  666. Phase* /*phase*/) -> int32_t { return arg; },
  667. };
  668. return Table[id_kind.ToIndex()];
  669. }
  670. // Given the stored value `arg` of an instruction field and its corresponding
  671. // kind `kind`, returns the constant value to use for that field, if it has a
  672. // constant phase. `*phase` is updated to include the new constant value. If
  673. // the resulting phase is not constant, the returned value is not useful and
  674. // will typically be `NoneIndex`.
  675. static auto GetConstantValueForArg(EvalContext& eval_context,
  676. SemIR::Inst::ArgAndKind arg_and_kind,
  677. Phase* phase) -> int32_t {
  678. return GetArgHandlerFn(arg_and_kind.kind())(eval_context,
  679. arg_and_kind.value(), phase);
  680. }
  681. // Given an instruction, replaces its operands with their constant values from
  682. // the specified evaluation context. `*phase` is updated to describe the
  683. // constant phase of the result. Returns whether `*phase` is a constant phase;
  684. // if not, `inst` may not be fully updated and should not be used.
  685. static auto ReplaceAllFieldsWithConstantValues(EvalContext& eval_context,
  686. SemIR::Inst* inst, Phase* phase)
  687. -> bool {
  688. auto arg0 =
  689. GetConstantValueForArg(eval_context, inst->arg0_and_kind(), phase);
  690. if (!IsConstantOrError(*phase)) {
  691. return false;
  692. }
  693. auto arg1 =
  694. GetConstantValueForArg(eval_context, inst->arg1_and_kind(), phase);
  695. if (!IsConstantOrError(*phase)) {
  696. return false;
  697. }
  698. inst->SetArgs(arg0, arg1);
  699. return true;
  700. }
  701. // Given an instruction and its ID, replaces its type with the corresponding
  702. // value in this evaluation context. Updates `*phase` to describe the phase of
  703. // the result, and returns whether `*phase` is a constant phase.
  704. static auto ReplaceTypeWithConstantValue(EvalContext& eval_context,
  705. SemIR::InstId inst_id,
  706. SemIR::Inst* inst, Phase* phase)
  707. -> bool {
  708. inst->SetType(GetTypeOfInst(eval_context, inst_id, *inst, phase));
  709. return IsConstantOrError(*phase);
  710. }
  711. template <typename InstT>
  712. static auto ReplaceTypeWithConstantValue(EvalContext& eval_context,
  713. SemIR::InstId inst_id, InstT* inst,
  714. Phase* phase) -> bool {
  715. inst->type_id = GetTypeOfInst(eval_context, inst_id, *inst, phase);
  716. return IsConstantOrError(*phase);
  717. }
  718. template <typename... Types>
  719. static auto KindHasGetConstantValueOverload(TypeEnum<Types...> e) -> bool {
  720. static constexpr std::array<bool, SemIR::IdKind::NumTypes> Values = {
  721. (HasGetConstantValueOverload<Types>)...};
  722. return Values[e.ToIndex()];
  723. }
  724. static auto ResolveSpecificDeclForSpecificId(EvalContext& eval_context,
  725. SemIR::SpecificId specific_id)
  726. -> void {
  727. if (!specific_id.has_value()) {
  728. return;
  729. }
  730. const auto& specific = eval_context.specifics().Get(specific_id);
  731. const auto& generic = eval_context.generics().Get(specific.generic_id);
  732. if (specific_id == generic.self_specific_id) {
  733. // Impl witness table construction happens before its generic decl is
  734. // finish, in order to make the table's instructions dependent
  735. // instructions of the Impl's generic. But those instructions can refer to
  736. // the generic's self specific. We can not resolve the specific
  737. // declaration for the self specific until the generic is finished, but it
  738. // is explicitly resolved at that time in `FinishGenericDecl()`.
  739. return;
  740. }
  741. ResolveSpecificDecl(eval_context.context(), eval_context.fallback_loc_id(),
  742. specific_id);
  743. }
  744. // Resolves the specific declarations for a specific id in any field of the
  745. // `inst` instruction.
  746. static auto ResolveSpecificDeclForInst(EvalContext& eval_context,
  747. const SemIR::Inst& inst) -> void {
  748. for (auto arg_and_kind : {inst.arg0_and_kind(), inst.arg1_and_kind()}) {
  749. // This switch must handle any field type that has a GetConstantValue()
  750. // overload which canonicalizes a specific (and thus potentially forms a new
  751. // specific) as part of forming its constant value.
  752. CARBON_KIND_SWITCH(arg_and_kind) {
  753. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  754. const auto& info =
  755. eval_context.context().facet_types().Get(facet_type_id);
  756. for (const auto& interface : info.extend_constraints) {
  757. ResolveSpecificDeclForSpecificId(eval_context, interface.specific_id);
  758. }
  759. for (const auto& interface : info.self_impls_constraints) {
  760. ResolveSpecificDeclForSpecificId(eval_context, interface.specific_id);
  761. }
  762. break;
  763. }
  764. case CARBON_KIND(SemIR::SpecificId specific_id): {
  765. ResolveSpecificDeclForSpecificId(eval_context, specific_id);
  766. break;
  767. }
  768. case CARBON_KIND(SemIR::SpecificInterfaceId specific_interface_id): {
  769. ResolveSpecificDeclForSpecificId(eval_context,
  770. eval_context.specific_interfaces()
  771. .Get(specific_interface_id)
  772. .specific_id);
  773. break;
  774. }
  775. // These id types have a GetConstantValue() overload but that overload
  776. // does not canonicalize any SpecificId in the value type.
  777. case SemIR::IdKind::For<SemIR::DestInstId>:
  778. case SemIR::IdKind::For<SemIR::EntityNameId>:
  779. case SemIR::IdKind::For<SemIR::InstBlockId>:
  780. case SemIR::IdKind::For<SemIR::InstId>:
  781. case SemIR::IdKind::For<SemIR::MetaInstId>:
  782. case SemIR::IdKind::For<SemIR::StructTypeFieldsId>:
  783. case SemIR::IdKind::For<SemIR::TypeInstId>:
  784. break;
  785. case SemIR::IdKind::None:
  786. // No arg.
  787. break;
  788. default:
  789. CARBON_CHECK(
  790. !KindHasGetConstantValueOverload(arg_and_kind.kind()),
  791. "Missing case for {0} which has a GetConstantValue() overload",
  792. arg_and_kind.kind());
  793. break;
  794. }
  795. }
  796. }
  797. auto AddImportedConstant(Context& context, SemIR::Inst inst)
  798. -> SemIR::ConstantId {
  799. EvalContext eval_context(&context, SemIR::LocId::None);
  800. CARBON_CHECK(inst.kind().has_type(), "Can't import untyped instructions: {0}",
  801. inst.kind());
  802. Phase phase = GetPhase(context.constant_values(),
  803. context.types().GetConstantId(inst.type_id()));
  804. // We ignore the return value of ReplaceAllFieldsWithConstantValues and just
  805. // propagate runtime and error constant values into the resulting ConstantId.
  806. ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase);
  807. return MakeConstantResult(context, inst, phase);
  808. }
  809. // Performs an index into a homogeneous aggregate, retrieving the specified
  810. // element.
  811. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  812. -> SemIR::ConstantId {
  813. Phase phase = Phase::Concrete;
  814. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  815. if (!index_id.has_value()) {
  816. return MakeNonConstantResult(phase);
  817. }
  818. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  819. if (!index) {
  820. CARBON_CHECK(phase != Phase::Concrete,
  821. "Concrete constant integer should be a literal");
  822. return MakeNonConstantResult(phase);
  823. }
  824. // Array indexing is invalid if the index is constant and out of range,
  825. // regardless of whether the array itself is constant.
  826. const auto& index_val = eval_context.ints().Get(index->int_id);
  827. auto aggregate_type_id = eval_context.GetTypeOfInst(inst.array_id);
  828. if (auto array_type =
  829. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  830. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  831. array_type->bound_id)) {
  832. // This awkward call to `getZExtValue` is a workaround for APInt not
  833. // supporting comparisons between integers of different bit widths.
  834. if (index_val.getActiveBits() > 64 ||
  835. eval_context.ints()
  836. .Get(bound->int_id)
  837. .ule(index_val.getZExtValue())) {
  838. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  839. "array index `{0}` is past the end of type {1}",
  840. TypedInt, SemIR::TypeId);
  841. eval_context.emitter().Emit(
  842. eval_context.GetDiagnosticLoc(inst.index_id), ArrayIndexOutOfBounds,
  843. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  844. return SemIR::ErrorInst::ConstantId;
  845. }
  846. }
  847. }
  848. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  849. if (!aggregate_id.has_value()) {
  850. return MakeNonConstantResult(phase);
  851. }
  852. auto aggregate =
  853. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  854. if (!aggregate) {
  855. // TODO: Consider forming a symbolic constant or reference constant array
  856. // index in this case.
  857. return MakeNonConstantResult(phase);
  858. }
  859. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  860. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  861. }
  862. // Forms a constant int type as an evaluation result. Requires that width_id is
  863. // constant.
  864. static auto MakeIntTypeResult(Context& context, SemIR::LocId loc_id,
  865. SemIR::IntKind int_kind, SemIR::InstId width_id,
  866. Phase phase) -> SemIR::ConstantId {
  867. auto result = SemIR::IntType{
  868. .type_id = GetSingletonType(context, SemIR::TypeType::TypeInstId),
  869. .int_kind = int_kind,
  870. .bit_width_id = width_id};
  871. if (!ValidateIntType(context, loc_id, result)) {
  872. return SemIR::ErrorInst::ConstantId;
  873. }
  874. return MakeConstantResult(context, result, phase);
  875. }
  876. // Performs a conversion between integer types, truncating if the value doesn't
  877. // fit in the destination type.
  878. static auto PerformIntConvert(Context& context, SemIR::InstId arg_id,
  879. SemIR::TypeId dest_type_id) -> SemIR::ConstantId {
  880. auto arg_val =
  881. context.ints().Get(context.insts().GetAs<SemIR::IntValue>(arg_id).int_id);
  882. auto [dest_is_signed, bit_width_id] =
  883. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  884. if (bit_width_id.has_value()) {
  885. // TODO: If the value fits in the destination type, reuse the existing
  886. // int_id rather than recomputing it. This is probably the most common case.
  887. bool src_is_signed = context.sem_ir().types().IsSignedInt(
  888. context.insts().Get(arg_id).type_id());
  889. unsigned width = context.ints().Get(bit_width_id).getZExtValue();
  890. arg_val =
  891. src_is_signed ? arg_val.sextOrTrunc(width) : arg_val.zextOrTrunc(width);
  892. }
  893. return MakeIntResult(context, dest_type_id, dest_is_signed, arg_val);
  894. }
  895. // Performs a conversion between integer types, diagnosing if the value doesn't
  896. // fit in the destination type.
  897. static auto PerformCheckedIntConvert(Context& context, SemIR::LocId loc_id,
  898. SemIR::InstId arg_id,
  899. SemIR::TypeId dest_type_id)
  900. -> SemIR::ConstantId {
  901. auto arg = context.insts().GetAs<SemIR::IntValue>(arg_id);
  902. auto arg_val = context.ints().Get(arg.int_id);
  903. auto [is_signed, bit_width_id] =
  904. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  905. auto width = bit_width_id.has_value()
  906. ? context.ints().Get(bit_width_id).getZExtValue()
  907. : arg_val.getBitWidth();
  908. if (!is_signed && arg_val.isNegative()) {
  909. CARBON_DIAGNOSTIC(
  910. NegativeIntInUnsignedType, Error,
  911. "negative integer value {0} converted to unsigned type {1}", TypedInt,
  912. SemIR::TypeId);
  913. context.emitter().Emit(loc_id, NegativeIntInUnsignedType,
  914. {.type = arg.type_id, .value = arg_val},
  915. dest_type_id);
  916. }
  917. unsigned arg_non_sign_bits = arg_val.getSignificantBits() - 1;
  918. if (arg_non_sign_bits + is_signed > width) {
  919. CARBON_DIAGNOSTIC(IntTooLargeForType, Error,
  920. "integer value {0} too large for type {1}", TypedInt,
  921. SemIR::TypeId);
  922. context.emitter().Emit(loc_id, IntTooLargeForType,
  923. {.type = arg.type_id, .value = arg_val},
  924. dest_type_id);
  925. }
  926. return MakeConstantResult(
  927. context, SemIR::IntValue{.type_id = dest_type_id, .int_id = arg.int_id},
  928. Phase::Concrete);
  929. }
  930. // Issues a diagnostic for a compile-time division by zero.
  931. static auto DiagnoseDivisionByZero(Context& context, SemIR::LocId loc_id)
  932. -> void {
  933. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  934. context.emitter().Emit(loc_id, CompileTimeDivisionByZero);
  935. }
  936. // Get an integer at a suitable bit-width: either `bit_width_id` if it has a
  937. // value, or the canonical width from the value store if not.
  938. static auto GetIntAtSuitableWidth(Context& context, IntId int_id,
  939. IntId bit_width_id) -> llvm::APInt {
  940. return bit_width_id.has_value()
  941. ? context.ints().GetAtWidth(int_id, bit_width_id)
  942. : context.ints().Get(int_id);
  943. }
  944. // Performs a builtin unary integer -> integer operation.
  945. static auto PerformBuiltinUnaryIntOp(Context& context, SemIR::LocId loc_id,
  946. SemIR::BuiltinFunctionKind builtin_kind,
  947. SemIR::InstId arg_id)
  948. -> SemIR::ConstantId {
  949. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  950. auto [is_signed, bit_width_id] =
  951. context.sem_ir().types().GetIntTypeInfo(op.type_id);
  952. llvm::APInt op_val = GetIntAtSuitableWidth(context, op.int_id, bit_width_id);
  953. switch (builtin_kind) {
  954. case SemIR::BuiltinFunctionKind::IntSNegate:
  955. if (op_val.isMinSignedValue()) {
  956. if (bit_width_id.has_value()) {
  957. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  958. "integer overflow in negation of {0}", TypedInt);
  959. context.emitter().Emit(loc_id, CompileTimeIntegerNegateOverflow,
  960. {.type = op.type_id, .value = op_val});
  961. } else {
  962. // Widen the integer so we don't overflow into the sign bit.
  963. op_val = op_val.sext(op_val.getBitWidth() +
  964. llvm::APInt::APINT_BITS_PER_WORD);
  965. }
  966. }
  967. op_val.negate();
  968. break;
  969. case SemIR::BuiltinFunctionKind::IntUNegate:
  970. CARBON_CHECK(bit_width_id.has_value(), "Unsigned negate on unsized int");
  971. op_val.negate();
  972. break;
  973. case SemIR::BuiltinFunctionKind::IntComplement:
  974. // TODO: Should we have separate builtins for signed and unsigned
  975. // complement? Like with signed/unsigned negate, these operations do
  976. // different things to the integer value, even though they do the same
  977. // thing to the bits. We treat IntLiteral complement as signed complement,
  978. // given that the result of unsigned complement depends on the bit width.
  979. op_val.flipAllBits();
  980. break;
  981. default:
  982. CARBON_FATAL("Unexpected builtin kind");
  983. }
  984. return MakeIntResult(context, op.type_id, is_signed, std::move(op_val));
  985. }
  986. namespace {
  987. // A pair of APInts that are the operands of a binary operator. We use an
  988. // aggregate rather than `std::pair` to allow RVO of the individual ints.
  989. struct APIntBinaryOperands {
  990. llvm::APInt lhs;
  991. llvm::APInt rhs;
  992. };
  993. } // namespace
  994. // Get a pair of integers at the same suitable bit-width: either their actual
  995. // width if they have a fixed width, or the smallest canonical width in which
  996. // they both fit otherwise.
  997. static auto GetIntsAtSuitableWidth(Context& context, IntId lhs_id, IntId rhs_id,
  998. IntId bit_width_id) -> APIntBinaryOperands {
  999. // Unsized operands: take the wider of the bit widths.
  1000. if (!bit_width_id.has_value()) {
  1001. APIntBinaryOperands result = {.lhs = context.ints().Get(lhs_id),
  1002. .rhs = context.ints().Get(rhs_id)};
  1003. if (result.lhs.getBitWidth() != result.rhs.getBitWidth()) {
  1004. if (result.lhs.getBitWidth() > result.rhs.getBitWidth()) {
  1005. result.rhs = result.rhs.sext(result.lhs.getBitWidth());
  1006. } else {
  1007. result.lhs = result.lhs.sext(result.rhs.getBitWidth());
  1008. }
  1009. }
  1010. return result;
  1011. }
  1012. return {.lhs = context.ints().GetAtWidth(lhs_id, bit_width_id),
  1013. .rhs = context.ints().GetAtWidth(rhs_id, bit_width_id)};
  1014. }
  1015. namespace {
  1016. // The result of performing a binary int operation.
  1017. struct BinaryIntOpResult {
  1018. llvm::APInt result_val;
  1019. bool overflow;
  1020. Lex::TokenKind op_token;
  1021. };
  1022. } // namespace
  1023. // Computes the result of a homogeneous binary (int, int) -> int operation.
  1024. static auto ComputeBinaryIntOpResult(SemIR::BuiltinFunctionKind builtin_kind,
  1025. const llvm::APInt& lhs_val,
  1026. const llvm::APInt& rhs_val)
  1027. -> BinaryIntOpResult {
  1028. llvm::APInt result_val;
  1029. bool overflow = false;
  1030. Lex::TokenKind op_token = Lex::TokenKind::Not;
  1031. switch (builtin_kind) {
  1032. // Arithmetic.
  1033. case SemIR::BuiltinFunctionKind::IntSAdd:
  1034. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  1035. op_token = Lex::TokenKind::Plus;
  1036. break;
  1037. case SemIR::BuiltinFunctionKind::IntSSub:
  1038. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  1039. op_token = Lex::TokenKind::Minus;
  1040. break;
  1041. case SemIR::BuiltinFunctionKind::IntSMul:
  1042. result_val = lhs_val.smul_ov(rhs_val, overflow);
  1043. op_token = Lex::TokenKind::Star;
  1044. break;
  1045. case SemIR::BuiltinFunctionKind::IntSDiv:
  1046. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  1047. op_token = Lex::TokenKind::Slash;
  1048. break;
  1049. case SemIR::BuiltinFunctionKind::IntSMod:
  1050. result_val = lhs_val.srem(rhs_val);
  1051. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  1052. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  1053. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  1054. op_token = Lex::TokenKind::Percent;
  1055. break;
  1056. case SemIR::BuiltinFunctionKind::IntUAdd:
  1057. result_val = lhs_val + rhs_val;
  1058. op_token = Lex::TokenKind::Plus;
  1059. break;
  1060. case SemIR::BuiltinFunctionKind::IntUSub:
  1061. result_val = lhs_val - rhs_val;
  1062. op_token = Lex::TokenKind::Minus;
  1063. break;
  1064. case SemIR::BuiltinFunctionKind::IntUMul:
  1065. result_val = lhs_val * rhs_val;
  1066. op_token = Lex::TokenKind::Star;
  1067. break;
  1068. case SemIR::BuiltinFunctionKind::IntUDiv:
  1069. result_val = lhs_val.udiv(rhs_val);
  1070. op_token = Lex::TokenKind::Slash;
  1071. break;
  1072. case SemIR::BuiltinFunctionKind::IntUMod:
  1073. result_val = lhs_val.urem(rhs_val);
  1074. op_token = Lex::TokenKind::Percent;
  1075. break;
  1076. // Bitwise.
  1077. case SemIR::BuiltinFunctionKind::IntAnd:
  1078. result_val = lhs_val & rhs_val;
  1079. op_token = Lex::TokenKind::And;
  1080. break;
  1081. case SemIR::BuiltinFunctionKind::IntOr:
  1082. result_val = lhs_val | rhs_val;
  1083. op_token = Lex::TokenKind::Pipe;
  1084. break;
  1085. case SemIR::BuiltinFunctionKind::IntXor:
  1086. result_val = lhs_val ^ rhs_val;
  1087. op_token = Lex::TokenKind::Caret;
  1088. break;
  1089. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1090. case SemIR::BuiltinFunctionKind::IntRightShift:
  1091. CARBON_FATAL("Non-homogeneous operation handled separately.");
  1092. default:
  1093. CARBON_FATAL("Unexpected operation kind.");
  1094. }
  1095. return {.result_val = std::move(result_val),
  1096. .overflow = overflow,
  1097. .op_token = op_token};
  1098. }
  1099. // Performs a builtin integer bit shift operation.
  1100. static auto PerformBuiltinIntShiftOp(Context& context, SemIR::LocId loc_id,
  1101. SemIR::BuiltinFunctionKind builtin_kind,
  1102. SemIR::InstId lhs_id, SemIR::InstId rhs_id)
  1103. -> SemIR::ConstantId {
  1104. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1105. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1106. auto [lhs_is_signed, lhs_bit_width_id] =
  1107. context.sem_ir().types().GetIntTypeInfo(lhs.type_id);
  1108. llvm::APInt lhs_val =
  1109. GetIntAtSuitableWidth(context, lhs.int_id, lhs_bit_width_id);
  1110. const auto& rhs_orig_val = context.ints().Get(rhs.int_id);
  1111. if (lhs_bit_width_id.has_value() && rhs_orig_val.uge(lhs_val.getBitWidth())) {
  1112. CARBON_DIAGNOSTIC(
  1113. CompileTimeShiftOutOfRange, Error,
  1114. "shift distance >= type width of {0} in `{1} {2:<<|>>} {3}`", unsigned,
  1115. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1116. context.emitter().Emit(
  1117. loc_id, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  1118. {.type = lhs.type_id, .value = lhs_val},
  1119. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1120. {.type = rhs.type_id, .value = rhs_orig_val});
  1121. // TODO: Is it useful to recover by returning 0 or -1?
  1122. return SemIR::ErrorInst::ConstantId;
  1123. }
  1124. if (rhs_orig_val.isNegative() &&
  1125. context.sem_ir().types().IsSignedInt(rhs.type_id)) {
  1126. CARBON_DIAGNOSTIC(CompileTimeShiftNegative, Error,
  1127. "shift distance negative in `{0} {1:<<|>>} {2}`",
  1128. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1129. context.emitter().Emit(
  1130. loc_id, CompileTimeShiftNegative,
  1131. {.type = lhs.type_id, .value = lhs_val},
  1132. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1133. {.type = rhs.type_id, .value = rhs_orig_val});
  1134. // TODO: Is it useful to recover by returning 0 or -1?
  1135. return SemIR::ErrorInst::ConstantId;
  1136. }
  1137. llvm::APInt result_val;
  1138. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  1139. if (!lhs_bit_width_id.has_value() && !lhs_val.isZero()) {
  1140. // Ensure we don't generate a ridiculously large integer through a bit
  1141. // shift.
  1142. auto width = rhs_orig_val.trySExtValue();
  1143. if (!width ||
  1144. *width > IntStore::MaxIntWidth - lhs_val.getSignificantBits()) {
  1145. CARBON_DIAGNOSTIC(CompileTimeUnsizedShiftOutOfRange, Error,
  1146. "shift distance of {0} would result in an "
  1147. "integer whose width is greater than the "
  1148. "maximum supported width of {1}",
  1149. TypedInt, int);
  1150. context.emitter().Emit(loc_id, CompileTimeUnsizedShiftOutOfRange,
  1151. {.type = rhs.type_id, .value = rhs_orig_val},
  1152. IntStore::MaxIntWidth);
  1153. return SemIR::ErrorInst::ConstantId;
  1154. }
  1155. lhs_val = lhs_val.sext(
  1156. IntStore::CanonicalBitWidth(lhs_val.getSignificantBits() + *width));
  1157. }
  1158. result_val =
  1159. lhs_val.shl(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1160. } else if (lhs_is_signed) {
  1161. result_val =
  1162. lhs_val.ashr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1163. } else {
  1164. CARBON_CHECK(lhs_bit_width_id.has_value(), "Logical shift on unsized int");
  1165. result_val =
  1166. lhs_val.lshr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1167. }
  1168. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  1169. std::move(result_val));
  1170. }
  1171. // Performs a homogeneous builtin binary integer -> integer operation.
  1172. static auto PerformBuiltinBinaryIntOp(Context& context, SemIR::LocId loc_id,
  1173. SemIR::BuiltinFunctionKind builtin_kind,
  1174. SemIR::InstId lhs_id,
  1175. SemIR::InstId rhs_id)
  1176. -> SemIR::ConstantId {
  1177. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1178. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1179. CARBON_CHECK(rhs.type_id == lhs.type_id, "Heterogeneous builtin integer op!");
  1180. auto type_id = lhs.type_id;
  1181. auto [is_signed, bit_width_id] =
  1182. context.sem_ir().types().GetIntTypeInfo(type_id);
  1183. auto [lhs_val, rhs_val] =
  1184. GetIntsAtSuitableWidth(context, lhs.int_id, rhs.int_id, bit_width_id);
  1185. // Check for division by zero.
  1186. switch (builtin_kind) {
  1187. case SemIR::BuiltinFunctionKind::IntSDiv:
  1188. case SemIR::BuiltinFunctionKind::IntSMod:
  1189. case SemIR::BuiltinFunctionKind::IntUDiv:
  1190. case SemIR::BuiltinFunctionKind::IntUMod:
  1191. if (rhs_val.isZero()) {
  1192. DiagnoseDivisionByZero(context, loc_id);
  1193. return SemIR::ErrorInst::ConstantId;
  1194. }
  1195. break;
  1196. default:
  1197. break;
  1198. }
  1199. BinaryIntOpResult result =
  1200. ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1201. if (result.overflow && !bit_width_id.has_value()) {
  1202. // Retry with a larger bit width. Most operations can only overflow by one
  1203. // bit, but signed n-bit multiplication can overflow to 2n-1 bits. We don't
  1204. // need to handle unsigned multiplication here because it's not permitted
  1205. // for unsized integers.
  1206. //
  1207. // Note that we speculatively first perform the calculation in the width of
  1208. // the wider operand: smaller operations are faster and overflow to a wider
  1209. // integer is unlikely to be needed, especially given that the width will
  1210. // have been rounded up to a multiple of 64 bits by the int store.
  1211. CARBON_CHECK(builtin_kind != SemIR::BuiltinFunctionKind::IntUMul,
  1212. "Unsigned arithmetic requires a fixed bitwidth");
  1213. int new_width =
  1214. builtin_kind == SemIR::BuiltinFunctionKind::IntSMul
  1215. ? lhs_val.getBitWidth() * 2
  1216. : IntStore::CanonicalBitWidth(lhs_val.getBitWidth() + 1);
  1217. new_width = std::min(new_width, IntStore::MaxIntWidth);
  1218. lhs_val = context.ints().GetAtWidth(lhs.int_id, new_width);
  1219. rhs_val = context.ints().GetAtWidth(rhs.int_id, new_width);
  1220. // Note that this can in theory still overflow if we limited `new_width` to
  1221. // `MaxIntWidth`. In that case we fall through to the signed overflow
  1222. // diagnostic below.
  1223. result = ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1224. CARBON_CHECK(!result.overflow || new_width == IntStore::MaxIntWidth);
  1225. }
  1226. if (result.overflow) {
  1227. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  1228. "integer overflow in calculation `{0} {1} {2}`", TypedInt,
  1229. Lex::TokenKind, TypedInt);
  1230. context.emitter().Emit(loc_id, CompileTimeIntegerOverflow,
  1231. {.type = type_id, .value = lhs_val}, result.op_token,
  1232. {.type = type_id, .value = rhs_val});
  1233. }
  1234. return MakeIntResult(context, type_id, is_signed,
  1235. std::move(result.result_val));
  1236. }
  1237. // Performs a builtin integer comparison.
  1238. static auto PerformBuiltinIntComparison(Context& context,
  1239. SemIR::BuiltinFunctionKind builtin_kind,
  1240. SemIR::InstId lhs_id,
  1241. SemIR::InstId rhs_id,
  1242. SemIR::TypeId bool_type_id)
  1243. -> SemIR::ConstantId {
  1244. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1245. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1246. llvm::APInt lhs_val = context.ints().Get(lhs.int_id);
  1247. llvm::APInt rhs_val = context.ints().Get(rhs.int_id);
  1248. bool result;
  1249. switch (builtin_kind) {
  1250. case SemIR::BuiltinFunctionKind::IntEq:
  1251. result = (lhs_val == rhs_val);
  1252. break;
  1253. case SemIR::BuiltinFunctionKind::IntNeq:
  1254. result = (lhs_val != rhs_val);
  1255. break;
  1256. case SemIR::BuiltinFunctionKind::IntLess:
  1257. result = lhs_val.slt(rhs_val);
  1258. break;
  1259. case SemIR::BuiltinFunctionKind::IntLessEq:
  1260. result = lhs_val.sle(rhs_val);
  1261. break;
  1262. case SemIR::BuiltinFunctionKind::IntGreater:
  1263. result = lhs_val.sgt(rhs_val);
  1264. break;
  1265. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  1266. result = lhs_val.sge(rhs_val);
  1267. break;
  1268. default:
  1269. CARBON_FATAL("Unexpected operation kind.");
  1270. }
  1271. return MakeBoolResult(context, bool_type_id, result);
  1272. }
  1273. // Performs a builtin unary float -> float operation.
  1274. static auto PerformBuiltinUnaryFloatOp(Context& context,
  1275. SemIR::BuiltinFunctionKind builtin_kind,
  1276. SemIR::InstId arg_id)
  1277. -> SemIR::ConstantId {
  1278. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  1279. auto op_val = context.floats().Get(op.float_id);
  1280. switch (builtin_kind) {
  1281. case SemIR::BuiltinFunctionKind::FloatNegate:
  1282. op_val.changeSign();
  1283. break;
  1284. default:
  1285. CARBON_FATAL("Unexpected builtin kind");
  1286. }
  1287. return MakeFloatResult(context, op.type_id, std::move(op_val));
  1288. }
  1289. // Performs a builtin binary float -> float operation.
  1290. static auto PerformBuiltinBinaryFloatOp(Context& context,
  1291. SemIR::BuiltinFunctionKind builtin_kind,
  1292. SemIR::InstId lhs_id,
  1293. SemIR::InstId rhs_id)
  1294. -> SemIR::ConstantId {
  1295. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  1296. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  1297. auto lhs_val = context.floats().Get(lhs.float_id);
  1298. auto rhs_val = context.floats().Get(rhs.float_id);
  1299. llvm::APFloat result_val(lhs_val.getSemantics());
  1300. switch (builtin_kind) {
  1301. case SemIR::BuiltinFunctionKind::FloatAdd:
  1302. result_val = lhs_val + rhs_val;
  1303. break;
  1304. case SemIR::BuiltinFunctionKind::FloatSub:
  1305. result_val = lhs_val - rhs_val;
  1306. break;
  1307. case SemIR::BuiltinFunctionKind::FloatMul:
  1308. result_val = lhs_val * rhs_val;
  1309. break;
  1310. case SemIR::BuiltinFunctionKind::FloatDiv:
  1311. result_val = lhs_val / rhs_val;
  1312. break;
  1313. default:
  1314. CARBON_FATAL("Unexpected operation kind.");
  1315. }
  1316. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  1317. }
  1318. // Performs a builtin float comparison.
  1319. static auto PerformBuiltinFloatComparison(
  1320. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1321. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  1322. -> SemIR::ConstantId {
  1323. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  1324. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  1325. const auto& lhs_val = context.floats().Get(lhs.float_id);
  1326. const auto& rhs_val = context.floats().Get(rhs.float_id);
  1327. bool result;
  1328. switch (builtin_kind) {
  1329. case SemIR::BuiltinFunctionKind::FloatEq:
  1330. result = (lhs_val == rhs_val);
  1331. break;
  1332. case SemIR::BuiltinFunctionKind::FloatNeq:
  1333. result = (lhs_val != rhs_val);
  1334. break;
  1335. case SemIR::BuiltinFunctionKind::FloatLess:
  1336. result = lhs_val < rhs_val;
  1337. break;
  1338. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1339. result = lhs_val <= rhs_val;
  1340. break;
  1341. case SemIR::BuiltinFunctionKind::FloatGreater:
  1342. result = lhs_val > rhs_val;
  1343. break;
  1344. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  1345. result = lhs_val >= rhs_val;
  1346. break;
  1347. default:
  1348. CARBON_FATAL("Unexpected operation kind.");
  1349. }
  1350. return MakeBoolResult(context, bool_type_id, result);
  1351. }
  1352. // Performs a builtin boolean comparison.
  1353. static auto PerformBuiltinBoolComparison(
  1354. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1355. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id) {
  1356. bool lhs = context.insts().GetAs<SemIR::BoolLiteral>(lhs_id).value.ToBool();
  1357. bool rhs = context.insts().GetAs<SemIR::BoolLiteral>(rhs_id).value.ToBool();
  1358. return MakeBoolResult(context, bool_type_id,
  1359. builtin_kind == SemIR::BuiltinFunctionKind::BoolEq
  1360. ? lhs == rhs
  1361. : lhs != rhs);
  1362. }
  1363. // Returns a constant for a call to a builtin function.
  1364. static auto MakeConstantForBuiltinCall(EvalContext& eval_context,
  1365. SemIR::LocId loc_id, SemIR::Call call,
  1366. SemIR::BuiltinFunctionKind builtin_kind,
  1367. llvm::ArrayRef<SemIR::InstId> arg_ids,
  1368. Phase phase) -> SemIR::ConstantId {
  1369. auto& context = eval_context.context();
  1370. switch (builtin_kind) {
  1371. case SemIR::BuiltinFunctionKind::None:
  1372. CARBON_FATAL("Not a builtin function.");
  1373. case SemIR::BuiltinFunctionKind::NoOp: {
  1374. // Return an empty tuple value.
  1375. auto type_id = GetTupleType(eval_context.context(), {});
  1376. return MakeConstantResult(
  1377. eval_context.context(),
  1378. SemIR::TupleValue{.type_id = type_id,
  1379. .elements_id = SemIR::InstBlockId::Empty},
  1380. phase);
  1381. }
  1382. case SemIR::BuiltinFunctionKind::PrintChar:
  1383. case SemIR::BuiltinFunctionKind::PrintInt:
  1384. case SemIR::BuiltinFunctionKind::ReadChar:
  1385. case SemIR::BuiltinFunctionKind::IntSAddAssign:
  1386. case SemIR::BuiltinFunctionKind::IntSSubAssign:
  1387. case SemIR::BuiltinFunctionKind::IntSMulAssign:
  1388. case SemIR::BuiltinFunctionKind::IntSDivAssign:
  1389. case SemIR::BuiltinFunctionKind::IntSModAssign:
  1390. case SemIR::BuiltinFunctionKind::IntUAddAssign:
  1391. case SemIR::BuiltinFunctionKind::IntUSubAssign:
  1392. case SemIR::BuiltinFunctionKind::IntUMulAssign:
  1393. case SemIR::BuiltinFunctionKind::IntUDivAssign:
  1394. case SemIR::BuiltinFunctionKind::IntUModAssign:
  1395. case SemIR::BuiltinFunctionKind::IntAndAssign:
  1396. case SemIR::BuiltinFunctionKind::IntOrAssign:
  1397. case SemIR::BuiltinFunctionKind::IntXorAssign:
  1398. case SemIR::BuiltinFunctionKind::IntLeftShiftAssign:
  1399. case SemIR::BuiltinFunctionKind::IntRightShiftAssign: {
  1400. // These are runtime-only builtins.
  1401. // TODO: Consider tracking this on the `BuiltinFunctionKind`.
  1402. return SemIR::ConstantId::NotConstant;
  1403. }
  1404. case SemIR::BuiltinFunctionKind::TypeAnd: {
  1405. CARBON_CHECK(arg_ids.size() == 2);
  1406. auto lhs_facet_type_id = SemIR::FacetTypeId::None;
  1407. auto rhs_facet_type_id = SemIR::FacetTypeId::None;
  1408. for (auto [facet_type_id, type_arg_id] :
  1409. llvm::zip(std::to_array({&lhs_facet_type_id, &rhs_facet_type_id}),
  1410. context.types().GetBlockAsTypeInstIds(arg_ids))) {
  1411. if (auto facet_type =
  1412. context.insts().TryGetAs<SemIR::FacetType>(type_arg_id)) {
  1413. *facet_type_id = facet_type->facet_type_id;
  1414. } else {
  1415. CARBON_DIAGNOSTIC(FacetTypeRequiredForTypeAndOperator, Error,
  1416. "non-facet type {0} combined with `&` operator",
  1417. SemIR::TypeId);
  1418. // TODO: Find a location for the lhs or rhs specifically, instead of
  1419. // the whole thing. If that's not possible we can change the text to
  1420. // say if it's referring to the left or the right side for the error.
  1421. // The `arg_id` instruction has no location in it for some reason.
  1422. context.emitter().Emit(
  1423. loc_id, FacetTypeRequiredForTypeAndOperator,
  1424. context.types().GetTypeIdForTypeInstId(type_arg_id));
  1425. }
  1426. }
  1427. // Allow errors to be diagnosed for both sides of the operator before
  1428. // returning here if any error occurred on either side.
  1429. if (!lhs_facet_type_id.has_value() || !rhs_facet_type_id.has_value()) {
  1430. return SemIR::ErrorInst::ConstantId;
  1431. }
  1432. // Reuse one of the argument instructions if nothing has changed.
  1433. if (lhs_facet_type_id == rhs_facet_type_id) {
  1434. return context.types().GetConstantId(
  1435. context.types().GetTypeIdForTypeInstId(arg_ids[0]));
  1436. }
  1437. auto combined_info = SemIR::FacetTypeInfo::Combine(
  1438. context.facet_types().Get(lhs_facet_type_id),
  1439. context.facet_types().Get(rhs_facet_type_id));
  1440. if (!ResolveFacetTypeRewriteConstraints(
  1441. eval_context.context(), loc_id,
  1442. combined_info.rewrite_constraints)) {
  1443. phase = Phase::UnknownDueToError;
  1444. }
  1445. combined_info.Canonicalize();
  1446. return MakeFacetTypeResult(eval_context.context(), combined_info, phase);
  1447. }
  1448. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  1449. return context.constant_values().Get(SemIR::IntLiteralType::TypeInstId);
  1450. }
  1451. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  1452. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Signed,
  1453. arg_ids[0], phase);
  1454. }
  1455. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  1456. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Unsigned,
  1457. arg_ids[0], phase);
  1458. }
  1459. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  1460. // TODO: Support a symbolic constant width.
  1461. if (phase != Phase::Concrete) {
  1462. break;
  1463. }
  1464. if (!ValidateFloatBitWidth(context, loc_id, arg_ids[0])) {
  1465. return SemIR::ErrorInst::ConstantId;
  1466. }
  1467. return context.constant_values().Get(SemIR::LegacyFloatType::TypeInstId);
  1468. }
  1469. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  1470. return context.constant_values().Get(SemIR::BoolType::TypeInstId);
  1471. }
  1472. // Integer conversions.
  1473. case SemIR::BuiltinFunctionKind::IntConvert: {
  1474. if (phase != Phase::Concrete) {
  1475. return MakeConstantResult(context, call, phase);
  1476. }
  1477. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1478. }
  1479. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  1480. if (phase != Phase::Concrete) {
  1481. return MakeConstantResult(context, call, phase);
  1482. }
  1483. return PerformCheckedIntConvert(context, loc_id, arg_ids[0],
  1484. call.type_id);
  1485. }
  1486. // Unary integer -> integer operations.
  1487. case SemIR::BuiltinFunctionKind::IntSNegate:
  1488. case SemIR::BuiltinFunctionKind::IntUNegate:
  1489. case SemIR::BuiltinFunctionKind::IntComplement: {
  1490. if (phase != Phase::Concrete) {
  1491. break;
  1492. }
  1493. return PerformBuiltinUnaryIntOp(context, loc_id, builtin_kind,
  1494. arg_ids[0]);
  1495. }
  1496. // Homogeneous binary integer -> integer operations.
  1497. case SemIR::BuiltinFunctionKind::IntSAdd:
  1498. case SemIR::BuiltinFunctionKind::IntSSub:
  1499. case SemIR::BuiltinFunctionKind::IntSMul:
  1500. case SemIR::BuiltinFunctionKind::IntSDiv:
  1501. case SemIR::BuiltinFunctionKind::IntSMod:
  1502. case SemIR::BuiltinFunctionKind::IntUAdd:
  1503. case SemIR::BuiltinFunctionKind::IntUSub:
  1504. case SemIR::BuiltinFunctionKind::IntUMul:
  1505. case SemIR::BuiltinFunctionKind::IntUDiv:
  1506. case SemIR::BuiltinFunctionKind::IntUMod:
  1507. case SemIR::BuiltinFunctionKind::IntAnd:
  1508. case SemIR::BuiltinFunctionKind::IntOr:
  1509. case SemIR::BuiltinFunctionKind::IntXor: {
  1510. if (phase != Phase::Concrete) {
  1511. break;
  1512. }
  1513. return PerformBuiltinBinaryIntOp(context, loc_id, builtin_kind,
  1514. arg_ids[0], arg_ids[1]);
  1515. }
  1516. // Bit shift operations.
  1517. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1518. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1519. if (phase != Phase::Concrete) {
  1520. break;
  1521. }
  1522. return PerformBuiltinIntShiftOp(context, loc_id, builtin_kind, arg_ids[0],
  1523. arg_ids[1]);
  1524. }
  1525. // Integer comparisons.
  1526. case SemIR::BuiltinFunctionKind::IntEq:
  1527. case SemIR::BuiltinFunctionKind::IntNeq:
  1528. case SemIR::BuiltinFunctionKind::IntLess:
  1529. case SemIR::BuiltinFunctionKind::IntLessEq:
  1530. case SemIR::BuiltinFunctionKind::IntGreater:
  1531. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1532. if (phase != Phase::Concrete) {
  1533. break;
  1534. }
  1535. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1536. arg_ids[1], call.type_id);
  1537. }
  1538. // Unary float -> float operations.
  1539. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1540. if (phase != Phase::Concrete) {
  1541. break;
  1542. }
  1543. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1544. }
  1545. // Binary float -> float operations.
  1546. case SemIR::BuiltinFunctionKind::FloatAdd:
  1547. case SemIR::BuiltinFunctionKind::FloatSub:
  1548. case SemIR::BuiltinFunctionKind::FloatMul:
  1549. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1550. if (phase != Phase::Concrete) {
  1551. break;
  1552. }
  1553. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1554. arg_ids[1]);
  1555. }
  1556. // Float comparisons.
  1557. case SemIR::BuiltinFunctionKind::FloatEq:
  1558. case SemIR::BuiltinFunctionKind::FloatNeq:
  1559. case SemIR::BuiltinFunctionKind::FloatLess:
  1560. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1561. case SemIR::BuiltinFunctionKind::FloatGreater:
  1562. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1563. if (phase != Phase::Concrete) {
  1564. break;
  1565. }
  1566. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1567. arg_ids[1], call.type_id);
  1568. }
  1569. // Bool comparisons.
  1570. case SemIR::BuiltinFunctionKind::BoolEq:
  1571. case SemIR::BuiltinFunctionKind::BoolNeq: {
  1572. if (phase != Phase::Concrete) {
  1573. break;
  1574. }
  1575. return PerformBuiltinBoolComparison(context, builtin_kind, arg_ids[0],
  1576. arg_ids[1], call.type_id);
  1577. }
  1578. }
  1579. return SemIR::ConstantId::NotConstant;
  1580. }
  1581. // Makes a constant for a call instruction.
  1582. static auto MakeConstantForCall(EvalContext& eval_context,
  1583. SemIR::InstId inst_id, SemIR::Call call)
  1584. -> SemIR::ConstantId {
  1585. Phase phase = Phase::Concrete;
  1586. // A call with an invalid argument list is used to represent an erroneous
  1587. // call.
  1588. //
  1589. // TODO: Use a better representation for this.
  1590. if (call.args_id == SemIR::InstBlockId::None) {
  1591. return SemIR::ErrorInst::ConstantId;
  1592. }
  1593. // Find the constant value of the callee.
  1594. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1595. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1596. auto callee_function =
  1597. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  1598. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1599. if (callee_function.function_id.has_value()) {
  1600. // Calls to builtins might be constant.
  1601. builtin_kind = eval_context.functions()
  1602. .Get(callee_function.function_id)
  1603. .builtin_function_kind();
  1604. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  1605. // TODO: Eventually we'll want to treat some kinds of non-builtin
  1606. // functions as producing constants.
  1607. return SemIR::ConstantId::NotConstant;
  1608. }
  1609. } else {
  1610. // Calls to non-functions, such as calls to generic entity names, might be
  1611. // constant.
  1612. }
  1613. // Find the argument values and the return type.
  1614. bool has_constant_operands =
  1615. has_constant_callee &&
  1616. ReplaceTypeWithConstantValue(eval_context, inst_id, &call, &phase) &&
  1617. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1618. &phase);
  1619. if (phase == Phase::UnknownDueToError) {
  1620. return SemIR::ErrorInst::ConstantId;
  1621. }
  1622. // If any operand of the call is non-constant, the call is non-constant.
  1623. // TODO: Some builtin calls might allow some operands to be non-constant.
  1624. if (!has_constant_operands) {
  1625. if (builtin_kind.IsCompTimeOnly(
  1626. eval_context.sem_ir(), eval_context.inst_blocks().Get(call.args_id),
  1627. call.type_id)) {
  1628. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1629. "non-constant call to compile-time-only function");
  1630. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1631. "compile-time-only function declared here");
  1632. eval_context.emitter()
  1633. .Build(inst_id, NonConstantCallToCompTimeOnlyFunction)
  1634. .Note(eval_context.functions()
  1635. .Get(callee_function.function_id)
  1636. .latest_decl_id(),
  1637. CompTimeOnlyFunctionHere)
  1638. .Emit();
  1639. }
  1640. return SemIR::ConstantId::NotConstant;
  1641. }
  1642. // Handle calls to builtins.
  1643. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1644. return MakeConstantForBuiltinCall(
  1645. eval_context, SemIR::LocId(inst_id), call, builtin_kind,
  1646. eval_context.inst_blocks().Get(call.args_id), phase);
  1647. }
  1648. return SemIR::ConstantId::NotConstant;
  1649. }
  1650. // Given an instruction, compute its phase based on its operands.
  1651. static auto ComputeInstPhase(Context& context, SemIR::Inst inst) -> Phase {
  1652. EvalContext eval_context(&context, SemIR::LocId::None);
  1653. auto phase = GetPhase(context.constant_values(),
  1654. context.types().GetConstantId(inst.type_id()));
  1655. GetConstantValueForArg(eval_context, inst.arg0_and_kind(), &phase);
  1656. GetConstantValueForArg(eval_context, inst.arg1_and_kind(), &phase);
  1657. CARBON_CHECK(IsConstantOrError(phase));
  1658. return phase;
  1659. }
  1660. // Convert a ConstantEvalResult to a ConstantId. Factored out of
  1661. // TryEvalTypedInst to avoid repeated instantiation of common code.
  1662. static auto ConvertEvalResultToConstantId(Context& context,
  1663. ConstantEvalResult result,
  1664. Phase orig_phase)
  1665. -> SemIR::ConstantId {
  1666. if (result.is_new()) {
  1667. return MakeConstantResult(
  1668. context, result.new_inst(),
  1669. result.same_phase_as_inst()
  1670. ? orig_phase
  1671. : ComputeInstPhase(context, result.new_inst()));
  1672. }
  1673. return result.existing();
  1674. }
  1675. // Evaluates an instruction of a known type in an evaluation context. The
  1676. // default behavior of this function depends on the constant kind of the
  1677. // instruction:
  1678. //
  1679. // - InstConstantKind::Never: returns ConstantId::NotConstant.
  1680. // - InstConstantKind::Indirect, SymbolicOnly, SymbolicOrReference,
  1681. // Conditional: evaluates all the operands of the instruction, and calls
  1682. // `EvalConstantInst` to evaluate the resulting constant instruction.
  1683. // - InstConstantKind::WheneverPossible, Always: evaluates all the operands of
  1684. // the instruction, and produces the resulting constant instruction as the
  1685. // result.
  1686. // - InstConstantKind::Unique: returns the `inst_id` as the resulting
  1687. // constant.
  1688. //
  1689. // Returns an error constant ID if any of the nested evaluations fail, and
  1690. // returns NotConstant if any of the nested evaluations is non-constant.
  1691. //
  1692. // This template is explicitly specialized for instructions that need special
  1693. // handling.
  1694. template <typename InstT>
  1695. static auto TryEvalTypedInst(EvalContext& eval_context, SemIR::InstId inst_id,
  1696. SemIR::Inst inst) -> SemIR::ConstantId {
  1697. constexpr auto ConstantKind = InstT::Kind.constant_kind();
  1698. if constexpr (ConstantKind == SemIR::InstConstantKind::Never) {
  1699. return SemIR::ConstantId::NotConstant;
  1700. } else if constexpr (ConstantKind == SemIR::InstConstantKind::AlwaysUnique) {
  1701. CARBON_CHECK(inst_id.has_value());
  1702. return SemIR::ConstantId::ForConcreteConstant(inst_id);
  1703. } else {
  1704. // Build a constant instruction by replacing each non-constant operand with
  1705. // its constant value.
  1706. Phase phase = Phase::Concrete;
  1707. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &inst, &phase) ||
  1708. !ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  1709. if constexpr (ConstantKind == SemIR::InstConstantKind::Always) {
  1710. CARBON_FATAL("{0} should always be constant", InstT::Kind);
  1711. }
  1712. return SemIR::ConstantId::NotConstant;
  1713. }
  1714. // If any operand of the instruction has an error in it, the instruction
  1715. // itself evaluates to an error.
  1716. if (phase == Phase::UnknownDueToError) {
  1717. return SemIR::ErrorInst::ConstantId;
  1718. }
  1719. // When canonicalizing a SpecificId, we defer resolving the specific's
  1720. // declaration until here, to avoid resolving declarations from imported
  1721. // specifics. (Imported instructions are not evaluated.)
  1722. ResolveSpecificDeclForInst(eval_context, inst);
  1723. if constexpr (ConstantKind == SemIR::InstConstantKind::Always ||
  1724. ConstantKind == SemIR::InstConstantKind::WheneverPossible) {
  1725. return MakeConstantResult(eval_context.context(), inst, phase);
  1726. } else if constexpr (ConstantKind == SemIR::InstConstantKind::InstAction) {
  1727. auto result_inst_id = PerformDelayedAction(
  1728. eval_context.context(), SemIR::LocId(inst_id), inst.As<InstT>());
  1729. if (result_inst_id.has_value()) {
  1730. // The result is an instruction.
  1731. return MakeConstantResult(
  1732. eval_context.context(),
  1733. SemIR::InstValue{.type_id = SemIR::InstType::TypeId,
  1734. .inst_id = result_inst_id},
  1735. Phase::Concrete);
  1736. }
  1737. // Couldn't perform the action because it's still dependent.
  1738. return MakeConstantResult(eval_context.context(), inst,
  1739. Phase::TemplateSymbolic);
  1740. } else if constexpr (InstT::Kind.constant_needs_inst_id() !=
  1741. SemIR::InstConstantNeedsInstIdKind::No) {
  1742. CARBON_CHECK(inst_id.has_value());
  1743. return ConvertEvalResultToConstantId(
  1744. eval_context.context(),
  1745. EvalConstantInst(eval_context.context(), inst_id, inst.As<InstT>()),
  1746. phase);
  1747. } else {
  1748. return ConvertEvalResultToConstantId(
  1749. eval_context.context(),
  1750. EvalConstantInst(eval_context.context(), inst.As<InstT>()), phase);
  1751. }
  1752. }
  1753. }
  1754. // Specialize evaluation for array indexing because we want to check the index
  1755. // expression even if the array expression is non-constant.
  1756. template <>
  1757. auto TryEvalTypedInst<SemIR::ArrayIndex>(EvalContext& eval_context,
  1758. SemIR::InstId /*inst_id*/,
  1759. SemIR::Inst inst)
  1760. -> SemIR::ConstantId {
  1761. return PerformArrayIndex(eval_context, inst.As<SemIR::ArrayIndex>());
  1762. }
  1763. // Specialize evaluation for function calls because we want to check the callee
  1764. // expression even if an argument expression is non-constant, and because we
  1765. // will eventually want to perform control flow handling here.
  1766. template <>
  1767. auto TryEvalTypedInst<SemIR::Call>(EvalContext& eval_context,
  1768. SemIR::InstId inst_id, SemIR::Inst inst)
  1769. -> SemIR::ConstantId {
  1770. return MakeConstantForCall(eval_context, inst_id, inst.As<SemIR::Call>());
  1771. }
  1772. // ImportRefLoaded can have a constant value, but it's owned and maintained by
  1773. // `import_ref.cpp`, not by us.
  1774. // TODO: Rearrange how `ImportRefLoaded` instructions are created so we never
  1775. // call this.
  1776. template <>
  1777. auto TryEvalTypedInst<SemIR::ImportRefLoaded>(EvalContext& /*eval_context*/,
  1778. SemIR::InstId /*inst_id*/,
  1779. SemIR::Inst /*inst*/)
  1780. -> SemIR::ConstantId {
  1781. return SemIR::ConstantId::NotConstant;
  1782. }
  1783. // Symbolic bindings are a special case because they can reach into the eval
  1784. // context and produce a context-specific value.
  1785. template <>
  1786. auto TryEvalTypedInst<SemIR::BindSymbolicName>(EvalContext& eval_context,
  1787. SemIR::InstId inst_id,
  1788. SemIR::Inst inst)
  1789. -> SemIR::ConstantId {
  1790. auto bind = inst.As<SemIR::BindSymbolicName>();
  1791. // If we know which specific we're evaluating within and this is an argument
  1792. // of that specific, its constant value is the corresponding argument value.
  1793. const auto& bind_name = eval_context.entity_names().Get(bind.entity_name_id);
  1794. if (bind_name.bind_index().has_value()) {
  1795. if (auto value =
  1796. eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  1797. value.has_value()) {
  1798. return value;
  1799. }
  1800. }
  1801. // The constant form of a symbolic binding is an idealized form of the
  1802. // original, with no equivalent value.
  1803. Phase phase = Phase::Concrete;
  1804. bind.value_id = SemIR::InstId::None;
  1805. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &bind, &phase) ||
  1806. !ReplaceFieldWithConstantValue(eval_context, &bind,
  1807. &SemIR::BindSymbolicName::entity_name_id,
  1808. &phase)) {
  1809. return SemIR::ConstantId::NotConstant;
  1810. }
  1811. // This correctly handles `Phase::UnknownDueToError`.
  1812. return MakeConstantResult(eval_context.context(), bind, phase);
  1813. }
  1814. // Returns whether `const_id` is the same constant facet value as
  1815. // `facet_value_inst_id`.
  1816. static auto IsSameFacetValue(Context& context, SemIR::ConstantId const_id,
  1817. SemIR::InstId facet_value_inst_id) -> bool {
  1818. if (auto facet_access_type = context.insts().TryGetAs<SemIR::FacetAccessType>(
  1819. context.constant_values().GetInstId(const_id))) {
  1820. const_id =
  1821. context.constant_values().Get(facet_access_type->facet_value_inst_id);
  1822. }
  1823. return const_id == context.constant_values().Get(facet_value_inst_id);
  1824. }
  1825. // TODO: Convert this to an EvalConstantInst function. This will require
  1826. // providing a `GetConstantValue` overload for a requirement block.
  1827. template <>
  1828. auto TryEvalTypedInst<SemIR::WhereExpr>(EvalContext& eval_context,
  1829. SemIR::InstId inst_id, SemIR::Inst inst)
  1830. -> SemIR::ConstantId {
  1831. auto typed_inst = inst.As<SemIR::WhereExpr>();
  1832. Phase phase = Phase::Concrete;
  1833. SemIR::TypeId base_facet_type_id =
  1834. eval_context.GetTypeOfInst(typed_inst.period_self_id);
  1835. SemIR::Inst base_facet_inst =
  1836. eval_context.types().GetAsInst(base_facet_type_id);
  1837. SemIR::FacetTypeInfo info = {.other_requirements = false};
  1838. // `where` provides that the base facet is an error, `type`, or a facet
  1839. // type.
  1840. if (auto facet_type = base_facet_inst.TryAs<SemIR::FacetType>()) {
  1841. info = eval_context.facet_types().Get(facet_type->facet_type_id);
  1842. } else if (base_facet_type_id == SemIR::ErrorInst::TypeId) {
  1843. return SemIR::ErrorInst::ConstantId;
  1844. } else {
  1845. CARBON_CHECK(base_facet_type_id == SemIR::TypeType::TypeId,
  1846. "Unexpected type_id: {0}, inst: {1}", base_facet_type_id,
  1847. base_facet_inst);
  1848. }
  1849. // Add the constraints from the `WhereExpr` instruction into `info`.
  1850. if (typed_inst.requirements_id.has_value()) {
  1851. auto insts = eval_context.inst_blocks().Get(typed_inst.requirements_id);
  1852. for (auto inst_id : insts) {
  1853. if (auto rewrite =
  1854. eval_context.insts().TryGetAs<SemIR::RequirementRewrite>(
  1855. inst_id)) {
  1856. info.rewrite_constraints.push_back(
  1857. {.lhs_id = rewrite->lhs_id, .rhs_id = rewrite->rhs_id});
  1858. } else if (auto impls =
  1859. eval_context.insts().TryGetAs<SemIR::RequirementImpls>(
  1860. inst_id)) {
  1861. SemIR::ConstantId lhs_const_id =
  1862. eval_context.GetConstantValue(impls->lhs_id);
  1863. SemIR::ConstantId rhs_const_id =
  1864. eval_context.GetConstantValue(impls->rhs_id);
  1865. if (IsSameFacetValue(eval_context.context(), lhs_const_id,
  1866. typed_inst.period_self_id)) {
  1867. auto rhs_inst_id =
  1868. eval_context.constant_values().GetInstId(rhs_const_id);
  1869. if (rhs_inst_id == SemIR::ErrorInst::InstId) {
  1870. // `.Self impls <error>`.
  1871. return SemIR::ErrorInst::ConstantId;
  1872. } else if (rhs_inst_id == SemIR::TypeType::TypeInstId) {
  1873. // `.Self impls type` -> nothing to do.
  1874. } else {
  1875. auto facet_type = eval_context.insts().GetAs<SemIR::FacetType>(
  1876. RequireConstantValue(eval_context, impls->rhs_id, &phase));
  1877. const auto& more_info =
  1878. eval_context.facet_types().Get(facet_type.facet_type_id);
  1879. // The way to prevent lookup into the interface requirements of a
  1880. // facet type is to put it to the right of a `.Self impls`, which we
  1881. // accomplish by putting them into `self_impls_constraints`.
  1882. llvm::append_range(info.self_impls_constraints,
  1883. more_info.extend_constraints);
  1884. llvm::append_range(info.self_impls_constraints,
  1885. more_info.self_impls_constraints);
  1886. // Other requirements are copied in.
  1887. llvm::append_range(info.rewrite_constraints,
  1888. more_info.rewrite_constraints);
  1889. info.other_requirements |= more_info.other_requirements;
  1890. }
  1891. } else {
  1892. // TODO: Handle `impls` constraints beyond `.Self impls`.
  1893. info.other_requirements = true;
  1894. }
  1895. } else {
  1896. // TODO: Handle other requirements
  1897. info.other_requirements = true;
  1898. }
  1899. }
  1900. }
  1901. auto const_info = GetConstantFacetTypeInfo(
  1902. eval_context, SemIR::LocId(inst_id), info, &phase);
  1903. return MakeFacetTypeResult(eval_context.context(), const_info, phase);
  1904. }
  1905. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1906. static auto TryEvalInstInContext(EvalContext& eval_context,
  1907. SemIR::InstId inst_id, SemIR::Inst inst)
  1908. -> SemIR::ConstantId {
  1909. using EvalInstFn =
  1910. auto(EvalContext & eval_context, SemIR::InstId inst_id, SemIR::Inst inst)
  1911. ->SemIR::ConstantId;
  1912. static constexpr EvalInstFn* EvalInstFns[] = {
  1913. #define CARBON_SEM_IR_INST_KIND(Kind) &TryEvalTypedInst<SemIR::Kind>,
  1914. #include "toolchain/sem_ir/inst_kind.def"
  1915. };
  1916. [[clang::musttail]] return EvalInstFns[inst.kind().AsInt()](eval_context,
  1917. inst_id, inst);
  1918. }
  1919. auto TryEvalInstUnsafe(Context& context, SemIR::InstId inst_id,
  1920. SemIR::Inst inst) -> SemIR::ConstantId {
  1921. EvalContext eval_context(&context, SemIR::LocId(inst_id));
  1922. return TryEvalInstInContext(eval_context, inst_id, inst);
  1923. }
  1924. auto TryEvalBlockForSpecific(Context& context, SemIR::LocId loc_id,
  1925. SemIR::SpecificId specific_id,
  1926. SemIR::GenericInstIndex::Region region)
  1927. -> SemIR::InstBlockId {
  1928. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1929. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1930. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1931. llvm::SmallVector<SemIR::InstId> result;
  1932. result.resize(eval_block.size(), SemIR::InstId::None);
  1933. EvalContext eval_context(&context, loc_id, specific_id,
  1934. SpecificEvalInfo{
  1935. .region = region,
  1936. .values = result,
  1937. });
  1938. Diagnostics::AnnotationScope annotate_diagnostics(
  1939. &context.emitter(), [&](auto& builder) {
  1940. CARBON_DIAGNOSTIC(ResolvingSpecificHere, Note, "in {0} used here",
  1941. SemIR::SpecificId);
  1942. builder.Note(loc_id, ResolvingSpecificHere, specific_id);
  1943. });
  1944. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1945. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1946. context.insts().Get(inst_id));
  1947. result[i] = context.constant_values().GetInstId(const_id);
  1948. CARBON_CHECK(result[i].has_value(), "Failed to evaluate {0} in eval block",
  1949. context.insts().Get(inst_id));
  1950. }
  1951. return context.inst_blocks().Add(result);
  1952. }
  1953. } // namespace Carbon::Check