eval.cpp 84 KB

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