eval.cpp 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917
  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::PrintChar:
  1663. case SemIR::BuiltinFunctionKind::PrintInt:
  1664. case SemIR::BuiltinFunctionKind::ReadChar:
  1665. case SemIR::BuiltinFunctionKind::FloatAddAssign:
  1666. case SemIR::BuiltinFunctionKind::FloatSubAssign:
  1667. case SemIR::BuiltinFunctionKind::FloatMulAssign:
  1668. case SemIR::BuiltinFunctionKind::FloatDivAssign:
  1669. case SemIR::BuiltinFunctionKind::IntSAddAssign:
  1670. case SemIR::BuiltinFunctionKind::IntSSubAssign:
  1671. case SemIR::BuiltinFunctionKind::IntSMulAssign:
  1672. case SemIR::BuiltinFunctionKind::IntSDivAssign:
  1673. case SemIR::BuiltinFunctionKind::IntSModAssign:
  1674. case SemIR::BuiltinFunctionKind::IntUAddAssign:
  1675. case SemIR::BuiltinFunctionKind::IntUSubAssign:
  1676. case SemIR::BuiltinFunctionKind::IntUMulAssign:
  1677. case SemIR::BuiltinFunctionKind::IntUDivAssign:
  1678. case SemIR::BuiltinFunctionKind::IntUModAssign:
  1679. case SemIR::BuiltinFunctionKind::IntAndAssign:
  1680. case SemIR::BuiltinFunctionKind::IntOrAssign:
  1681. case SemIR::BuiltinFunctionKind::IntXorAssign:
  1682. case SemIR::BuiltinFunctionKind::IntLeftShiftAssign:
  1683. case SemIR::BuiltinFunctionKind::IntRightShiftAssign:
  1684. case SemIR::BuiltinFunctionKind::PointerMakeNull:
  1685. case SemIR::BuiltinFunctionKind::PointerIsNull:
  1686. case SemIR::BuiltinFunctionKind::PointerUnsafeConvert:
  1687. case SemIR::BuiltinFunctionKind::CppStdInitializerListMake: {
  1688. // These are runtime-only builtins.
  1689. // TODO: Consider tracking this on the `BuiltinFunctionKind`.
  1690. return SemIR::ConstantId::NotConstant;
  1691. }
  1692. case SemIR::BuiltinFunctionKind::TypeAnd: {
  1693. CARBON_CHECK(arg_ids.size() == 2);
  1694. auto lhs_facet_type_id = ArgToFacetTypeId(context, loc_id, arg_ids[0]);
  1695. auto rhs_facet_type_id = ArgToFacetTypeId(context, loc_id, arg_ids[1]);
  1696. // Allow errors to be diagnosed for both sides of the operator before
  1697. // returning here if any error occurred on either side.
  1698. if (!lhs_facet_type_id.has_value() || !rhs_facet_type_id.has_value()) {
  1699. return SemIR::ErrorInst::ConstantId;
  1700. }
  1701. // Reuse one of the argument instructions if nothing has changed.
  1702. if (lhs_facet_type_id == rhs_facet_type_id) {
  1703. return context.types().GetConstantId(
  1704. context.types().GetTypeIdForTypeInstId(arg_ids[0]));
  1705. }
  1706. auto combined_info = SemIR::FacetTypeInfo::Combine(
  1707. context.facet_types().Get(lhs_facet_type_id),
  1708. context.facet_types().Get(rhs_facet_type_id));
  1709. if (!ResolveFacetTypeRewriteConstraints(
  1710. eval_context.context(), loc_id,
  1711. combined_info.rewrite_constraints)) {
  1712. phase = Phase::UnknownDueToError;
  1713. }
  1714. combined_info.Canonicalize();
  1715. return MakeFacetTypeResult(eval_context.context(), combined_info, phase);
  1716. }
  1717. case SemIR::BuiltinFunctionKind::CharLiteralMakeType: {
  1718. return context.constant_values().Get(SemIR::CharLiteralType::TypeInstId);
  1719. }
  1720. case SemIR::BuiltinFunctionKind::FloatLiteralMakeType: {
  1721. return context.constant_values().Get(SemIR::FloatLiteralType::TypeInstId);
  1722. }
  1723. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  1724. return context.constant_values().Get(SemIR::IntLiteralType::TypeInstId);
  1725. }
  1726. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  1727. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Signed,
  1728. arg_ids[0], phase);
  1729. }
  1730. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  1731. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Unsigned,
  1732. arg_ids[0], phase);
  1733. }
  1734. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  1735. return MakeFloatTypeResult(context, loc_id, arg_ids[0], phase);
  1736. }
  1737. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  1738. return context.constant_values().Get(SemIR::BoolType::TypeInstId);
  1739. }
  1740. case SemIR::BuiltinFunctionKind::MaybeUnformedMakeType: {
  1741. return MakeConstantResult(
  1742. context,
  1743. SemIR::MaybeUnformedType{
  1744. .type_id = SemIR::TypeType::TypeId,
  1745. .inner_id = context.types().GetAsTypeInstId(arg_ids[0])},
  1746. phase);
  1747. }
  1748. case SemIR::BuiltinFunctionKind::FormMakeType: {
  1749. return context.constant_values().Get(SemIR::FormType::TypeInstId);
  1750. }
  1751. // Character conversions.
  1752. case SemIR::BuiltinFunctionKind::CharConvertChecked: {
  1753. if (phase != Phase::Concrete) {
  1754. return MakeConstantResult(context, call, phase);
  1755. }
  1756. return PerformCheckedCharConvert(context, loc_id, arg_ids[0],
  1757. call.type_id);
  1758. }
  1759. // Integer conversions.
  1760. case SemIR::BuiltinFunctionKind::IntConvertChar: {
  1761. if (phase != Phase::Concrete) {
  1762. return MakeConstantResult(context, call, phase);
  1763. }
  1764. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1765. }
  1766. case SemIR::BuiltinFunctionKind::IntConvert: {
  1767. if (phase != Phase::Concrete) {
  1768. return MakeConstantResult(context, call, phase);
  1769. }
  1770. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1771. }
  1772. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  1773. if (phase != Phase::Concrete) {
  1774. return MakeConstantResult(context, call, phase);
  1775. }
  1776. return PerformCheckedIntConvert(context, loc_id, arg_ids[0],
  1777. call.type_id);
  1778. }
  1779. // Unary integer -> integer operations.
  1780. case SemIR::BuiltinFunctionKind::IntSNegate:
  1781. case SemIR::BuiltinFunctionKind::IntUNegate:
  1782. case SemIR::BuiltinFunctionKind::IntComplement: {
  1783. if (phase != Phase::Concrete) {
  1784. break;
  1785. }
  1786. return PerformBuiltinUnaryIntOp(context, loc_id, builtin_kind,
  1787. arg_ids[0]);
  1788. }
  1789. // Homogeneous binary integer -> integer operations.
  1790. case SemIR::BuiltinFunctionKind::IntSAdd:
  1791. case SemIR::BuiltinFunctionKind::IntSSub:
  1792. case SemIR::BuiltinFunctionKind::IntSMul:
  1793. case SemIR::BuiltinFunctionKind::IntSDiv:
  1794. case SemIR::BuiltinFunctionKind::IntSMod:
  1795. case SemIR::BuiltinFunctionKind::IntUAdd:
  1796. case SemIR::BuiltinFunctionKind::IntUSub:
  1797. case SemIR::BuiltinFunctionKind::IntUMul:
  1798. case SemIR::BuiltinFunctionKind::IntUDiv:
  1799. case SemIR::BuiltinFunctionKind::IntUMod:
  1800. case SemIR::BuiltinFunctionKind::IntAnd:
  1801. case SemIR::BuiltinFunctionKind::IntOr:
  1802. case SemIR::BuiltinFunctionKind::IntXor: {
  1803. if (phase != Phase::Concrete) {
  1804. break;
  1805. }
  1806. return PerformBuiltinBinaryIntOp(context, loc_id, builtin_kind,
  1807. arg_ids[0], arg_ids[1]);
  1808. }
  1809. // Bit shift operations.
  1810. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1811. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1812. if (phase != Phase::Concrete) {
  1813. break;
  1814. }
  1815. return PerformBuiltinIntShiftOp(context, loc_id, builtin_kind, arg_ids[0],
  1816. arg_ids[1]);
  1817. }
  1818. // Integer comparisons.
  1819. case SemIR::BuiltinFunctionKind::IntEq:
  1820. case SemIR::BuiltinFunctionKind::IntNeq:
  1821. case SemIR::BuiltinFunctionKind::IntLess:
  1822. case SemIR::BuiltinFunctionKind::IntLessEq:
  1823. case SemIR::BuiltinFunctionKind::IntGreater:
  1824. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1825. if (phase != Phase::Concrete) {
  1826. break;
  1827. }
  1828. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1829. arg_ids[1], call.type_id);
  1830. }
  1831. // Floating-point conversions.
  1832. case SemIR::BuiltinFunctionKind::FloatConvertChecked: {
  1833. if (phase != Phase::Concrete) {
  1834. return MakeConstantResult(context, call, phase);
  1835. }
  1836. return PerformCheckedFloatConvert(context, loc_id, arg_ids[0],
  1837. call.type_id);
  1838. }
  1839. // Unary float -> float operations.
  1840. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1841. if (phase != Phase::Concrete) {
  1842. break;
  1843. }
  1844. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1845. }
  1846. // Binary float -> float operations.
  1847. case SemIR::BuiltinFunctionKind::FloatAdd:
  1848. case SemIR::BuiltinFunctionKind::FloatSub:
  1849. case SemIR::BuiltinFunctionKind::FloatMul:
  1850. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1851. if (phase != Phase::Concrete) {
  1852. break;
  1853. }
  1854. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1855. arg_ids[1]);
  1856. }
  1857. // Float comparisons.
  1858. case SemIR::BuiltinFunctionKind::FloatEq:
  1859. case SemIR::BuiltinFunctionKind::FloatNeq:
  1860. case SemIR::BuiltinFunctionKind::FloatLess:
  1861. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1862. case SemIR::BuiltinFunctionKind::FloatGreater:
  1863. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1864. if (phase != Phase::Concrete) {
  1865. break;
  1866. }
  1867. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1868. arg_ids[1], call.type_id);
  1869. }
  1870. // Bool comparisons.
  1871. case SemIR::BuiltinFunctionKind::BoolEq:
  1872. case SemIR::BuiltinFunctionKind::BoolNeq: {
  1873. if (phase != Phase::Concrete) {
  1874. break;
  1875. }
  1876. return PerformBuiltinBoolComparison(context, builtin_kind, arg_ids[0],
  1877. arg_ids[1], call.type_id);
  1878. }
  1879. }
  1880. return SemIR::ConstantId::NotConstant;
  1881. }
  1882. static auto TryEvalCall(EvalContext& outer_eval_context, SemIR::LocId loc_id,
  1883. const SemIR::Function& function,
  1884. SemIR::SpecificId specific_id,
  1885. SemIR::InstBlockId args_id) -> SemIR::ConstantId;
  1886. // Makes a constant for a call instruction.
  1887. static auto MakeConstantForCall(EvalContext& eval_context,
  1888. SemIR::InstId inst_id, SemIR::Call call)
  1889. -> SemIR::ConstantId {
  1890. Phase phase = Phase::Concrete;
  1891. // A call with an invalid argument list is used to represent an erroneous
  1892. // call.
  1893. //
  1894. // TODO: Use a better representation for this.
  1895. if (call.args_id == SemIR::InstBlockId::None) {
  1896. return SemIR::ErrorInst::ConstantId;
  1897. }
  1898. // Find the constant value of the callee.
  1899. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1900. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1901. auto callee = SemIR::GetCallee(eval_context.sem_ir(), call.callee_id);
  1902. const SemIR::Function* function = nullptr;
  1903. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1904. auto evaluation_mode = SemIR::Function::EvaluationMode::None;
  1905. if (auto* callee_function = std::get_if<SemIR::CalleeFunction>(&callee)) {
  1906. function = &eval_context.functions().Get(callee_function->function_id);
  1907. builtin_kind = function->builtin_function_kind();
  1908. evaluation_mode = function->evaluation_mode;
  1909. // Calls to builtins and to `eval` or `musteval` functions might be
  1910. // constant.
  1911. if (builtin_kind == SemIR::BuiltinFunctionKind::None &&
  1912. evaluation_mode == SemIR::Function::EvaluationMode::None) {
  1913. return SemIR::ConstantId::NotConstant;
  1914. }
  1915. } else {
  1916. // Calls to non-functions, such as calls to generic entity names, might be
  1917. // constant.
  1918. }
  1919. // Find the argument values and the return type.
  1920. bool has_constant_operands =
  1921. has_constant_callee &&
  1922. ReplaceTypeWithConstantValue(eval_context, inst_id, &call, &phase) &&
  1923. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1924. &phase);
  1925. if (phase == Phase::UnknownDueToError) {
  1926. return SemIR::ErrorInst::ConstantId;
  1927. }
  1928. // If any operand of the call is non-constant, the call is non-constant.
  1929. // TODO: Some builtin calls might allow some operands to be non-constant.
  1930. if (!has_constant_operands) {
  1931. if (builtin_kind.IsCompTimeOnly(
  1932. eval_context.sem_ir(), eval_context.inst_blocks().Get(call.args_id),
  1933. call.type_id) ||
  1934. evaluation_mode == SemIR::Function::EvaluationMode::MustEval) {
  1935. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1936. "non-constant call to compile-time-only function");
  1937. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1938. "compile-time-only function declared here");
  1939. const auto& function = eval_context.functions().Get(
  1940. std::get<SemIR::CalleeFunction>(callee).function_id);
  1941. eval_context.emitter()
  1942. .Build(inst_id, NonConstantCallToCompTimeOnlyFunction)
  1943. .Note(function.latest_decl_id(), CompTimeOnlyFunctionHere)
  1944. .Emit();
  1945. }
  1946. return SemIR::ConstantId::NotConstant;
  1947. }
  1948. // Handle calls to builtins.
  1949. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1950. return MakeConstantForBuiltinCall(
  1951. eval_context, SemIR::LocId(inst_id), call, builtin_kind,
  1952. eval_context.inst_blocks().Get(call.args_id), phase);
  1953. }
  1954. // Handle calls to `eval` and `musteval` functions.
  1955. if (evaluation_mode != SemIR::Function::EvaluationMode::None) {
  1956. // A non-concrete call to `eval` or `musteval` is a template symbolic
  1957. // constant, regardless of the phase of the arguments.
  1958. if (phase != Phase::Concrete) {
  1959. CARBON_CHECK(phase <= Phase::TemplateSymbolic);
  1960. return MakeConstantResult(eval_context.context(), call,
  1961. Phase::TemplateSymbolic);
  1962. }
  1963. // TODO: Instead of performing the call immediately, add it to a work queue
  1964. // and do it non-recursively.
  1965. return TryEvalCall(
  1966. eval_context, SemIR::LocId(inst_id), *function,
  1967. std::get<SemIR::CalleeFunction>(callee).resolved_specific_id,
  1968. call.args_id);
  1969. }
  1970. return SemIR::ConstantId::NotConstant;
  1971. }
  1972. // Given an instruction, compute its phase based on its operands.
  1973. static auto ComputeInstPhase(Context& context, SemIR::Inst inst) -> Phase {
  1974. EvalContext eval_context(&context, SemIR::LocId::None);
  1975. auto phase = GetPhase(context.constant_values(),
  1976. context.types().GetConstantId(inst.type_id()));
  1977. GetConstantValueForArg(eval_context, inst.arg0_and_kind(), &phase);
  1978. GetConstantValueForArg(eval_context, inst.arg1_and_kind(), &phase);
  1979. CARBON_CHECK(IsConstantOrError(phase));
  1980. return phase;
  1981. }
  1982. // Convert a ConstantEvalResult to a ConstantId. Factored out of
  1983. // TryEvalTypedInst to avoid repeated instantiation of common code.
  1984. static auto ConvertEvalResultToConstantId(Context& context,
  1985. ConstantEvalResult result,
  1986. Phase orig_phase)
  1987. -> SemIR::ConstantId {
  1988. if (result.is_new()) {
  1989. return MakeConstantResult(
  1990. context, result.new_inst(),
  1991. result.same_phase_as_inst()
  1992. ? orig_phase
  1993. : ComputeInstPhase(context, result.new_inst()));
  1994. }
  1995. return result.existing();
  1996. }
  1997. // Evaluates an instruction of a known type in an evaluation context. The
  1998. // default behavior of this function depends on the constant kind of the
  1999. // instruction:
  2000. //
  2001. // - InstConstantKind::Never: returns ConstantId::NotConstant.
  2002. // - InstConstantKind::Indirect, SymbolicOnly, SymbolicOrReference,
  2003. // Conditional: evaluates all the operands of the instruction, and calls
  2004. // `EvalConstantInst` to evaluate the resulting constant instruction.
  2005. // - InstConstantKind::WheneverPossible, Always: evaluates all the operands of
  2006. // the instruction, and produces the resulting constant instruction as the
  2007. // result.
  2008. // - InstConstantKind::Unique: returns the `inst_id` as the resulting
  2009. // constant.
  2010. //
  2011. // Returns an error constant ID if any of the nested evaluations fail, and
  2012. // returns NotConstant if any of the nested evaluations is non-constant.
  2013. //
  2014. // This template is explicitly specialized for instructions that need special
  2015. // handling.
  2016. template <typename InstT>
  2017. static auto TryEvalTypedInst(EvalContext& eval_context, SemIR::InstId inst_id,
  2018. SemIR::Inst inst) -> SemIR::ConstantId {
  2019. constexpr auto ConstantKind = InstT::Kind.constant_kind();
  2020. if constexpr (ConstantKind == SemIR::InstConstantKind::Never) {
  2021. return SemIR::ConstantId::NotConstant;
  2022. } else if constexpr (ConstantKind == SemIR::InstConstantKind::AlwaysUnique) {
  2023. CARBON_CHECK(inst_id.has_value());
  2024. return SemIR::ConstantId::ForConcreteConstant(inst_id);
  2025. } else {
  2026. // Build a constant instruction by replacing each non-constant operand with
  2027. // its constant value.
  2028. Phase phase = Phase::Concrete;
  2029. if ((SemIR::Internal::HasTypeIdMember<InstT> &&
  2030. !ReplaceTypeWithConstantValue(eval_context, inst_id, &inst, &phase)) ||
  2031. !ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  2032. if constexpr (ConstantKind == SemIR::InstConstantKind::Always) {
  2033. CARBON_FATAL("{0} should always be constant", InstT::Kind);
  2034. }
  2035. return SemIR::ConstantId::NotConstant;
  2036. }
  2037. // If any operand of the instruction has an error in it, the instruction
  2038. // itself evaluates to an error.
  2039. if (phase == Phase::UnknownDueToError) {
  2040. return SemIR::ErrorInst::ConstantId;
  2041. }
  2042. // When canonicalizing a SpecificId, we defer resolving the specific's
  2043. // declaration until here, to avoid resolving declarations from imported
  2044. // specifics. (Imported instructions are not evaluated.)
  2045. ResolveSpecificDeclForInst(eval_context, inst);
  2046. if constexpr (ConstantKind == SemIR::InstConstantKind::Always ||
  2047. ConstantKind == SemIR::InstConstantKind::WheneverPossible) {
  2048. return MakeConstantResult(eval_context.context(), inst, phase);
  2049. } else if constexpr (ConstantKind == SemIR::InstConstantKind::InstAction) {
  2050. auto result_inst_id = PerformDelayedAction(
  2051. eval_context.context(), SemIR::LocId(inst_id), inst.As<InstT>());
  2052. if (result_inst_id.has_value()) {
  2053. // The result is an instruction.
  2054. return MakeConstantResult(
  2055. eval_context.context(),
  2056. SemIR::InstValue{
  2057. .type_id = GetSingletonType(eval_context.context(),
  2058. SemIR::InstType::TypeInstId),
  2059. .inst_id = result_inst_id},
  2060. Phase::Concrete);
  2061. }
  2062. // Couldn't perform the action because it's still dependent.
  2063. return MakeConstantResult(eval_context.context(), inst,
  2064. Phase::TemplateSymbolic);
  2065. } else if constexpr (InstT::Kind.constant_needs_inst_id() !=
  2066. SemIR::InstConstantNeedsInstIdKind::No) {
  2067. CARBON_CHECK(inst_id.has_value());
  2068. return ConvertEvalResultToConstantId(
  2069. eval_context.context(),
  2070. EvalConstantInst(eval_context.context(), inst_id, inst.As<InstT>()),
  2071. phase);
  2072. } else {
  2073. return ConvertEvalResultToConstantId(
  2074. eval_context.context(),
  2075. EvalConstantInst(eval_context.context(), inst.As<InstT>()), phase);
  2076. }
  2077. }
  2078. }
  2079. // Specialize evaluation for array indexing because we want to check the index
  2080. // expression even if the array expression is non-constant.
  2081. template <>
  2082. auto TryEvalTypedInst<SemIR::ArrayIndex>(EvalContext& eval_context,
  2083. SemIR::InstId /*inst_id*/,
  2084. SemIR::Inst inst)
  2085. -> SemIR::ConstantId {
  2086. return PerformArrayIndex(eval_context, inst.As<SemIR::ArrayIndex>());
  2087. }
  2088. // Specialize evaluation for function calls because we want to check the callee
  2089. // expression even if an argument expression is non-constant, and because we
  2090. // will eventually want to perform control flow handling here.
  2091. template <>
  2092. auto TryEvalTypedInst<SemIR::Call>(EvalContext& eval_context,
  2093. SemIR::InstId inst_id, SemIR::Inst inst)
  2094. -> SemIR::ConstantId {
  2095. return MakeConstantForCall(eval_context, inst_id, inst.As<SemIR::Call>());
  2096. }
  2097. // ImportRefLoaded can have a constant value, but it's owned and maintained by
  2098. // `import_ref.cpp`, not by us.
  2099. // TODO: Rearrange how `ImportRefLoaded` instructions are created so we never
  2100. // call this.
  2101. template <>
  2102. auto TryEvalTypedInst<SemIR::ImportRefLoaded>(EvalContext& /*eval_context*/,
  2103. SemIR::InstId /*inst_id*/,
  2104. SemIR::Inst /*inst*/)
  2105. -> SemIR::ConstantId {
  2106. return SemIR::ConstantId::NotConstant;
  2107. }
  2108. // Symbolic bindings are a special case because they can reach into the eval
  2109. // context and produce a context-specific value.
  2110. template <>
  2111. auto TryEvalTypedInst<SemIR::SymbolicBinding>(EvalContext& eval_context,
  2112. SemIR::InstId inst_id,
  2113. SemIR::Inst inst)
  2114. -> SemIR::ConstantId {
  2115. auto bind = inst.As<SemIR::SymbolicBinding>();
  2116. // If we know which specific we're evaluating within and this is an argument
  2117. // of that specific, its constant value is the corresponding argument value.
  2118. const auto& bind_name = eval_context.entity_names().Get(bind.entity_name_id);
  2119. if (bind_name.bind_index().has_value()) {
  2120. if (auto value =
  2121. eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  2122. value.has_value()) {
  2123. return value;
  2124. }
  2125. }
  2126. // The constant form of a symbolic binding is an idealized form of the
  2127. // original, with no equivalent value.
  2128. Phase phase = Phase::Concrete;
  2129. bind.value_id = SemIR::InstId::None;
  2130. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &bind, &phase) ||
  2131. !ReplaceFieldWithConstantValue(eval_context, &bind,
  2132. &SemIR::SymbolicBinding::entity_name_id,
  2133. &phase)) {
  2134. return SemIR::ConstantId::NotConstant;
  2135. }
  2136. // This correctly handles `Phase::UnknownDueToError`.
  2137. return MakeConstantResult(eval_context.context(), bind, phase);
  2138. }
  2139. template <>
  2140. auto TryEvalTypedInst<SemIR::SymbolicBindingType>(EvalContext& eval_context,
  2141. SemIR::InstId inst_id,
  2142. SemIR::Inst inst)
  2143. -> SemIR::ConstantId {
  2144. // If a specific provides a new value for the binding with `entity_name_id`,
  2145. // the SymbolicBindingType is evaluated for that new value.
  2146. const auto& bind_name = eval_context.entity_names().Get(
  2147. inst.As<SemIR::SymbolicBindingType>().entity_name_id);
  2148. if (bind_name.bind_index().has_value()) {
  2149. if (auto value =
  2150. eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  2151. value.has_value()) {
  2152. auto value_inst_id = eval_context.constant_values().GetInstId(value);
  2153. // A SymbolicBindingType can evaluate to a FacetAccessType if the new
  2154. // value of the entity is a facet value that that does not have a concrete
  2155. // type (a FacetType) and does not have a new EntityName to point to (a
  2156. // SymbolicBinding).
  2157. auto access = SemIR::FacetAccessType{
  2158. .type_id = SemIR::TypeType::TypeId,
  2159. .facet_value_inst_id = value_inst_id,
  2160. };
  2161. return ConvertEvalResultToConstantId(
  2162. eval_context.context(),
  2163. EvalConstantInst(eval_context.context(), access),
  2164. ComputeInstPhase(eval_context.context(), access));
  2165. }
  2166. }
  2167. Phase phase = Phase::Concrete;
  2168. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &inst, &phase) ||
  2169. !ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  2170. return SemIR::ConstantId::NotConstant;
  2171. }
  2172. // Propagate error phase after getting the constant value for all fields.
  2173. if (phase == Phase::UnknownDueToError) {
  2174. return SemIR::ErrorInst::ConstantId;
  2175. }
  2176. // Evaluation of SymbolicBindingType.
  2177. //
  2178. // Like FacetAccessType, a SymbolicBindingType of a FacetValue just evaluates
  2179. // to the type inside.
  2180. //
  2181. // TODO: Look in ScopeStack with the entity_name_id to find the facet value
  2182. // and get its constant value in the current specific context. The
  2183. // facet_value_inst_id will go away.
  2184. if (auto facet_value = eval_context.insts().TryGetAs<SemIR::FacetValue>(
  2185. inst.As<SemIR::SymbolicBindingType>().facet_value_inst_id)) {
  2186. return eval_context.constant_values().Get(facet_value->type_inst_id);
  2187. }
  2188. return MakeConstantResult(eval_context.context(), inst, phase);
  2189. }
  2190. // Returns whether `const_id` is the same constant facet value as
  2191. // `facet_value_inst_id`.
  2192. //
  2193. // Compares with the canonical facet value of `const_id`, dropping any `as type`
  2194. // conversions.
  2195. static auto IsSameFacetValue(Context& context, SemIR::ConstantId const_id,
  2196. SemIR::InstId facet_value_inst_id) -> bool {
  2197. auto canon_const_id = GetCanonicalFacetOrTypeValue(context, const_id);
  2198. return canon_const_id == context.constant_values().Get(facet_value_inst_id);
  2199. }
  2200. // TODO: Convert this to an EvalConstantInst function. This will require
  2201. // providing a `GetConstantValue` overload for a requirement block.
  2202. template <>
  2203. auto TryEvalTypedInst<SemIR::WhereExpr>(EvalContext& eval_context,
  2204. SemIR::InstId inst_id, SemIR::Inst inst)
  2205. -> SemIR::ConstantId {
  2206. auto typed_inst = inst.As<SemIR::WhereExpr>();
  2207. Phase phase = Phase::Concrete;
  2208. SemIR::FacetTypeInfo info;
  2209. // Add the constraints from the `WhereExpr` instruction into `info`.
  2210. if (typed_inst.requirements_id.has_value()) {
  2211. auto insts = eval_context.inst_blocks().Get(typed_inst.requirements_id);
  2212. for (auto inst_id : insts) {
  2213. if (auto base =
  2214. eval_context.insts().TryGetAs<SemIR::RequirementBaseFacetType>(
  2215. inst_id)) {
  2216. if (base->base_type_inst_id == SemIR::ErrorInst::TypeInstId) {
  2217. return SemIR::ErrorInst::ConstantId;
  2218. }
  2219. if (auto base_facet_type =
  2220. eval_context.insts().TryGetAs<SemIR::FacetType>(
  2221. base->base_type_inst_id)) {
  2222. const auto& base_info =
  2223. eval_context.facet_types().Get(base_facet_type->facet_type_id);
  2224. info.extend_constraints.append(base_info.extend_constraints);
  2225. info.self_impls_constraints.append(base_info.self_impls_constraints);
  2226. info.rewrite_constraints.append(base_info.rewrite_constraints);
  2227. info.other_requirements |= base_info.other_requirements;
  2228. }
  2229. } else if (auto rewrite =
  2230. eval_context.insts().TryGetAs<SemIR::RequirementRewrite>(
  2231. inst_id)) {
  2232. info.rewrite_constraints.push_back(
  2233. {.lhs_id = rewrite->lhs_id, .rhs_id = rewrite->rhs_id});
  2234. } else if (auto impls =
  2235. eval_context.insts().TryGetAs<SemIR::RequirementImpls>(
  2236. inst_id)) {
  2237. SemIR::ConstantId lhs_const_id =
  2238. eval_context.GetConstantValue(impls->lhs_id);
  2239. SemIR::ConstantId rhs_const_id =
  2240. eval_context.GetConstantValue(impls->rhs_id);
  2241. if (IsSameFacetValue(eval_context.context(), lhs_const_id,
  2242. typed_inst.period_self_id)) {
  2243. auto rhs_inst_id =
  2244. eval_context.constant_values().GetInstId(rhs_const_id);
  2245. if (rhs_inst_id == SemIR::ErrorInst::InstId) {
  2246. // `.Self impls <error>`.
  2247. return SemIR::ErrorInst::ConstantId;
  2248. } else if (rhs_inst_id == SemIR::TypeType::TypeInstId) {
  2249. // `.Self impls type` -> nothing to do.
  2250. } else {
  2251. auto facet_type = eval_context.insts().GetAs<SemIR::FacetType>(
  2252. RequireConstantValue(eval_context, impls->rhs_id, &phase));
  2253. const auto& more_info =
  2254. eval_context.facet_types().Get(facet_type.facet_type_id);
  2255. // The way to prevent lookup into the interface requirements of a
  2256. // facet type is to put it to the right of a `.Self impls`, which we
  2257. // accomplish by putting them into `self_impls_constraints`.
  2258. llvm::append_range(info.self_impls_constraints,
  2259. more_info.extend_constraints);
  2260. llvm::append_range(info.self_impls_constraints,
  2261. more_info.self_impls_constraints);
  2262. // Other requirements are copied in.
  2263. llvm::append_range(info.rewrite_constraints,
  2264. more_info.rewrite_constraints);
  2265. info.other_requirements |= more_info.other_requirements;
  2266. }
  2267. } else {
  2268. // TODO: Handle `impls` constraints beyond `.Self impls`.
  2269. info.other_requirements = true;
  2270. }
  2271. } else {
  2272. // TODO: Handle other requirements.
  2273. info.other_requirements = true;
  2274. }
  2275. }
  2276. }
  2277. auto const_info = GetConstantFacetTypeInfo(
  2278. eval_context, SemIR::LocId(inst_id), info, &phase);
  2279. return MakeFacetTypeResult(eval_context.context(), const_info, phase);
  2280. }
  2281. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  2282. static auto TryEvalInstInContext(EvalContext& eval_context,
  2283. SemIR::InstId inst_id, SemIR::Inst inst)
  2284. -> SemIR::ConstantId {
  2285. using EvalInstFn =
  2286. auto(EvalContext & eval_context, SemIR::InstId inst_id, SemIR::Inst inst)
  2287. ->SemIR::ConstantId;
  2288. static constexpr EvalInstFn* EvalInstFns[] = {
  2289. #define CARBON_SEM_IR_INST_KIND(Kind) &TryEvalTypedInst<SemIR::Kind>,
  2290. #include "toolchain/sem_ir/inst_kind.def"
  2291. };
  2292. [[clang::musttail]] return EvalInstFns[inst.kind().AsInt()](eval_context,
  2293. inst_id, inst);
  2294. }
  2295. auto TryEvalInstUnsafe(Context& context, SemIR::InstId inst_id,
  2296. SemIR::Inst inst) -> SemIR::ConstantId {
  2297. EvalContext eval_context(&context, SemIR::LocId(inst_id));
  2298. return TryEvalInstInContext(eval_context, inst_id, inst);
  2299. }
  2300. auto TryEvalBlockForSpecific(Context& context, SemIR::LocId loc_id,
  2301. SemIR::SpecificId specific_id,
  2302. SemIR::GenericInstIndex::Region region)
  2303. -> SemIR::InstBlockId {
  2304. auto generic_id = context.specifics().Get(specific_id).generic_id;
  2305. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  2306. auto eval_block = context.inst_blocks().Get(eval_block_id);
  2307. llvm::SmallVector<SemIR::InstId> result;
  2308. result.resize(eval_block.size(), SemIR::InstId::None);
  2309. EvalContext eval_context(&context, loc_id, specific_id,
  2310. SpecificEvalInfo{
  2311. .region = region,
  2312. .values = result,
  2313. });
  2314. Diagnostics::ContextScope diagnostic_context(
  2315. &context.emitter(), [&](auto& builder) {
  2316. CARBON_DIAGNOSTIC(ResolvingSpecificHere, SoftContext,
  2317. "unable to monomorphize specific {0}",
  2318. SemIR::SpecificId);
  2319. builder.Context(loc_id, ResolvingSpecificHere, specific_id);
  2320. });
  2321. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  2322. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  2323. context.insts().Get(inst_id));
  2324. result[i] = context.constant_values().GetInstId(const_id);
  2325. CARBON_CHECK(result[i].has_value(), "Failed to evaluate {0} in eval block",
  2326. context.insts().Get(inst_id));
  2327. }
  2328. return context.inst_blocks().Add(result);
  2329. }
  2330. // Information about the function call we are currently executing. Unlike
  2331. // evaluation, execution sequentially interprets instructions, and can handle
  2332. // control flow and (eventually) side effects and mutable state.
  2333. class FunctionExecContext : public EvalContext {
  2334. public:
  2335. // A block argument passed to `BranchWithArg`.
  2336. struct BlockArgValue {
  2337. SemIR::InstBlockId block_id = SemIR::InstBlockId::None;
  2338. SemIR::ConstantId arg_id = SemIR::ConstantId::None;
  2339. };
  2340. FunctionExecContext(Context* context, SemIR::LocId loc_id,
  2341. SemIR::SpecificId specific_id,
  2342. Map<SemIR::InstId, SemIR::ConstantId>* locals,
  2343. SemIR::InstBlockId args_id)
  2344. : EvalContext(context, loc_id, specific_id,
  2345. LocalEvalInfo{.locals = locals}),
  2346. args_(context->inst_blocks().Get(args_id)) {}
  2347. // Returns the argument values supplied in the call to the function.
  2348. auto args() const -> llvm::ArrayRef<SemIR::InstId> { return args_; }
  2349. using EvalContext::locals;
  2350. // Branch control flow to the given block. This replaces the innermost block
  2351. // in the block stack, but doesn't affect any enclosing blocks.
  2352. auto BranchTo(SemIR::InstBlockId block_id) -> void {
  2353. blocks_.back() = inst_blocks().Get(block_id);
  2354. }
  2355. // Push a new block to be executed immediately. After the block finishes,
  2356. // control will resume after the current instruction.
  2357. auto PushBlock(SemIR::InstBlockId block_id) -> void {
  2358. blocks_.push_back(inst_blocks().Get(block_id));
  2359. }
  2360. // Pops and returns the next instruction to be executed.
  2361. auto PopNextInstId() -> SemIR::InstId {
  2362. while (blocks_.back().empty()) {
  2363. blocks_.pop_back();
  2364. CARBON_CHECK(!blocks_.empty(), "Fell off end of function");
  2365. }
  2366. return blocks_.back().consume_front();
  2367. }
  2368. // Sets the most recent block argument value provided by a `BranchWithArg`.
  2369. // This can later be retrieved by a `BlockArg`.
  2370. auto SetCurrentBlockArgValue(BlockArgValue arg) -> void {
  2371. current_block_arg_value_ = arg;
  2372. }
  2373. // Returns the most recent block argument value provided by a `BranchWithArg`.
  2374. auto current_block_arg_value() const -> BlockArgValue {
  2375. return current_block_arg_value_;
  2376. }
  2377. private:
  2378. // The stack of code blocks that we are currently evaluating. This is kept as
  2379. // a stack so that we can schedule the function body to execute after the decl
  2380. // block and so that we can handle `SpliceBlock`s. When the innermost block is
  2381. // complete, it will be popped and the next outer block will execute.
  2382. llvm::SmallVector<llvm::ArrayRef<SemIR::InstId>, 4> blocks_;
  2383. // The arguments in the function call.
  2384. llvm::ArrayRef<SemIR::InstId> args_;
  2385. // The block argument provided by the most recently executed `BranchWithArg`.
  2386. // We assume that we only need to track one of these, as the branch target
  2387. // will invoke `BlockArg` before the next `BranchWithArg` happens. We will
  2388. // need to track more than one of these if that ever changes.
  2389. BlockArgValue current_block_arg_value_;
  2390. };
  2391. // Handles the result of executing an instruction in a function. Returns an
  2392. // error the result is not a constant, and otherwise updates the locals map to
  2393. // track the result as an input to later evaluations in this function and
  2394. // returns None.
  2395. static auto HandleExecResult(FunctionExecContext& eval_context,
  2396. SemIR::InstId inst_id, SemIR::ConstantId const_id)
  2397. -> SemIR::ConstantId {
  2398. if (!const_id.has_value() || !const_id.is_constant()) {
  2399. DiagnoseNonConstantValue(eval_context, inst_id);
  2400. return SemIR::ErrorInst::ConstantId;
  2401. }
  2402. if (const_id == SemIR::ErrorInst::ConstantId) {
  2403. return const_id;
  2404. }
  2405. eval_context.locals().Update(inst_id, const_id);
  2406. return SemIR::ConstantId::None;
  2407. }
  2408. // Executes an instruction for TryEvalCall. By default, performs normal
  2409. // evaluation of the instruction within a context that supplies the values
  2410. // produced by executing prior instructions in this function execution. This is
  2411. // specialized for instructions that have special handling in function
  2412. // execution, such as those that access parameters or perform flow control. If
  2413. // execution should continue, returns `SemIR::ConstantId::None`, otherwise
  2414. // returns the result to produce for the enclosing function call, which should
  2415. // be either the returned value or an error.
  2416. template <typename InstT>
  2417. static auto TryExecTypedInst(FunctionExecContext& eval_context,
  2418. SemIR::InstId inst_id, SemIR::Inst inst)
  2419. -> SemIR::ConstantId {
  2420. if constexpr (InstT::Kind.expr_category().TryAsFixedCategory() ==
  2421. SemIR::ExprCategory::NotExpr) {
  2422. // Instructions in this category are assumed to not have a runtime effect.
  2423. // This includes some kinds of declaration.
  2424. return SemIR::ConstantId::None;
  2425. }
  2426. if constexpr (InstT::Kind.constant_kind() != SemIR::InstConstantKind::Never) {
  2427. if (eval_context.constant_values().Get(inst_id).is_concrete()) {
  2428. // Instruction has a concrete constant value that doesn't depend on the
  2429. // context. We don't need to evaluate it again.
  2430. return SemIR::ConstantId::None;
  2431. }
  2432. }
  2433. // Evaluate the instruction in the current context.
  2434. auto const_id = TryEvalTypedInst<InstT>(eval_context, inst_id, inst);
  2435. return HandleExecResult(eval_context, inst_id, const_id);
  2436. }
  2437. template <>
  2438. auto TryExecTypedInst<SemIR::BlockArg>(FunctionExecContext& eval_context,
  2439. SemIR::InstId inst_id, SemIR::Inst inst)
  2440. -> SemIR::ConstantId {
  2441. auto block_arg = inst.As<SemIR::BlockArg>();
  2442. CARBON_CHECK(
  2443. block_arg.block_id == eval_context.current_block_arg_value().block_id,
  2444. "BlockArg does not refer to most recent BranchWithArg");
  2445. eval_context.locals().Update(inst_id,
  2446. eval_context.current_block_arg_value().arg_id);
  2447. return SemIR::ConstantId::None;
  2448. }
  2449. template <>
  2450. auto TryExecTypedInst<SemIR::Branch>(FunctionExecContext& eval_context,
  2451. SemIR::InstId /*inst_id*/,
  2452. SemIR::Inst inst) -> SemIR::ConstantId {
  2453. auto branch = inst.As<SemIR::Branch>();
  2454. eval_context.BranchTo(branch.target_id);
  2455. return SemIR::ConstantId::None;
  2456. }
  2457. template <>
  2458. auto TryExecTypedInst<SemIR::BranchIf>(FunctionExecContext& eval_context,
  2459. SemIR::InstId /*inst_id*/,
  2460. SemIR::Inst inst) -> SemIR::ConstantId {
  2461. auto branch_if = inst.As<SemIR::BranchIf>();
  2462. auto cond_id = CheckConcreteValue(eval_context, branch_if.cond_id);
  2463. if (cond_id == SemIR::ErrorInst::InstId) {
  2464. return SemIR::ErrorInst::ConstantId;
  2465. }
  2466. auto cond = eval_context.insts().GetAs<SemIR::BoolLiteral>(cond_id);
  2467. if (cond.value == SemIR::BoolValue::True) {
  2468. eval_context.BranchTo(branch_if.target_id);
  2469. }
  2470. return SemIR::ConstantId::None;
  2471. }
  2472. template <>
  2473. auto TryExecTypedInst<SemIR::BranchWithArg>(FunctionExecContext& eval_context,
  2474. SemIR::InstId /*inst_id*/,
  2475. SemIR::Inst inst)
  2476. -> SemIR::ConstantId {
  2477. auto branch = inst.As<SemIR::BranchWithArg>();
  2478. eval_context.SetCurrentBlockArgValue(
  2479. {.block_id = branch.target_id,
  2480. .arg_id = eval_context.GetConstantValue(branch.arg_id)});
  2481. eval_context.BranchTo(branch.target_id);
  2482. return SemIR::ConstantId::None;
  2483. }
  2484. template <>
  2485. auto TryExecTypedInst<SemIR::Return>(FunctionExecContext& eval_context,
  2486. SemIR::InstId /*inst_id*/,
  2487. SemIR::Inst /*inst*/)
  2488. -> SemIR::ConstantId {
  2489. return MakeEmptyTupleResult(eval_context);
  2490. }
  2491. template <>
  2492. auto TryExecTypedInst<SemIR::ReturnExpr>(FunctionExecContext& eval_context,
  2493. SemIR::InstId /*inst_id*/,
  2494. SemIR::Inst inst)
  2495. -> SemIR::ConstantId {
  2496. auto return_expr = inst.As<SemIR::ReturnExpr>();
  2497. return eval_context.GetConstantValue(return_expr.expr_id);
  2498. }
  2499. template <>
  2500. auto TryExecTypedInst<SemIR::ReturnSlot>(FunctionExecContext& eval_context,
  2501. SemIR::InstId inst_id,
  2502. SemIR::Inst inst)
  2503. -> SemIR::ConstantId {
  2504. auto return_slot = inst.As<SemIR::ReturnSlot>();
  2505. // In the case where the function's return type is not in-place, the return
  2506. // slot will refer to an out parameter that doesn't have an argument. In that
  2507. // case, we don't have a constant value for storage_id. To handle this, copy
  2508. // the value directly from the locals map rather than using GetConstantValue.
  2509. //
  2510. // TODO: Remove this and use a normal call to `GetConstantValue` if we stop
  2511. // adding out parameters with no corresponding argument.
  2512. eval_context.locals().Insert(
  2513. inst_id, eval_context.locals().Lookup(return_slot.storage_id).value());
  2514. return SemIR::ConstantId::None;
  2515. }
  2516. template <>
  2517. auto TryExecTypedInst<SemIR::SpliceBlock>(FunctionExecContext& eval_context,
  2518. SemIR::InstId /*inst_id*/,
  2519. SemIR::Inst inst)
  2520. -> SemIR::ConstantId {
  2521. auto splice_block = inst.As<SemIR::SpliceBlock>();
  2522. eval_context.PushBlock(splice_block.block_id);
  2523. // TODO: Copy the values from the result_id instruction to the result of
  2524. // the splice_block instruction once the spliced block finishes.
  2525. return SemIR::ConstantId::None;
  2526. }
  2527. // Executes the introduction of a parameter into the local scope. Copies the
  2528. // argument supplied by the caller for the parameter into the locals map.
  2529. static auto TryExecTypedParam(FunctionExecContext& eval_context,
  2530. SemIR::InstId inst_id, SemIR::Inst inst)
  2531. -> SemIR::ConstantId {
  2532. auto param = inst.As<SemIR::AnyParam>();
  2533. CARBON_CHECK(static_cast<size_t>(param.index.index) <
  2534. eval_context.args().size());
  2535. eval_context.locals().Insert(inst_id,
  2536. eval_context.constant_values().Get(
  2537. eval_context.args()[param.index.index]));
  2538. return SemIR::ConstantId::None;
  2539. }
  2540. template <>
  2541. auto TryExecTypedInst<SemIR::OutParam>(FunctionExecContext& eval_context,
  2542. SemIR::InstId inst_id, SemIR::Inst inst)
  2543. -> SemIR::ConstantId {
  2544. auto param = inst.As<SemIR::OutParam>();
  2545. if (static_cast<size_t>(param.index.index) >= eval_context.args().size()) {
  2546. // For return values that have a copy initializing representation, the SemIR
  2547. // has an OutParam with an index that has no corresponding argument. In that
  2548. // case, we do not have a constant value for the parameter, but this doesn't
  2549. // prevent the call from being constant.
  2550. //
  2551. // TODO: Remove this once we stop adding out parameters with no
  2552. // corresponding argument.
  2553. eval_context.locals().Insert(inst_id, SemIR::ConstantId::None);
  2554. return SemIR::ConstantId::None;
  2555. }
  2556. return TryExecTypedParam(eval_context, inst_id, inst);
  2557. }
  2558. template <>
  2559. auto TryExecTypedInst<SemIR::RefParam>(FunctionExecContext& eval_context,
  2560. SemIR::InstId inst_id, SemIR::Inst inst)
  2561. -> SemIR::ConstantId {
  2562. return TryExecTypedParam(eval_context, inst_id, inst);
  2563. }
  2564. template <>
  2565. auto TryExecTypedInst<SemIR::ValueParam>(FunctionExecContext& eval_context,
  2566. SemIR::InstId inst_id,
  2567. SemIR::Inst inst)
  2568. -> SemIR::ConstantId {
  2569. return TryExecTypedParam(eval_context, inst_id, inst);
  2570. }
  2571. template <>
  2572. auto TryExecTypedInst<SemIR::ValueBinding>(FunctionExecContext& eval_context,
  2573. SemIR::InstId inst_id,
  2574. SemIR::Inst inst)
  2575. -> SemIR::ConstantId {
  2576. auto value_binding = inst.As<SemIR::ValueBinding>();
  2577. auto local_value_id = eval_context.GetConstantValue(value_binding.value_id);
  2578. eval_context.locals().Insert(inst_id, local_value_id);
  2579. return SemIR::ConstantId::None;
  2580. }
  2581. static auto TryExecInst(FunctionExecContext& eval_context,
  2582. SemIR::InstId inst_id, SemIR::Inst inst)
  2583. -> SemIR::ConstantId {
  2584. using ExecInstFn = auto(FunctionExecContext & eval_context,
  2585. SemIR::InstId inst_id, SemIR::Inst inst)
  2586. ->SemIR::ConstantId;
  2587. static constexpr ExecInstFn* ExecInstFns[] = {
  2588. #define CARBON_SEM_IR_INST_KIND(Kind) &TryExecTypedInst<SemIR::Kind>,
  2589. #include "toolchain/sem_ir/inst_kind.def"
  2590. };
  2591. [[clang::musttail]] return ExecInstFns[inst.kind().AsInt()](eval_context,
  2592. inst_id, inst);
  2593. }
  2594. // Evaluates a call to an `eval` or `musteval` function by executing the
  2595. // function body.
  2596. static auto TryEvalCall(EvalContext& outer_eval_context, SemIR::LocId loc_id,
  2597. const SemIR::Function& function,
  2598. SemIR::SpecificId specific_id,
  2599. SemIR::InstBlockId args_id) -> SemIR::ConstantId {
  2600. if (function.clang_decl_id != SemIR::ClangDeclId::None) {
  2601. return EvalCppCall(outer_eval_context.context(), loc_id,
  2602. function.clang_decl_id, args_id);
  2603. } else if (function.body_block_ids.empty()) {
  2604. // TODO: Diagnose this.
  2605. return SemIR::ConstantId::NotConstant;
  2606. }
  2607. // TODO: Consider tracking the lowest and highest inst_id in the function and
  2608. // using an array instead of a map. We would still need a map for instantiated
  2609. // portions of a function template.
  2610. Map<SemIR::InstId, SemIR::ConstantId> locals;
  2611. FunctionExecContext eval_context(&outer_eval_context.context(), loc_id,
  2612. specific_id, &locals, args_id);
  2613. Diagnostics::AnnotationScope annotate_diagnostics(
  2614. &eval_context.emitter(), [&](auto& builder) {
  2615. CARBON_DIAGNOSTIC(InCallToEvalFn, Note, "in call to {0} here",
  2616. SemIR::NameId);
  2617. builder.Note(loc_id, InCallToEvalFn, function.name_id);
  2618. });
  2619. // Execute the function decl block followed by the body.
  2620. eval_context.PushBlock(function.body_block_ids.front());
  2621. eval_context.PushBlock(eval_context.insts()
  2622. .GetAs<SemIR::FunctionDecl>(function.definition_id)
  2623. .decl_block_id);
  2624. // Execute the blocks. This is mostly expression evaluation, with special
  2625. // handling for control flow and parameters.
  2626. while (true) {
  2627. auto inst_id = eval_context.PopNextInstId();
  2628. auto inst = eval_context.context().insts().Get(inst_id);
  2629. if (auto result = TryExecInst(eval_context, inst_id, inst);
  2630. result.has_value()) {
  2631. return result;
  2632. }
  2633. }
  2634. }
  2635. } // namespace Carbon::Check