eval.cpp 88 KB

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