eval.cpp 95 KB

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