eval.cpp 77 KB

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