eval.cpp 121 KB

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