eval.cpp 87 KB

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