eval.cpp 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076
  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. Ignores the instructions in the
  532. // specified range of indexes, replacing those elements with `None`.
  533. static auto GetConstantBlockValueIgnoringIndexRange(
  534. EvalContext& eval_context, SemIR::InstBlockId inst_block_id, Phase* phase,
  535. std::pair<int, int> ignored_range) -> SemIR::InstBlockId {
  536. if (!inst_block_id.has_value()) {
  537. return SemIR::InstBlockId::None;
  538. }
  539. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  540. llvm::SmallVector<SemIR::InstId> const_insts;
  541. for (auto inst_id : insts) {
  542. auto const_inst_id = SemIR::InstId::None;
  543. if (static_cast<int>(const_insts.size()) < ignored_range.first ||
  544. static_cast<int>(const_insts.size()) >= ignored_range.second) {
  545. const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  546. if (!const_inst_id.has_value()) {
  547. return SemIR::InstBlockId::None;
  548. }
  549. }
  550. // Once we leave the small buffer, we know the first few elements are all
  551. // constant, so it's likely that the entire block is constant. Resize to
  552. // the target size given that we're going to allocate memory now anyway.
  553. if (const_insts.size() == const_insts.capacity()) {
  554. const_insts.reserve(insts.size());
  555. }
  556. const_insts.push_back(const_inst_id);
  557. }
  558. // TODO: If the new block is identical to the original block, and we know the
  559. // old ID was canonical, return the original ID.
  560. return eval_context.inst_blocks().AddCanonical(const_insts);
  561. }
  562. // If the given instruction block contains only constants, returns a
  563. // corresponding block of those values.
  564. static auto GetConstantValue(EvalContext& eval_context,
  565. SemIR::InstBlockId inst_block_id, Phase* phase)
  566. -> SemIR::InstBlockId {
  567. return GetConstantBlockValueIgnoringIndexRange(eval_context, inst_block_id,
  568. phase, {0, 0});
  569. }
  570. // Compute the constant value of a type block. This may be different from the
  571. // input type block if we have known generic arguments.
  572. static auto GetConstantValue(EvalContext& eval_context,
  573. SemIR::StructTypeFieldsId fields_id, Phase* phase)
  574. -> SemIR::StructTypeFieldsId {
  575. if (!fields_id.has_value()) {
  576. return SemIR::StructTypeFieldsId::None;
  577. }
  578. auto fields = eval_context.context().struct_type_fields().Get(fields_id);
  579. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  580. for (auto field : fields) {
  581. auto new_type_inst_id =
  582. GetConstantValue(eval_context, field.type_inst_id, phase);
  583. if (!new_type_inst_id.has_value()) {
  584. return SemIR::StructTypeFieldsId::None;
  585. }
  586. // Once we leave the small buffer, we know the first few elements are all
  587. // constant, so it's likely that the entire block is constant. Resize to the
  588. // target size given that we're going to allocate memory now anyway.
  589. if (new_fields.size() == new_fields.capacity()) {
  590. new_fields.reserve(fields.size());
  591. }
  592. new_fields.push_back(
  593. {.name_id = field.name_id, .type_inst_id = new_type_inst_id});
  594. }
  595. // TODO: If the new block is identical to the original block, and we know the
  596. // old ID was canonical, return the original ID.
  597. return eval_context.context().struct_type_fields().AddCanonical(new_fields);
  598. }
  599. // The constant value of a specific is the specific with the corresponding
  600. // constant values for its arguments.
  601. static auto GetConstantValue(EvalContext& eval_context,
  602. SemIR::SpecificId specific_id, Phase* phase)
  603. -> SemIR::SpecificId {
  604. if (!specific_id.has_value()) {
  605. return SemIR::SpecificId::None;
  606. }
  607. const auto& specific = eval_context.specifics().Get(specific_id);
  608. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  609. if (!args_id.has_value()) {
  610. return SemIR::SpecificId::None;
  611. }
  612. // Generally, when making a new specific, it's done through MakeSpecific(),
  613. // which will ensure the declaration is resolved.
  614. //
  615. // However, the SpecificId returned here is intentionally left without its
  616. // declaration resolved. Imported instructions with SpecificIds should not
  617. // have the specific's declaration resolved, but other instructions which
  618. // include a new SpecificId should.
  619. //
  620. // The resolving of the specific's declaration will be ensured later when
  621. // evaluating the instruction containing the SpecificId.
  622. if (args_id == specific.args_id) {
  623. return specific_id;
  624. }
  625. return eval_context.context().specifics().GetOrAdd(specific.generic_id,
  626. args_id);
  627. }
  628. static auto GetConstantValue(EvalContext& eval_context,
  629. SemIR::SpecificInterfaceId specific_interface_id,
  630. Phase* phase) -> SemIR::SpecificInterfaceId {
  631. const auto& interface =
  632. eval_context.specific_interfaces().Get(specific_interface_id);
  633. if (!interface.specific_id.has_value()) {
  634. return specific_interface_id;
  635. }
  636. return eval_context.specific_interfaces().Add(
  637. {.interface_id = interface.interface_id,
  638. .specific_id =
  639. GetConstantValue(eval_context, interface.specific_id, phase)});
  640. }
  641. // Like `GetConstantValue` but for a `FacetTypeInfo`.
  642. static auto GetConstantFacetTypeInfo(EvalContext& eval_context,
  643. SemIR::LocId loc_id,
  644. const SemIR::FacetTypeInfo& orig,
  645. Phase* phase) -> SemIR::FacetTypeInfo {
  646. SemIR::FacetTypeInfo info = {};
  647. info.extend_constraints.reserve(orig.extend_constraints.size());
  648. for (const auto& extend : orig.extend_constraints) {
  649. // TODO: Add GetConstantValue for SpecificInterface.
  650. info.extend_constraints.push_back(
  651. {.interface_id = extend.interface_id,
  652. .specific_id =
  653. GetConstantValue(eval_context, extend.specific_id, phase)});
  654. }
  655. info.self_impls_constraints.reserve(orig.self_impls_constraints.size());
  656. for (const auto& self_impls : orig.self_impls_constraints) {
  657. // TODO: Add GetConstantValue for SpecificInterface.
  658. info.self_impls_constraints.push_back(
  659. {.interface_id = self_impls.interface_id,
  660. .specific_id =
  661. GetConstantValue(eval_context, self_impls.specific_id, phase)});
  662. }
  663. info.extend_named_constraints.reserve(orig.extend_named_constraints.size());
  664. for (const auto& extend : orig.extend_named_constraints) {
  665. // TODO: Add GetConstantValue for SpecificNamedConstraint.
  666. info.extend_named_constraints.push_back(
  667. {.named_constraint_id = extend.named_constraint_id,
  668. .specific_id =
  669. GetConstantValue(eval_context, extend.specific_id, phase)});
  670. }
  671. info.self_impls_named_constraints.reserve(
  672. orig.self_impls_named_constraints.size());
  673. for (const auto& self_impls : orig.self_impls_named_constraints) {
  674. // TODO: Add GetConstantValue for SpecificNamedConstraint.
  675. info.self_impls_named_constraints.push_back(
  676. {.named_constraint_id = self_impls.named_constraint_id,
  677. .specific_id =
  678. GetConstantValue(eval_context, self_impls.specific_id, phase)});
  679. }
  680. info.type_impls_interfaces.reserve(orig.type_impls_interfaces.size());
  681. for (const auto& type_impls : orig.type_impls_interfaces) {
  682. info.type_impls_interfaces.push_back(
  683. {.self_type =
  684. GetConstantValue(eval_context, type_impls.self_type, phase),
  685. // TODO: Add GetConstantValue for SpecificInterface.
  686. .specific_interface = {
  687. .interface_id = type_impls.specific_interface.interface_id,
  688. .specific_id = GetConstantValue(
  689. eval_context, type_impls.specific_interface.specific_id,
  690. phase)}});
  691. }
  692. info.type_impls_named_constraints.reserve(
  693. orig.type_impls_named_constraints.size());
  694. for (const auto& type_impls : orig.type_impls_named_constraints) {
  695. info.type_impls_named_constraints.push_back(
  696. {.self_type =
  697. GetConstantValue(eval_context, type_impls.self_type, phase),
  698. // TODO: Add GetConstantValue for SpecificNamedConstraint.
  699. .specific_named_constraint = {
  700. .named_constraint_id =
  701. type_impls.specific_named_constraint.named_constraint_id,
  702. .specific_id = GetConstantValue(
  703. eval_context, type_impls.specific_named_constraint.specific_id,
  704. phase)}});
  705. }
  706. // Rewrite constraints are resolved first before replacing them with their
  707. // canonical instruction, so that in a `WhereExpr` we can work with the
  708. // `ImplWitnessAccess` references to `.Self` on the LHS of the constraints
  709. // rather than the value of the associated constant they reference.
  710. //
  711. // This also implies that we may find `ImplWitnessAccessSubstituted`
  712. // instructions in the LHS and RHS of these constraints, which are preserved
  713. // to maintain them as an unresolved reference to an associated constant, but
  714. // which must be handled gracefully during resolution. They will be replaced
  715. // with the constant value of the `ImplWitnessAccess` below when they are
  716. // substituted with a constant value.
  717. info.rewrite_constraints = orig.rewrite_constraints;
  718. if (!ResolveFacetTypeRewriteConstraints(eval_context.context(), loc_id,
  719. info.rewrite_constraints)) {
  720. *phase = Phase::UnknownDueToError;
  721. }
  722. for (auto& rewrite : info.rewrite_constraints) {
  723. // `where` requirements using `.Self` should not be considered symbolic.
  724. auto lhs_id = RequireConstantValueIgnoringPeriodSelf(eval_context,
  725. rewrite.lhs_id, phase);
  726. auto rhs_id = RequireConstantValueIgnoringPeriodSelf(eval_context,
  727. rewrite.rhs_id, phase);
  728. rewrite = {.lhs_id = lhs_id, .rhs_id = rhs_id};
  729. }
  730. // TODO: Process other requirements.
  731. info.other_requirements = orig.other_requirements;
  732. info.Canonicalize();
  733. return info;
  734. }
  735. static auto GetConstantValue(EvalContext& eval_context,
  736. SemIR::FacetTypeId facet_type_id, Phase* phase)
  737. -> SemIR::FacetTypeId {
  738. SemIR::FacetTypeInfo info = GetConstantFacetTypeInfo(
  739. eval_context, SemIR::LocId::None,
  740. eval_context.facet_types().Get(facet_type_id), phase);
  741. return eval_context.facet_types().Add(info);
  742. }
  743. static auto GetConstantValue(EvalContext& eval_context,
  744. SemIR::EntityNameId entity_name_id, Phase* phase)
  745. -> SemIR::EntityNameId {
  746. const auto& bind_name = eval_context.entity_names().Get(entity_name_id);
  747. Phase name_phase;
  748. if (bind_name.name_id == SemIR::NameId::PeriodSelf) {
  749. name_phase = Phase::PeriodSelfSymbolic;
  750. } else if (!bind_name.bind_index().has_value()) {
  751. name_phase = Phase::Concrete;
  752. } else if (bind_name.is_template) {
  753. name_phase = Phase::TemplateSymbolic;
  754. } else {
  755. name_phase = Phase::CheckedSymbolic;
  756. }
  757. *phase = LatestPhase(*phase, name_phase);
  758. return eval_context.entity_names().MakeCanonical(entity_name_id);
  759. }
  760. // Replaces the specified field of the given typed instruction with its constant
  761. // value, if it has constant phase. Returns true on success, false if the value
  762. // has runtime phase.
  763. template <typename InstT, typename FieldIdT>
  764. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  765. InstT* inst, FieldIdT InstT::* field,
  766. Phase* phase) -> bool {
  767. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  768. if (!unwrapped.has_value() && (inst->*field).has_value()) {
  769. return false;
  770. }
  771. inst->*field = unwrapped;
  772. return IsConstantOrError(*phase);
  773. }
  774. // Function template that can be called with an argument of type `T`. Used below
  775. // to detect which overloads of `GetConstantValue` exist.
  776. template <typename T>
  777. static void Accept(T /*arg*/) {}
  778. // Determines whether a `GetConstantValue` overload exists for a given ID type.
  779. // Note that we do not check whether `GetConstantValue` is *callable* with a
  780. // given ID type, because that would use the `InstId` overload for
  781. // `AbsoluteInstId` and similar wrapper types, which should be left alone.
  782. template <typename IdT>
  783. static constexpr bool HasGetConstantValueOverload = requires {
  784. Accept<auto (*)(EvalContext&, IdT, Phase*)->IdT>(GetConstantValue);
  785. };
  786. using ArgHandlerFnT = auto(EvalContext& context, int32_t arg, Phase* phase)
  787. -> int32_t;
  788. // Returns the arg handler for an `IdKind`.
  789. template <typename... Types>
  790. static auto GetArgHandlerFn(TypeEnum<Types...> id_kind) -> ArgHandlerFnT* {
  791. static constexpr std::array<ArgHandlerFnT*, SemIR::IdKind::NumValues> Table =
  792. {
  793. [](EvalContext& eval_context, int32_t arg, Phase* phase) -> int32_t {
  794. auto id = SemIR::Inst::FromRaw<Types>(arg);
  795. if constexpr (HasGetConstantValueOverload<Types>) {
  796. // If we have a custom `GetConstantValue` overload, call it.
  797. return SemIR::Inst::ToRaw(
  798. GetConstantValue(eval_context, id, phase));
  799. } else {
  800. // Otherwise, we assume the value is already constant.
  801. return arg;
  802. }
  803. }...,
  804. // Invalid and None handling (ordering-sensitive).
  805. [](auto...) -> int32_t { CARBON_FATAL("Unexpected invalid IdKind"); },
  806. [](EvalContext& /*context*/, int32_t arg,
  807. Phase* /*phase*/) -> int32_t { return arg; },
  808. };
  809. return Table[id_kind.ToIndex()];
  810. }
  811. // Given the stored value `arg` of an instruction field and its corresponding
  812. // kind `kind`, returns the constant value to use for that field, if it has a
  813. // constant phase. `*phase` is updated to include the new constant value. If
  814. // the resulting phase is not constant, the returned value is not useful and
  815. // will typically be `NoneIndex`.
  816. static auto GetConstantValueForArg(EvalContext& eval_context,
  817. SemIR::Inst::ArgAndKind arg_and_kind,
  818. Phase* phase) -> int32_t {
  819. return GetArgHandlerFn(arg_and_kind.kind())(eval_context,
  820. arg_and_kind.value(), phase);
  821. }
  822. // Given an instruction, replaces its operands with their constant values from
  823. // the specified evaluation context. `*phase` is updated to describe the
  824. // constant phase of the result. Returns whether `*phase` is a constant phase;
  825. // if not, `inst` may not be fully updated and should not be used.
  826. static auto ReplaceAllFieldsWithConstantValues(EvalContext& eval_context,
  827. SemIR::Inst* inst, Phase* phase)
  828. -> bool {
  829. auto arg0 =
  830. GetConstantValueForArg(eval_context, inst->arg0_and_kind(), phase);
  831. if (!IsConstantOrError(*phase)) {
  832. return false;
  833. }
  834. auto arg1 =
  835. GetConstantValueForArg(eval_context, inst->arg1_and_kind(), phase);
  836. if (!IsConstantOrError(*phase)) {
  837. return false;
  838. }
  839. inst->SetArgs(arg0, arg1);
  840. return true;
  841. }
  842. // Given an instruction and its ID, replaces its type with the corresponding
  843. // value in this evaluation context. Updates `*phase` to describe the phase of
  844. // the result, and returns whether `*phase` is a constant phase.
  845. static auto ReplaceTypeWithConstantValue(EvalContext& eval_context,
  846. SemIR::InstId inst_id,
  847. SemIR::Inst* inst, Phase* phase)
  848. -> bool {
  849. inst->SetType(GetTypeOfInst(eval_context, inst_id, *inst, phase));
  850. return IsConstantOrError(*phase);
  851. }
  852. template <typename InstT>
  853. static auto ReplaceTypeWithConstantValue(EvalContext& eval_context,
  854. SemIR::InstId inst_id, InstT* inst,
  855. Phase* phase) -> bool {
  856. inst->type_id = GetTypeOfInst(eval_context, inst_id, *inst, phase);
  857. return IsConstantOrError(*phase);
  858. }
  859. template <typename... Types>
  860. static auto KindHasGetConstantValueOverload(TypeEnum<Types...> e) -> bool {
  861. static constexpr std::array<bool, SemIR::IdKind::NumTypes> Values = {
  862. (HasGetConstantValueOverload<Types>)...};
  863. return Values[e.ToIndex()];
  864. }
  865. static auto ResolveSpecificDeclForSpecificId(EvalContext& eval_context,
  866. SemIR::SpecificId specific_id)
  867. -> void {
  868. if (!specific_id.has_value()) {
  869. return;
  870. }
  871. const auto& specific = eval_context.specifics().Get(specific_id);
  872. const auto& generic = eval_context.generics().Get(specific.generic_id);
  873. if (specific_id == generic.self_specific_id) {
  874. // Impl witness table construction happens before its generic decl is
  875. // finish, in order to make the table's instructions dependent
  876. // instructions of the Impl's generic. But those instructions can refer to
  877. // the generic's self specific. We can not resolve the specific
  878. // declaration for the self specific until the generic is finished, but it
  879. // is explicitly resolved at that time in `FinishGenericDecl()`.
  880. return;
  881. }
  882. ResolveSpecificDecl(eval_context.context(), eval_context.fallback_loc_id(),
  883. specific_id);
  884. }
  885. // Resolves the specific declarations for a specific id in any field of the
  886. // `inst` instruction.
  887. static auto ResolveSpecificDeclForInst(EvalContext& eval_context,
  888. const SemIR::Inst& inst) -> void {
  889. for (auto arg_and_kind : {inst.arg0_and_kind(), inst.arg1_and_kind()}) {
  890. // This switch must handle any field type that has a GetConstantValue()
  891. // overload which canonicalizes a specific (and thus potentially forms a new
  892. // specific) as part of forming its constant value.
  893. CARBON_KIND_SWITCH(arg_and_kind) {
  894. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  895. const auto& info =
  896. eval_context.context().facet_types().Get(facet_type_id);
  897. for (const auto& interface : info.extend_constraints) {
  898. ResolveSpecificDeclForSpecificId(eval_context, interface.specific_id);
  899. }
  900. for (const auto& interface : info.self_impls_constraints) {
  901. ResolveSpecificDeclForSpecificId(eval_context, interface.specific_id);
  902. }
  903. for (const auto& constraint : info.extend_named_constraints) {
  904. ResolveSpecificDeclForSpecificId(eval_context,
  905. constraint.specific_id);
  906. }
  907. for (const auto& constraint : info.self_impls_named_constraints) {
  908. ResolveSpecificDeclForSpecificId(eval_context,
  909. constraint.specific_id);
  910. }
  911. for (const auto& type_impls : info.type_impls_interfaces) {
  912. ResolveSpecificDeclForSpecificId(
  913. eval_context, type_impls.specific_interface.specific_id);
  914. }
  915. for (const auto& type_impls : info.type_impls_named_constraints) {
  916. ResolveSpecificDeclForSpecificId(
  917. eval_context, type_impls.specific_named_constraint.specific_id);
  918. }
  919. break;
  920. }
  921. case CARBON_KIND(SemIR::SpecificId specific_id): {
  922. ResolveSpecificDeclForSpecificId(eval_context, specific_id);
  923. break;
  924. }
  925. case CARBON_KIND(SemIR::SpecificInterfaceId specific_interface_id): {
  926. ResolveSpecificDeclForSpecificId(eval_context,
  927. eval_context.specific_interfaces()
  928. .Get(specific_interface_id)
  929. .specific_id);
  930. break;
  931. }
  932. // These id types have a GetConstantValue() overload but that overload
  933. // does not canonicalize any SpecificId in the value type.
  934. case SemIR::IdKind::For<SemIR::DestInstId>:
  935. case SemIR::IdKind::For<SemIR::EntityNameId>:
  936. case SemIR::IdKind::For<SemIR::InstBlockId>:
  937. case SemIR::IdKind::For<SemIR::InstId>:
  938. case SemIR::IdKind::For<SemIR::MetaInstId>:
  939. case SemIR::IdKind::For<SemIR::StructTypeFieldsId>:
  940. case SemIR::IdKind::For<SemIR::TypeInstId>:
  941. break;
  942. case SemIR::IdKind::None:
  943. // No arg.
  944. break;
  945. default:
  946. CARBON_CHECK(
  947. !KindHasGetConstantValueOverload(arg_and_kind.kind()),
  948. "Missing case for {0} which has a GetConstantValue() overload",
  949. arg_and_kind.kind());
  950. break;
  951. }
  952. }
  953. }
  954. auto AddImportedConstant(Context& context, SemIR::Inst inst)
  955. -> SemIR::ConstantId {
  956. EvalContext eval_context(&context, SemIR::LocId::None);
  957. CARBON_CHECK(inst.kind().has_type(), "Can't import untyped instructions: {0}",
  958. inst.kind());
  959. Phase phase = GetPhase(context.constant_values(),
  960. context.types().GetConstantId(inst.type_id()));
  961. // We ignore the return value of ReplaceAllFieldsWithConstantValues and just
  962. // propagate runtime and error constant values into the resulting ConstantId.
  963. ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase);
  964. return MakeConstantResult(context, inst, phase);
  965. }
  966. // Performs an index into a homogeneous aggregate, retrieving the specified
  967. // element.
  968. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  969. -> SemIR::ConstantId {
  970. Phase phase = Phase::Concrete;
  971. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  972. if (!index_id.has_value()) {
  973. return MakeNonConstantResult(phase);
  974. }
  975. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  976. if (!index) {
  977. CARBON_CHECK(phase != Phase::Concrete,
  978. "Concrete constant integer should be a literal");
  979. return MakeNonConstantResult(phase);
  980. }
  981. // Array indexing is invalid if the index is constant and out of range,
  982. // regardless of whether the array itself is constant.
  983. const auto& index_val = eval_context.ints().Get(index->int_id);
  984. auto aggregate_type_id = eval_context.GetTypeOfInst(inst.array_id);
  985. if (auto array_type =
  986. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  987. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  988. array_type->bound_id)) {
  989. // This awkward call to `getZExtValue` is a workaround for APInt not
  990. // supporting comparisons between integers of different bit widths.
  991. if (index_val.getActiveBits() > 64 ||
  992. eval_context.ints()
  993. .Get(bound->int_id)
  994. .ule(index_val.getZExtValue())) {
  995. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  996. "array index `{0}` is past the end of type {1}",
  997. TypedInt, SemIR::TypeId);
  998. eval_context.emitter().Emit(
  999. eval_context.GetDiagnosticLoc(inst.index_id), ArrayIndexOutOfBounds,
  1000. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  1001. return SemIR::ErrorInst::ConstantId;
  1002. }
  1003. }
  1004. }
  1005. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  1006. if (!aggregate_id.has_value()) {
  1007. return MakeNonConstantResult(phase);
  1008. }
  1009. auto aggregate =
  1010. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  1011. if (!aggregate) {
  1012. // TODO: Consider forming a symbolic constant or reference constant array
  1013. // index in this case.
  1014. return MakeNonConstantResult(phase);
  1015. }
  1016. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  1017. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  1018. }
  1019. // Performs a conversion between character types, diagnosing if the value
  1020. // doesn't fit in the destination type.
  1021. static auto PerformCheckedCharConvert(Context& context, SemIR::LocId loc_id,
  1022. SemIR::InstId arg_id,
  1023. SemIR::TypeId dest_type_id)
  1024. -> SemIR::ConstantId {
  1025. auto arg = context.insts().GetAs<SemIR::CharLiteralValue>(arg_id);
  1026. // Values over 0x80 require multiple code units in UTF-8.
  1027. if (arg.value.index >= 0x80) {
  1028. CARBON_DIAGNOSTIC(CharTooLargeForType, Error,
  1029. "character value {0} too large for type {1}",
  1030. SemIR::CharId, SemIR::TypeId);
  1031. context.emitter().Emit(loc_id, CharTooLargeForType, arg.value,
  1032. dest_type_id);
  1033. return SemIR::ErrorInst::ConstantId;
  1034. }
  1035. llvm::APInt int_val(8, arg.value.index, /*isSigned=*/false);
  1036. return MakeIntResult(context, dest_type_id, /*is_signed=*/false, int_val);
  1037. }
  1038. // Forms a constant int type as an evaluation result. Requires that width_id is
  1039. // constant.
  1040. static auto MakeIntTypeResult(Context& context, SemIR::LocId loc_id,
  1041. SemIR::IntKind int_kind, SemIR::InstId width_id,
  1042. Phase phase) -> SemIR::ConstantId {
  1043. auto result = SemIR::IntType{.type_id = SemIR::TypeType::TypeId,
  1044. .int_kind = int_kind,
  1045. .bit_width_id = width_id};
  1046. if (!ValidateIntType(context, loc_id, result)) {
  1047. return SemIR::ErrorInst::ConstantId;
  1048. }
  1049. return MakeConstantResult(context, result, phase);
  1050. }
  1051. // Forms a constant float type as an evaluation result. Requires that width_id
  1052. // is constant.
  1053. static auto MakeFloatTypeResult(Context& context, SemIR::LocId loc_id,
  1054. SemIR::InstId width_id, Phase phase)
  1055. -> SemIR::ConstantId {
  1056. auto result = SemIR::FloatType{.type_id = SemIR::TypeType::TypeId,
  1057. .bit_width_id = width_id,
  1058. .float_kind = SemIR::FloatKind::None};
  1059. if (!ValidateFloatTypeAndSetKind(context, loc_id, result)) {
  1060. return SemIR::ErrorInst::ConstantId;
  1061. }
  1062. return MakeConstantResult(context, result, phase);
  1063. }
  1064. // Performs a conversion between integer types, truncating if the value doesn't
  1065. // fit in the destination type.
  1066. static auto PerformIntConvert(Context& context, SemIR::InstId arg_id,
  1067. SemIR::TypeId dest_type_id) -> SemIR::ConstantId {
  1068. auto arg_val =
  1069. context.ints().Get(context.insts().GetAs<SemIR::IntValue>(arg_id).int_id);
  1070. auto [dest_is_signed, bit_width_id] =
  1071. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  1072. if (bit_width_id.has_value()) {
  1073. // TODO: If the value fits in the destination type, reuse the existing
  1074. // int_id rather than recomputing it. This is probably the most common case.
  1075. bool src_is_signed = context.sem_ir().types().IsSignedInt(
  1076. context.insts().Get(arg_id).type_id());
  1077. unsigned width = context.ints().Get(bit_width_id).getZExtValue();
  1078. arg_val =
  1079. src_is_signed ? arg_val.sextOrTrunc(width) : arg_val.zextOrTrunc(width);
  1080. }
  1081. return MakeIntResult(context, dest_type_id, dest_is_signed, arg_val);
  1082. }
  1083. // Performs a conversion between integer types, diagnosing if the value doesn't
  1084. // fit in the destination type.
  1085. static auto PerformCheckedIntConvert(Context& context, SemIR::LocId loc_id,
  1086. SemIR::InstId arg_id,
  1087. SemIR::TypeId dest_type_id)
  1088. -> SemIR::ConstantId {
  1089. auto arg = context.insts().GetAs<SemIR::IntValue>(arg_id);
  1090. auto arg_val = context.ints().Get(arg.int_id);
  1091. auto [is_signed, bit_width_id] =
  1092. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  1093. auto width = bit_width_id.has_value()
  1094. ? context.ints().Get(bit_width_id).getZExtValue()
  1095. : arg_val.getBitWidth();
  1096. if (!is_signed && arg_val.isNegative()) {
  1097. CARBON_DIAGNOSTIC(
  1098. NegativeIntInUnsignedType, Error,
  1099. "negative integer value {0} converted to unsigned type {1}", TypedInt,
  1100. SemIR::TypeId);
  1101. context.emitter().Emit(loc_id, NegativeIntInUnsignedType,
  1102. {.type = arg.type_id, .value = arg_val},
  1103. dest_type_id);
  1104. }
  1105. unsigned arg_non_sign_bits = arg_val.getSignificantBits() - 1;
  1106. if (arg_non_sign_bits + is_signed > width) {
  1107. CARBON_DIAGNOSTIC(IntTooLargeForType, Error,
  1108. "integer value {0} too large for type {1}", TypedInt,
  1109. SemIR::TypeId);
  1110. context.emitter().Emit(loc_id, IntTooLargeForType,
  1111. {.type = arg.type_id, .value = arg_val},
  1112. dest_type_id);
  1113. }
  1114. return MakeConstantResult(
  1115. context, SemIR::IntValue{.type_id = dest_type_id, .int_id = arg.int_id},
  1116. Phase::Concrete);
  1117. }
  1118. // Performs a conversion between floating-point types, diagnosing if the value
  1119. // doesn't fit in the destination type.
  1120. static auto PerformCheckedFloatConvert(Context& context, SemIR::LocId loc_id,
  1121. SemIR::InstId arg_id,
  1122. SemIR::TypeId dest_type_id)
  1123. -> SemIR::ConstantId {
  1124. auto dest_type_object_rep_id = context.types().GetObjectRepr(dest_type_id);
  1125. CARBON_CHECK(dest_type_object_rep_id.has_value(),
  1126. "Conversion to incomplete type");
  1127. auto dest_float_type =
  1128. context.types().TryGetAs<SemIR::FloatType>(dest_type_object_rep_id);
  1129. CARBON_CHECK(dest_float_type || context.types().Is<SemIR::FloatLiteralType>(
  1130. dest_type_object_rep_id));
  1131. if (auto literal =
  1132. context.insts().TryGetAs<SemIR::FloatLiteralValue>(arg_id)) {
  1133. if (!dest_float_type) {
  1134. return MakeConstantResult(
  1135. context,
  1136. SemIR::FloatLiteralValue{.type_id = dest_type_id,
  1137. .real_id = literal->real_id},
  1138. Phase::Concrete);
  1139. }
  1140. // Convert the real literal to an llvm::APFloat and add it to the floats
  1141. // ValueStore. In the future this would use an arbitrary precision Rational
  1142. // type.
  1143. //
  1144. // TODO: Implement Carbon's actual implicit conversion rules for
  1145. // floating-point constants, as per the design
  1146. // docs/design/expressions/implicit_conversions.md
  1147. auto real_value = context.sem_ir().reals().Get(literal->real_id);
  1148. // Convert the real value to a string.
  1149. llvm::SmallString<64> str;
  1150. real_value.mantissa.toString(str, real_value.is_decimal ? 10 : 16,
  1151. /*signed=*/false, /*formatAsCLiteral=*/true);
  1152. str += real_value.is_decimal ? "e" : "p";
  1153. real_value.exponent.toStringSigned(str);
  1154. // Convert the string to an APFloat.
  1155. llvm::APFloat result(dest_float_type->float_kind.Semantics());
  1156. // TODO: The implementation of this conversion effectively converts back to
  1157. // APInts, but unfortunately the conversion from integer mantissa and
  1158. // exponent in IEEEFloat::roundSignificandWithExponent is not part of the
  1159. // public API.
  1160. auto status =
  1161. result.convertFromString(str, llvm::APFloat::rmNearestTiesToEven);
  1162. if (auto error = status.takeError()) {
  1163. // The literal we create should always successfully parse.
  1164. CARBON_FATAL("Float literal parsing failed: {0}",
  1165. toString(std::move(error)));
  1166. }
  1167. if (status.get() & llvm::APFloat::opOverflow) {
  1168. CARBON_DIAGNOSTIC(FloatLiteralTooLargeForType, Error,
  1169. "value {0} too large for floating-point type {1}",
  1170. RealId, SemIR::TypeId);
  1171. context.emitter().Emit(loc_id, FloatLiteralTooLargeForType,
  1172. literal->real_id, dest_type_id);
  1173. return SemIR::ErrorInst::ConstantId;
  1174. }
  1175. return MakeFloatResult(context, dest_type_id, std::move(result));
  1176. }
  1177. if (!dest_float_type) {
  1178. context.TODO(loc_id, "conversion from float to float literal");
  1179. return SemIR::ErrorInst::ConstantId;
  1180. }
  1181. // Convert to the destination float semantics.
  1182. auto arg = context.insts().GetAs<SemIR::FloatValue>(arg_id);
  1183. llvm::APFloat result = context.floats().Get(arg.float_id);
  1184. bool loses_info;
  1185. auto status = result.convert(dest_float_type->float_kind.Semantics(),
  1186. llvm::APFloat::rmNearestTiesToEven, &loses_info);
  1187. if (status & llvm::APFloat::opOverflow) {
  1188. CARBON_DIAGNOSTIC(FloatTooLargeForType, Error,
  1189. "value {0} too large for floating-point type {1}",
  1190. llvm::APFloat, SemIR::TypeId);
  1191. context.emitter().Emit(loc_id, FloatTooLargeForType,
  1192. context.floats().Get(arg.float_id), dest_type_id);
  1193. return SemIR::ErrorInst::ConstantId;
  1194. }
  1195. return MakeFloatResult(context, dest_type_id, std::move(result));
  1196. }
  1197. // Issues a diagnostic for a compile-time division by zero.
  1198. static auto DiagnoseDivisionByZero(Context& context, SemIR::LocId loc_id)
  1199. -> void {
  1200. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  1201. context.emitter().Emit(loc_id, CompileTimeDivisionByZero);
  1202. }
  1203. // Get an integer at a suitable bit-width: either `bit_width_id` if it has a
  1204. // value, or the canonical width from the value store if not.
  1205. static auto GetIntAtSuitableWidth(Context& context, IntId int_id,
  1206. IntId bit_width_id) -> llvm::APInt {
  1207. return bit_width_id.has_value()
  1208. ? context.ints().GetAtWidth(int_id, bit_width_id)
  1209. : context.ints().Get(int_id);
  1210. }
  1211. // Performs a builtin unary integer -> integer operation.
  1212. static auto PerformBuiltinUnaryIntOp(Context& context, SemIR::LocId loc_id,
  1213. SemIR::BuiltinFunctionKind builtin_kind,
  1214. SemIR::InstId arg_id)
  1215. -> SemIR::ConstantId {
  1216. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  1217. auto [is_signed, bit_width_id] =
  1218. context.sem_ir().types().GetIntTypeInfo(op.type_id);
  1219. llvm::APInt op_val = GetIntAtSuitableWidth(context, op.int_id, bit_width_id);
  1220. switch (builtin_kind) {
  1221. case SemIR::BuiltinFunctionKind::IntSNegate:
  1222. if (op_val.isMinSignedValue()) {
  1223. if (bit_width_id.has_value()) {
  1224. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  1225. "integer overflow in negation of {0}", TypedInt);
  1226. context.emitter().Emit(loc_id, CompileTimeIntegerNegateOverflow,
  1227. {.type = op.type_id, .value = op_val});
  1228. } else {
  1229. // Widen the integer so we don't overflow into the sign bit.
  1230. op_val = op_val.sext(op_val.getBitWidth() +
  1231. llvm::APInt::APINT_BITS_PER_WORD);
  1232. }
  1233. }
  1234. op_val.negate();
  1235. break;
  1236. case SemIR::BuiltinFunctionKind::IntUNegate:
  1237. CARBON_CHECK(bit_width_id.has_value(), "Unsigned negate on unsized int");
  1238. op_val.negate();
  1239. break;
  1240. case SemIR::BuiltinFunctionKind::IntComplement:
  1241. // TODO: Should we have separate builtins for signed and unsigned
  1242. // complement? Like with signed/unsigned negate, these operations do
  1243. // different things to the integer value, even though they do the same
  1244. // thing to the bits. We treat IntLiteral complement as signed complement,
  1245. // given that the result of unsigned complement depends on the bit width.
  1246. op_val.flipAllBits();
  1247. break;
  1248. default:
  1249. CARBON_FATAL("Unexpected builtin kind");
  1250. }
  1251. return MakeIntResult(context, op.type_id, is_signed, std::move(op_val));
  1252. }
  1253. namespace {
  1254. // A pair of APInts that are the operands of a binary operator. We use an
  1255. // aggregate rather than `std::pair` to allow RVO of the individual ints.
  1256. struct APIntBinaryOperands {
  1257. llvm::APInt lhs;
  1258. llvm::APInt rhs;
  1259. };
  1260. } // namespace
  1261. // Get a pair of integers at the same suitable bit-width: either their actual
  1262. // width if they have a fixed width, or the smallest canonical width in which
  1263. // they both fit otherwise.
  1264. static auto GetIntsAtSuitableWidth(Context& context, IntId lhs_id, IntId rhs_id,
  1265. IntId bit_width_id) -> APIntBinaryOperands {
  1266. // Unsized operands: take the wider of the bit widths.
  1267. if (!bit_width_id.has_value()) {
  1268. APIntBinaryOperands result = {.lhs = context.ints().Get(lhs_id),
  1269. .rhs = context.ints().Get(rhs_id)};
  1270. if (result.lhs.getBitWidth() != result.rhs.getBitWidth()) {
  1271. if (result.lhs.getBitWidth() > result.rhs.getBitWidth()) {
  1272. result.rhs = result.rhs.sext(result.lhs.getBitWidth());
  1273. } else {
  1274. result.lhs = result.lhs.sext(result.rhs.getBitWidth());
  1275. }
  1276. }
  1277. return result;
  1278. }
  1279. return {.lhs = context.ints().GetAtWidth(lhs_id, bit_width_id),
  1280. .rhs = context.ints().GetAtWidth(rhs_id, bit_width_id)};
  1281. }
  1282. namespace {
  1283. // The result of performing a binary int operation.
  1284. struct BinaryIntOpResult {
  1285. llvm::APInt result_val;
  1286. bool overflow;
  1287. Lex::TokenKind op_token;
  1288. };
  1289. } // namespace
  1290. // Computes the result of a homogeneous binary (int, int) -> int operation.
  1291. static auto ComputeBinaryIntOpResult(SemIR::BuiltinFunctionKind builtin_kind,
  1292. const llvm::APInt& lhs_val,
  1293. const llvm::APInt& rhs_val)
  1294. -> BinaryIntOpResult {
  1295. llvm::APInt result_val;
  1296. bool overflow = false;
  1297. Lex::TokenKind op_token = Lex::TokenKind::Not;
  1298. switch (builtin_kind) {
  1299. // Arithmetic.
  1300. case SemIR::BuiltinFunctionKind::IntSAdd:
  1301. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  1302. op_token = Lex::TokenKind::Plus;
  1303. break;
  1304. case SemIR::BuiltinFunctionKind::IntSSub:
  1305. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  1306. op_token = Lex::TokenKind::Minus;
  1307. break;
  1308. case SemIR::BuiltinFunctionKind::IntSMul:
  1309. result_val = lhs_val.smul_ov(rhs_val, overflow);
  1310. op_token = Lex::TokenKind::Star;
  1311. break;
  1312. case SemIR::BuiltinFunctionKind::IntSDiv:
  1313. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  1314. op_token = Lex::TokenKind::Slash;
  1315. break;
  1316. case SemIR::BuiltinFunctionKind::IntSMod:
  1317. result_val = lhs_val.srem(rhs_val);
  1318. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  1319. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  1320. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  1321. op_token = Lex::TokenKind::Percent;
  1322. break;
  1323. case SemIR::BuiltinFunctionKind::IntUAdd:
  1324. result_val = lhs_val + rhs_val;
  1325. op_token = Lex::TokenKind::Plus;
  1326. break;
  1327. case SemIR::BuiltinFunctionKind::IntUSub:
  1328. result_val = lhs_val - rhs_val;
  1329. op_token = Lex::TokenKind::Minus;
  1330. break;
  1331. case SemIR::BuiltinFunctionKind::IntUMul:
  1332. result_val = lhs_val * rhs_val;
  1333. op_token = Lex::TokenKind::Star;
  1334. break;
  1335. case SemIR::BuiltinFunctionKind::IntUDiv:
  1336. result_val = lhs_val.udiv(rhs_val);
  1337. op_token = Lex::TokenKind::Slash;
  1338. break;
  1339. case SemIR::BuiltinFunctionKind::IntUMod:
  1340. result_val = lhs_val.urem(rhs_val);
  1341. op_token = Lex::TokenKind::Percent;
  1342. break;
  1343. // Bitwise.
  1344. case SemIR::BuiltinFunctionKind::IntAnd:
  1345. result_val = lhs_val & rhs_val;
  1346. op_token = Lex::TokenKind::And;
  1347. break;
  1348. case SemIR::BuiltinFunctionKind::IntOr:
  1349. result_val = lhs_val | rhs_val;
  1350. op_token = Lex::TokenKind::Pipe;
  1351. break;
  1352. case SemIR::BuiltinFunctionKind::IntXor:
  1353. result_val = lhs_val ^ rhs_val;
  1354. op_token = Lex::TokenKind::Caret;
  1355. break;
  1356. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1357. case SemIR::BuiltinFunctionKind::IntRightShift:
  1358. CARBON_FATAL("Non-homogeneous operation handled separately.");
  1359. default:
  1360. CARBON_FATAL("Unexpected operation kind.");
  1361. }
  1362. return {.result_val = std::move(result_val),
  1363. .overflow = overflow,
  1364. .op_token = op_token};
  1365. }
  1366. // Performs a builtin integer bit shift operation.
  1367. static auto PerformBuiltinIntShiftOp(Context& context, SemIR::LocId loc_id,
  1368. SemIR::BuiltinFunctionKind builtin_kind,
  1369. SemIR::InstId lhs_id, SemIR::InstId rhs_id)
  1370. -> SemIR::ConstantId {
  1371. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1372. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1373. auto [lhs_is_signed, lhs_bit_width_id] =
  1374. context.sem_ir().types().GetIntTypeInfo(lhs.type_id);
  1375. llvm::APInt lhs_val =
  1376. GetIntAtSuitableWidth(context, lhs.int_id, lhs_bit_width_id);
  1377. const auto& rhs_orig_val = context.ints().Get(rhs.int_id);
  1378. if (lhs_bit_width_id.has_value() && rhs_orig_val.uge(lhs_val.getBitWidth())) {
  1379. CARBON_DIAGNOSTIC(
  1380. CompileTimeShiftOutOfRange, Error,
  1381. "shift distance >= type width of {0} in `{1} {2:<<|>>} {3}`", unsigned,
  1382. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1383. context.emitter().Emit(
  1384. loc_id, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  1385. {.type = lhs.type_id, .value = lhs_val},
  1386. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1387. {.type = rhs.type_id, .value = rhs_orig_val});
  1388. // TODO: Is it useful to recover by returning 0 or -1?
  1389. return SemIR::ErrorInst::ConstantId;
  1390. }
  1391. if (rhs_orig_val.isNegative() &&
  1392. context.sem_ir().types().IsSignedInt(rhs.type_id)) {
  1393. CARBON_DIAGNOSTIC(CompileTimeShiftNegative, Error,
  1394. "shift distance negative in `{0} {1:<<|>>} {2}`",
  1395. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1396. context.emitter().Emit(
  1397. loc_id, CompileTimeShiftNegative,
  1398. {.type = lhs.type_id, .value = lhs_val},
  1399. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1400. {.type = rhs.type_id, .value = rhs_orig_val});
  1401. // TODO: Is it useful to recover by returning 0 or -1?
  1402. return SemIR::ErrorInst::ConstantId;
  1403. }
  1404. llvm::APInt result_val;
  1405. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  1406. if (!lhs_bit_width_id.has_value() && !lhs_val.isZero()) {
  1407. // Ensure we don't generate a ridiculously large integer through a bit
  1408. // shift.
  1409. auto width = rhs_orig_val.trySExtValue();
  1410. if (!width ||
  1411. *width > IntStore::MaxIntWidth - lhs_val.getSignificantBits()) {
  1412. CARBON_DIAGNOSTIC(CompileTimeUnsizedShiftOutOfRange, Error,
  1413. "shift distance of {0} would result in an "
  1414. "integer whose width is greater than the "
  1415. "maximum supported width of {1}",
  1416. TypedInt, int);
  1417. context.emitter().Emit(loc_id, CompileTimeUnsizedShiftOutOfRange,
  1418. {.type = rhs.type_id, .value = rhs_orig_val},
  1419. IntStore::MaxIntWidth);
  1420. return SemIR::ErrorInst::ConstantId;
  1421. }
  1422. lhs_val = lhs_val.sext(
  1423. IntStore::CanonicalBitWidth(lhs_val.getSignificantBits() + *width));
  1424. }
  1425. result_val =
  1426. lhs_val.shl(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1427. } else if (lhs_is_signed) {
  1428. result_val =
  1429. lhs_val.ashr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1430. } else {
  1431. CARBON_CHECK(lhs_bit_width_id.has_value(), "Logical shift on unsized int");
  1432. result_val =
  1433. lhs_val.lshr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1434. }
  1435. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  1436. std::move(result_val));
  1437. }
  1438. // Performs a homogeneous builtin binary integer -> integer operation.
  1439. static auto PerformBuiltinBinaryIntOp(Context& context, SemIR::LocId loc_id,
  1440. SemIR::BuiltinFunctionKind builtin_kind,
  1441. SemIR::InstId lhs_id,
  1442. SemIR::InstId rhs_id)
  1443. -> SemIR::ConstantId {
  1444. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1445. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1446. CARBON_CHECK(rhs.type_id == lhs.type_id, "Heterogeneous builtin integer op!");
  1447. auto type_id = lhs.type_id;
  1448. auto [is_signed, bit_width_id] =
  1449. context.sem_ir().types().GetIntTypeInfo(type_id);
  1450. auto [lhs_val, rhs_val] =
  1451. GetIntsAtSuitableWidth(context, lhs.int_id, rhs.int_id, bit_width_id);
  1452. // Check for division by zero.
  1453. switch (builtin_kind) {
  1454. case SemIR::BuiltinFunctionKind::IntSDiv:
  1455. case SemIR::BuiltinFunctionKind::IntSMod:
  1456. case SemIR::BuiltinFunctionKind::IntUDiv:
  1457. case SemIR::BuiltinFunctionKind::IntUMod:
  1458. if (rhs_val.isZero()) {
  1459. DiagnoseDivisionByZero(context, loc_id);
  1460. return SemIR::ErrorInst::ConstantId;
  1461. }
  1462. break;
  1463. default:
  1464. break;
  1465. }
  1466. BinaryIntOpResult result =
  1467. ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1468. if (result.overflow && !bit_width_id.has_value()) {
  1469. // Retry with a larger bit width. Most operations can only overflow by one
  1470. // bit, but signed n-bit multiplication can overflow to 2n-1 bits. We don't
  1471. // need to handle unsigned multiplication here because it's not permitted
  1472. // for unsized integers.
  1473. //
  1474. // Note that we speculatively first perform the calculation in the width of
  1475. // the wider operand: smaller operations are faster and overflow to a wider
  1476. // integer is unlikely to be needed, especially given that the width will
  1477. // have been rounded up to a multiple of 64 bits by the int store.
  1478. CARBON_CHECK(builtin_kind != SemIR::BuiltinFunctionKind::IntUMul,
  1479. "Unsigned arithmetic requires a fixed bitwidth");
  1480. int new_width =
  1481. builtin_kind == SemIR::BuiltinFunctionKind::IntSMul
  1482. ? lhs_val.getBitWidth() * 2
  1483. : IntStore::CanonicalBitWidth(lhs_val.getBitWidth() + 1);
  1484. new_width = std::min(new_width, IntStore::MaxIntWidth);
  1485. lhs_val = context.ints().GetAtWidth(lhs.int_id, new_width);
  1486. rhs_val = context.ints().GetAtWidth(rhs.int_id, new_width);
  1487. // Note that this can in theory still overflow if we limited `new_width` to
  1488. // `MaxIntWidth`. In that case we fall through to the signed overflow
  1489. // diagnostic below.
  1490. result = ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1491. CARBON_CHECK(!result.overflow || new_width == IntStore::MaxIntWidth);
  1492. }
  1493. if (result.overflow) {
  1494. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  1495. "integer overflow in calculation `{0} {1} {2}`", TypedInt,
  1496. Lex::TokenKind, TypedInt);
  1497. context.emitter().Emit(loc_id, CompileTimeIntegerOverflow,
  1498. {.type = type_id, .value = lhs_val}, result.op_token,
  1499. {.type = type_id, .value = rhs_val});
  1500. }
  1501. return MakeIntResult(context, type_id, is_signed,
  1502. std::move(result.result_val));
  1503. }
  1504. // Performs a builtin integer comparison.
  1505. static auto PerformBuiltinIntComparison(Context& context,
  1506. SemIR::BuiltinFunctionKind builtin_kind,
  1507. SemIR::InstId lhs_id,
  1508. SemIR::InstId rhs_id,
  1509. SemIR::TypeId bool_type_id)
  1510. -> SemIR::ConstantId {
  1511. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1512. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1513. llvm::APInt lhs_val = context.ints().Get(lhs.int_id);
  1514. llvm::APInt rhs_val = context.ints().Get(rhs.int_id);
  1515. bool result;
  1516. switch (builtin_kind) {
  1517. case SemIR::BuiltinFunctionKind::IntEq:
  1518. result = (lhs_val == rhs_val);
  1519. break;
  1520. case SemIR::BuiltinFunctionKind::IntNeq:
  1521. result = (lhs_val != rhs_val);
  1522. break;
  1523. case SemIR::BuiltinFunctionKind::IntLess:
  1524. result = lhs_val.slt(rhs_val);
  1525. break;
  1526. case SemIR::BuiltinFunctionKind::IntLessEq:
  1527. result = lhs_val.sle(rhs_val);
  1528. break;
  1529. case SemIR::BuiltinFunctionKind::IntGreater:
  1530. result = lhs_val.sgt(rhs_val);
  1531. break;
  1532. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  1533. result = lhs_val.sge(rhs_val);
  1534. break;
  1535. default:
  1536. CARBON_FATAL("Unexpected operation kind.");
  1537. }
  1538. return MakeBoolResult(context, bool_type_id, result);
  1539. }
  1540. // Performs a builtin unary float -> float operation.
  1541. static auto PerformBuiltinUnaryFloatOp(Context& context,
  1542. SemIR::BuiltinFunctionKind builtin_kind,
  1543. SemIR::InstId arg_id)
  1544. -> SemIR::ConstantId {
  1545. auto op = context.insts().GetAs<SemIR::FloatValue>(arg_id);
  1546. auto op_val = context.floats().Get(op.float_id);
  1547. switch (builtin_kind) {
  1548. case SemIR::BuiltinFunctionKind::FloatNegate:
  1549. op_val.changeSign();
  1550. break;
  1551. default:
  1552. CARBON_FATAL("Unexpected builtin kind");
  1553. }
  1554. return MakeFloatResult(context, op.type_id, std::move(op_val));
  1555. }
  1556. // Performs a builtin binary float -> float operation.
  1557. static auto PerformBuiltinBinaryFloatOp(Context& context,
  1558. SemIR::BuiltinFunctionKind builtin_kind,
  1559. SemIR::InstId lhs_id,
  1560. SemIR::InstId rhs_id)
  1561. -> SemIR::ConstantId {
  1562. auto lhs = context.insts().GetAs<SemIR::FloatValue>(lhs_id);
  1563. auto rhs = context.insts().GetAs<SemIR::FloatValue>(rhs_id);
  1564. auto lhs_val = context.floats().Get(lhs.float_id);
  1565. auto rhs_val = context.floats().Get(rhs.float_id);
  1566. llvm::APFloat result_val(lhs_val.getSemantics());
  1567. switch (builtin_kind) {
  1568. case SemIR::BuiltinFunctionKind::FloatAdd:
  1569. result_val = lhs_val + rhs_val;
  1570. break;
  1571. case SemIR::BuiltinFunctionKind::FloatSub:
  1572. result_val = lhs_val - rhs_val;
  1573. break;
  1574. case SemIR::BuiltinFunctionKind::FloatMul:
  1575. result_val = lhs_val * rhs_val;
  1576. break;
  1577. case SemIR::BuiltinFunctionKind::FloatDiv:
  1578. result_val = lhs_val / rhs_val;
  1579. break;
  1580. default:
  1581. CARBON_FATAL("Unexpected operation kind.");
  1582. }
  1583. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  1584. }
  1585. // Performs a builtin float comparison.
  1586. static auto PerformBuiltinFloatComparison(
  1587. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1588. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  1589. -> SemIR::ConstantId {
  1590. auto lhs = context.insts().GetAs<SemIR::FloatValue>(lhs_id);
  1591. auto rhs = context.insts().GetAs<SemIR::FloatValue>(rhs_id);
  1592. const auto& lhs_val = context.floats().Get(lhs.float_id);
  1593. const auto& rhs_val = context.floats().Get(rhs.float_id);
  1594. bool result;
  1595. switch (builtin_kind) {
  1596. case SemIR::BuiltinFunctionKind::FloatEq:
  1597. result = (lhs_val == rhs_val);
  1598. break;
  1599. case SemIR::BuiltinFunctionKind::FloatNeq:
  1600. result = (lhs_val != rhs_val);
  1601. break;
  1602. case SemIR::BuiltinFunctionKind::FloatLess:
  1603. result = lhs_val < rhs_val;
  1604. break;
  1605. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1606. result = lhs_val <= rhs_val;
  1607. break;
  1608. case SemIR::BuiltinFunctionKind::FloatGreater:
  1609. result = lhs_val > rhs_val;
  1610. break;
  1611. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  1612. result = lhs_val >= rhs_val;
  1613. break;
  1614. default:
  1615. CARBON_FATAL("Unexpected operation kind.");
  1616. }
  1617. return MakeBoolResult(context, bool_type_id, result);
  1618. }
  1619. // Performs a builtin boolean comparison.
  1620. static auto PerformBuiltinBoolComparison(
  1621. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1622. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id) {
  1623. bool lhs = context.insts().GetAs<SemIR::BoolLiteral>(lhs_id).value.ToBool();
  1624. bool rhs = context.insts().GetAs<SemIR::BoolLiteral>(rhs_id).value.ToBool();
  1625. return MakeBoolResult(context, bool_type_id,
  1626. builtin_kind == SemIR::BuiltinFunctionKind::BoolEq
  1627. ? lhs == rhs
  1628. : lhs != rhs);
  1629. }
  1630. // Converts a call argument to a FacetTypeId.
  1631. static auto ArgToFacetTypeId(Context& context, SemIR::LocId loc_id,
  1632. SemIR::InstId arg_id) -> SemIR::FacetTypeId {
  1633. auto type_arg_id = context.types().GetAsTypeInstId(arg_id);
  1634. if (auto facet_type =
  1635. context.insts().TryGetAs<SemIR::FacetType>(type_arg_id)) {
  1636. return facet_type->facet_type_id;
  1637. }
  1638. CARBON_DIAGNOSTIC(FacetTypeRequiredForTypeAndOperator, Error,
  1639. "non-facet type {0} combined with `&` operator",
  1640. SemIR::TypeId);
  1641. // TODO: Find a location for the lhs or rhs specifically, instead of
  1642. // the whole thing. If that's not possible we can change the text to
  1643. // say if it's referring to the left or the right side for the error.
  1644. // The `arg_id` instruction has no location in it for some reason.
  1645. context.emitter().Emit(loc_id, FacetTypeRequiredForTypeAndOperator,
  1646. context.types().GetTypeIdForTypeInstId(type_arg_id));
  1647. return SemIR::FacetTypeId::None;
  1648. }
  1649. // Returns a constant for a call to a builtin function.
  1650. static auto MakeConstantForBuiltinCall(EvalContext& eval_context,
  1651. SemIR::LocId loc_id, SemIR::Call call,
  1652. SemIR::BuiltinFunctionKind builtin_kind,
  1653. llvm::ArrayRef<SemIR::InstId> arg_ids,
  1654. Phase phase) -> SemIR::ConstantId {
  1655. auto& context = eval_context.context();
  1656. switch (builtin_kind) {
  1657. case SemIR::BuiltinFunctionKind::None:
  1658. CARBON_FATAL("Not a builtin function.");
  1659. case SemIR::BuiltinFunctionKind::NoOp: {
  1660. return MakeEmptyTupleResult(eval_context);
  1661. }
  1662. case SemIR::BuiltinFunctionKind::PrimitiveCopy: {
  1663. return context.constant_values().Get(arg_ids[0]);
  1664. }
  1665. case SemIR::BuiltinFunctionKind::StringAt: {
  1666. Phase phase = Phase::Concrete;
  1667. auto str_id = GetConstantValue(eval_context, arg_ids[0], &phase);
  1668. auto index_id = GetConstantValue(eval_context, arg_ids[1], &phase);
  1669. if (phase != Phase::Concrete) {
  1670. return MakeNonConstantResult(phase);
  1671. }
  1672. auto str_struct = eval_context.insts().GetAs<SemIR::StructValue>(str_id);
  1673. auto elements = eval_context.inst_blocks().Get(str_struct.elements_id);
  1674. // String struct has two fields: a pointer to the string data and the
  1675. // length.
  1676. CARBON_CHECK(elements.size() == 2, "String struct should have 2 fields.");
  1677. auto string_literal = eval_context.insts().GetAs<SemIR::StringLiteral>(
  1678. eval_context.constant_values().GetConstantInstId(elements[0]));
  1679. const auto& string_value =
  1680. eval_context.sem_ir().string_literal_values().Get(
  1681. string_literal.string_literal_id);
  1682. auto index_inst = eval_context.insts().GetAs<SemIR::IntValue>(index_id);
  1683. const auto& index_val = eval_context.ints().Get(index_inst.int_id);
  1684. if (index_val.isNegative()) {
  1685. CARBON_DIAGNOSTIC(StringAtIndexNegative, Error,
  1686. "index `{0}` is negative.", TypedInt);
  1687. context.emitter().Emit(
  1688. loc_id, StringAtIndexNegative,
  1689. {.type = eval_context.insts().Get(index_id).type_id(),
  1690. .value = index_val});
  1691. return SemIR::ConstantId::NotConstant;
  1692. }
  1693. if (index_val.getZExtValue() >= string_value.size()) {
  1694. CARBON_DIAGNOSTIC(
  1695. StringAtIndexOutOfBounds, Error,
  1696. "string index `{0}` is out of bounds; string has length {1}.",
  1697. TypedInt, size_t);
  1698. context.emitter().Emit(
  1699. loc_id, StringAtIndexOutOfBounds,
  1700. {.type = eval_context.insts().Get(index_id).type_id(),
  1701. .value = index_val},
  1702. string_value.size());
  1703. return SemIR::ConstantId::NotConstant;
  1704. }
  1705. auto char_value =
  1706. static_cast<uint8_t>(string_value[index_val.getZExtValue()]);
  1707. auto int_id = eval_context.ints().Add(
  1708. llvm::APSInt(llvm::APInt(32, char_value), /*isUnsigned=*/false));
  1709. return MakeConstantResult(
  1710. eval_context.context(),
  1711. SemIR::IntValue{.type_id = call.type_id, .int_id = int_id}, phase);
  1712. }
  1713. case SemIR::BuiltinFunctionKind::MakeUninitialized:
  1714. case SemIR::BuiltinFunctionKind::PrintChar:
  1715. case SemIR::BuiltinFunctionKind::PrintInt:
  1716. case SemIR::BuiltinFunctionKind::ReadChar:
  1717. case SemIR::BuiltinFunctionKind::FloatAddAssign:
  1718. case SemIR::BuiltinFunctionKind::FloatSubAssign:
  1719. case SemIR::BuiltinFunctionKind::FloatMulAssign:
  1720. case SemIR::BuiltinFunctionKind::FloatDivAssign:
  1721. case SemIR::BuiltinFunctionKind::IntSAddAssign:
  1722. case SemIR::BuiltinFunctionKind::IntSSubAssign:
  1723. case SemIR::BuiltinFunctionKind::IntSMulAssign:
  1724. case SemIR::BuiltinFunctionKind::IntSDivAssign:
  1725. case SemIR::BuiltinFunctionKind::IntSModAssign:
  1726. case SemIR::BuiltinFunctionKind::IntUAddAssign:
  1727. case SemIR::BuiltinFunctionKind::IntUSubAssign:
  1728. case SemIR::BuiltinFunctionKind::IntUMulAssign:
  1729. case SemIR::BuiltinFunctionKind::IntUDivAssign:
  1730. case SemIR::BuiltinFunctionKind::IntUModAssign:
  1731. case SemIR::BuiltinFunctionKind::IntAndAssign:
  1732. case SemIR::BuiltinFunctionKind::IntOrAssign:
  1733. case SemIR::BuiltinFunctionKind::IntXorAssign:
  1734. case SemIR::BuiltinFunctionKind::IntLeftShiftAssign:
  1735. case SemIR::BuiltinFunctionKind::IntRightShiftAssign:
  1736. case SemIR::BuiltinFunctionKind::PointerMakeNull:
  1737. case SemIR::BuiltinFunctionKind::PointerIsNull:
  1738. case SemIR::BuiltinFunctionKind::PointerUnsafeConvert:
  1739. case SemIR::BuiltinFunctionKind::CppStdInitializerListMake: {
  1740. // These are runtime-only builtins.
  1741. // TODO: Consider tracking this on the `BuiltinFunctionKind`.
  1742. return SemIR::ConstantId::NotConstant;
  1743. }
  1744. case SemIR::BuiltinFunctionKind::TypeAnd: {
  1745. CARBON_CHECK(arg_ids.size() == 2);
  1746. auto lhs_facet_type_id = ArgToFacetTypeId(context, loc_id, arg_ids[0]);
  1747. auto rhs_facet_type_id = ArgToFacetTypeId(context, loc_id, arg_ids[1]);
  1748. // Allow errors to be diagnosed for both sides of the operator before
  1749. // returning here if any error occurred on either side.
  1750. if (!lhs_facet_type_id.has_value() || !rhs_facet_type_id.has_value()) {
  1751. return SemIR::ErrorInst::ConstantId;
  1752. }
  1753. // Reuse one of the argument instructions if nothing has changed.
  1754. if (lhs_facet_type_id == rhs_facet_type_id) {
  1755. return context.types().GetConstantId(
  1756. context.types().GetTypeIdForTypeInstId(arg_ids[0]));
  1757. }
  1758. auto combined_info = SemIR::FacetTypeInfo::Combine(
  1759. context.facet_types().Get(lhs_facet_type_id),
  1760. context.facet_types().Get(rhs_facet_type_id));
  1761. if (!ResolveFacetTypeRewriteConstraints(
  1762. eval_context.context(), loc_id,
  1763. combined_info.rewrite_constraints)) {
  1764. phase = Phase::UnknownDueToError;
  1765. }
  1766. combined_info.Canonicalize();
  1767. return MakeFacetTypeResult(eval_context.context(), combined_info, phase);
  1768. }
  1769. case SemIR::BuiltinFunctionKind::CharLiteralMakeType: {
  1770. return context.constant_values().Get(SemIR::CharLiteralType::TypeInstId);
  1771. }
  1772. case SemIR::BuiltinFunctionKind::FloatLiteralMakeType: {
  1773. return context.constant_values().Get(SemIR::FloatLiteralType::TypeInstId);
  1774. }
  1775. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  1776. return context.constant_values().Get(SemIR::IntLiteralType::TypeInstId);
  1777. }
  1778. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  1779. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Signed,
  1780. arg_ids[0], phase);
  1781. }
  1782. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  1783. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Unsigned,
  1784. arg_ids[0], phase);
  1785. }
  1786. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  1787. return MakeFloatTypeResult(context, loc_id, arg_ids[0], phase);
  1788. }
  1789. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  1790. return context.constant_values().Get(SemIR::BoolType::TypeInstId);
  1791. }
  1792. case SemIR::BuiltinFunctionKind::MaybeUnformedMakeType: {
  1793. return MakeConstantResult(
  1794. context,
  1795. SemIR::MaybeUnformedType{
  1796. .type_id = SemIR::TypeType::TypeId,
  1797. .inner_id = context.types().GetAsTypeInstId(arg_ids[0])},
  1798. phase);
  1799. }
  1800. case SemIR::BuiltinFunctionKind::FormMakeType: {
  1801. return context.constant_values().Get(SemIR::FormType::TypeInstId);
  1802. }
  1803. // Character conversions.
  1804. case SemIR::BuiltinFunctionKind::CharConvertChecked: {
  1805. if (phase != Phase::Concrete) {
  1806. return MakeConstantResult(context, call, phase);
  1807. }
  1808. return PerformCheckedCharConvert(context, loc_id, arg_ids[0],
  1809. call.type_id);
  1810. }
  1811. // Integer conversions.
  1812. case SemIR::BuiltinFunctionKind::IntConvertChar: {
  1813. if (phase != Phase::Concrete) {
  1814. return MakeConstantResult(context, call, phase);
  1815. }
  1816. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1817. }
  1818. case SemIR::BuiltinFunctionKind::IntConvert: {
  1819. if (phase != Phase::Concrete) {
  1820. return MakeConstantResult(context, call, phase);
  1821. }
  1822. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1823. }
  1824. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  1825. if (phase != Phase::Concrete) {
  1826. return MakeConstantResult(context, call, phase);
  1827. }
  1828. return PerformCheckedIntConvert(context, loc_id, arg_ids[0],
  1829. call.type_id);
  1830. }
  1831. // Unary integer -> integer operations.
  1832. case SemIR::BuiltinFunctionKind::IntSNegate:
  1833. case SemIR::BuiltinFunctionKind::IntUNegate:
  1834. case SemIR::BuiltinFunctionKind::IntComplement: {
  1835. if (phase != Phase::Concrete) {
  1836. break;
  1837. }
  1838. return PerformBuiltinUnaryIntOp(context, loc_id, builtin_kind,
  1839. arg_ids[0]);
  1840. }
  1841. // Homogeneous binary integer -> integer operations.
  1842. case SemIR::BuiltinFunctionKind::IntSAdd:
  1843. case SemIR::BuiltinFunctionKind::IntSSub:
  1844. case SemIR::BuiltinFunctionKind::IntSMul:
  1845. case SemIR::BuiltinFunctionKind::IntSDiv:
  1846. case SemIR::BuiltinFunctionKind::IntSMod:
  1847. case SemIR::BuiltinFunctionKind::IntUAdd:
  1848. case SemIR::BuiltinFunctionKind::IntUSub:
  1849. case SemIR::BuiltinFunctionKind::IntUMul:
  1850. case SemIR::BuiltinFunctionKind::IntUDiv:
  1851. case SemIR::BuiltinFunctionKind::IntUMod:
  1852. case SemIR::BuiltinFunctionKind::IntAnd:
  1853. case SemIR::BuiltinFunctionKind::IntOr:
  1854. case SemIR::BuiltinFunctionKind::IntXor: {
  1855. if (phase != Phase::Concrete) {
  1856. break;
  1857. }
  1858. return PerformBuiltinBinaryIntOp(context, loc_id, builtin_kind,
  1859. arg_ids[0], arg_ids[1]);
  1860. }
  1861. // Bit shift operations.
  1862. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1863. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1864. if (phase != Phase::Concrete) {
  1865. break;
  1866. }
  1867. return PerformBuiltinIntShiftOp(context, loc_id, builtin_kind, arg_ids[0],
  1868. arg_ids[1]);
  1869. }
  1870. // Integer comparisons.
  1871. case SemIR::BuiltinFunctionKind::IntEq:
  1872. case SemIR::BuiltinFunctionKind::IntNeq:
  1873. case SemIR::BuiltinFunctionKind::IntLess:
  1874. case SemIR::BuiltinFunctionKind::IntLessEq:
  1875. case SemIR::BuiltinFunctionKind::IntGreater:
  1876. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1877. if (phase != Phase::Concrete) {
  1878. break;
  1879. }
  1880. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1881. arg_ids[1], call.type_id);
  1882. }
  1883. // Floating-point conversions.
  1884. case SemIR::BuiltinFunctionKind::FloatConvertChecked: {
  1885. if (phase != Phase::Concrete) {
  1886. return MakeConstantResult(context, call, phase);
  1887. }
  1888. return PerformCheckedFloatConvert(context, loc_id, arg_ids[0],
  1889. call.type_id);
  1890. }
  1891. // Unary float -> float operations.
  1892. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1893. if (phase != Phase::Concrete) {
  1894. break;
  1895. }
  1896. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1897. }
  1898. // Binary float -> float operations.
  1899. case SemIR::BuiltinFunctionKind::FloatAdd:
  1900. case SemIR::BuiltinFunctionKind::FloatSub:
  1901. case SemIR::BuiltinFunctionKind::FloatMul:
  1902. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1903. if (phase != Phase::Concrete) {
  1904. break;
  1905. }
  1906. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1907. arg_ids[1]);
  1908. }
  1909. // Float comparisons.
  1910. case SemIR::BuiltinFunctionKind::FloatEq:
  1911. case SemIR::BuiltinFunctionKind::FloatNeq:
  1912. case SemIR::BuiltinFunctionKind::FloatLess:
  1913. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1914. case SemIR::BuiltinFunctionKind::FloatGreater:
  1915. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1916. if (phase != Phase::Concrete) {
  1917. break;
  1918. }
  1919. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1920. arg_ids[1], call.type_id);
  1921. }
  1922. // Bool comparisons.
  1923. case SemIR::BuiltinFunctionKind::BoolEq:
  1924. case SemIR::BuiltinFunctionKind::BoolNeq: {
  1925. if (phase != Phase::Concrete) {
  1926. break;
  1927. }
  1928. return PerformBuiltinBoolComparison(context, builtin_kind, arg_ids[0],
  1929. arg_ids[1], call.type_id);
  1930. }
  1931. }
  1932. return SemIR::ConstantId::NotConstant;
  1933. }
  1934. static auto TryEvalCall(EvalContext& outer_eval_context, SemIR::LocId loc_id,
  1935. const SemIR::Function& function,
  1936. SemIR::SpecificId specific_id,
  1937. SemIR::InstBlockId args_id) -> SemIR::ConstantId;
  1938. // Returns the range of parameter indexes that contain the return storage for
  1939. // this function call.
  1940. static auto GetReturnStorageParamIndexRange(EvalContext& eval_context,
  1941. const SemIR::Callee& callee)
  1942. -> std::pair<int, int> {
  1943. if (const auto* callee_function =
  1944. std::get_if<SemIR::CalleeFunction>(&callee)) {
  1945. const auto& function =
  1946. eval_context.functions().Get(callee_function->function_id);
  1947. return {function.call_param_ranges.return_begin().index,
  1948. function.call_param_ranges.return_end().index};
  1949. }
  1950. return {0, 0};
  1951. }
  1952. // Replace the `args_id` field of a call with its constant value. The return
  1953. // storage argument, if any, is instead replaced with `None`.
  1954. static auto ReplaceCallArgsFieldWithConstantValue(EvalContext& eval_context,
  1955. const SemIR::Callee& callee,
  1956. SemIR::Call* call,
  1957. Phase* phase) -> bool {
  1958. auto return_storage_param_index_range =
  1959. GetReturnStorageParamIndexRange(eval_context, callee);
  1960. auto args_id = GetConstantBlockValueIgnoringIndexRange(
  1961. eval_context, call->args_id, phase, return_storage_param_index_range);
  1962. if (!args_id.has_value() && call->args_id.has_value()) {
  1963. return false;
  1964. }
  1965. call->args_id = args_id;
  1966. return IsConstantOrError(*phase);
  1967. }
  1968. // Makes a constant for a call instruction.
  1969. static auto MakeConstantForCall(EvalContext& eval_context,
  1970. SemIR::InstId inst_id, SemIR::Call call)
  1971. -> SemIR::ConstantId {
  1972. Phase phase = Phase::Concrete;
  1973. // A call with an invalid argument list is used to represent an erroneous
  1974. // call.
  1975. //
  1976. // TODO: Use a better representation for this.
  1977. if (call.args_id == SemIR::InstBlockId::None) {
  1978. return SemIR::ErrorInst::ConstantId;
  1979. }
  1980. // If the callee is a C++ thunk, modify the `call` to directly call
  1981. // the thunk's callee.
  1982. MaybeModifyCppThunkCallForConstEval(eval_context.context(), &call);
  1983. // Find the constant value of the callee.
  1984. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1985. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1986. auto callee = SemIR::GetCallee(eval_context.sem_ir(), call.callee_id);
  1987. const SemIR::Function* function = nullptr;
  1988. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1989. auto evaluation_mode = SemIR::Function::EvaluationMode::None;
  1990. if (auto* callee_function = std::get_if<SemIR::CalleeFunction>(&callee)) {
  1991. function = &eval_context.functions().Get(callee_function->function_id);
  1992. builtin_kind = function->builtin_function_kind();
  1993. evaluation_mode = function->evaluation_mode;
  1994. // Calls to builtins and to `eval` or `musteval` functions might be
  1995. // constant.
  1996. if (builtin_kind == SemIR::BuiltinFunctionKind::None &&
  1997. evaluation_mode == SemIR::Function::EvaluationMode::None) {
  1998. return SemIR::ConstantId::NotConstant;
  1999. }
  2000. } else {
  2001. // Calls to non-functions, such as calls to generic entity names, might be
  2002. // constant.
  2003. }
  2004. // Find the argument values and the return type.
  2005. bool has_constant_operands =
  2006. has_constant_callee &&
  2007. ReplaceTypeWithConstantValue(eval_context, inst_id, &call, &phase) &&
  2008. ReplaceCallArgsFieldWithConstantValue(eval_context, callee, &call,
  2009. &phase);
  2010. if (phase == Phase::UnknownDueToError) {
  2011. return SemIR::ErrorInst::ConstantId;
  2012. }
  2013. // If any operand of the call is non-constant, the call is non-constant.
  2014. // TODO: Some builtin calls might allow some operands to be non-constant.
  2015. if (!has_constant_operands) {
  2016. if (builtin_kind.IsCompTimeOnly(
  2017. eval_context.sem_ir(), eval_context.inst_blocks().Get(call.args_id),
  2018. call.type_id) ||
  2019. evaluation_mode == SemIR::Function::EvaluationMode::MustEval) {
  2020. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  2021. "non-constant call to compile-time-only function");
  2022. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  2023. "compile-time-only function declared here");
  2024. const auto& function = eval_context.functions().Get(
  2025. std::get<SemIR::CalleeFunction>(callee).function_id);
  2026. eval_context.emitter()
  2027. .Build(inst_id, NonConstantCallToCompTimeOnlyFunction)
  2028. .Note(function.latest_decl_id(), CompTimeOnlyFunctionHere)
  2029. .Emit();
  2030. }
  2031. return SemIR::ConstantId::NotConstant;
  2032. }
  2033. // Handle calls to builtins.
  2034. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  2035. return MakeConstantForBuiltinCall(
  2036. eval_context, SemIR::LocId(inst_id), call, builtin_kind,
  2037. eval_context.inst_blocks().Get(call.args_id), phase);
  2038. }
  2039. // Handle calls to `eval` and `musteval` functions.
  2040. if (evaluation_mode != SemIR::Function::EvaluationMode::None) {
  2041. // A non-concrete call to `eval` or `musteval` is a template symbolic
  2042. // constant, regardless of the phase of the arguments.
  2043. if (phase != Phase::Concrete) {
  2044. CARBON_CHECK(phase <= Phase::TemplateSymbolic);
  2045. return MakeConstantResult(eval_context.context(), call,
  2046. Phase::TemplateSymbolic);
  2047. }
  2048. // TODO: Instead of performing the call immediately, add it to a work queue
  2049. // and do it non-recursively.
  2050. return TryEvalCall(
  2051. eval_context, SemIR::LocId(inst_id), *function,
  2052. std::get<SemIR::CalleeFunction>(callee).resolved_specific_id,
  2053. call.args_id);
  2054. }
  2055. return SemIR::ConstantId::NotConstant;
  2056. }
  2057. // Given an instruction, compute its phase based on its operands.
  2058. static auto ComputeInstPhase(Context& context, SemIR::Inst inst) -> Phase {
  2059. EvalContext eval_context(&context, SemIR::LocId::None);
  2060. auto phase = GetPhase(context.constant_values(),
  2061. context.types().GetConstantId(inst.type_id()));
  2062. GetConstantValueForArg(eval_context, inst.arg0_and_kind(), &phase);
  2063. GetConstantValueForArg(eval_context, inst.arg1_and_kind(), &phase);
  2064. CARBON_CHECK(IsConstantOrError(phase));
  2065. return phase;
  2066. }
  2067. // Convert a ConstantEvalResult to a ConstantId. Factored out of
  2068. // TryEvalTypedInst to avoid repeated instantiation of common code.
  2069. static auto ConvertEvalResultToConstantId(Context& context,
  2070. ConstantEvalResult result,
  2071. SemIR::InstKind orig_inst_kind,
  2072. Phase orig_phase)
  2073. -> SemIR::ConstantId {
  2074. if (result.is_new()) {
  2075. auto is_symbolic_only =
  2076. orig_inst_kind.constant_kind() == SemIR::InstConstantKind::SymbolicOnly;
  2077. auto new_phase = result.same_phase_as_inst()
  2078. ? orig_phase
  2079. : ComputeInstPhase(context, result.new_inst());
  2080. CARBON_CHECK(!is_symbolic_only || new_phase > Phase::Concrete ||
  2081. result.new_inst().kind() != orig_inst_kind,
  2082. "SymbolicOnly instruction `{0}` has a concrete value",
  2083. orig_inst_kind);
  2084. return MakeConstantResult(context, result.new_inst(), new_phase);
  2085. }
  2086. return result.existing();
  2087. }
  2088. // Evaluates an instruction of a known type in an evaluation context. The
  2089. // default behavior of this function depends on the constant kind of the
  2090. // instruction:
  2091. //
  2092. // - InstConstantKind::Never: returns ConstantId::NotConstant.
  2093. // - InstConstantKind::Indirect, SymbolicOnly, SymbolicOrReference,
  2094. // Conditional: evaluates all the operands of the instruction, and calls
  2095. // `EvalConstantInst` to evaluate the resulting constant instruction.
  2096. // - InstConstantKind::WheneverPossible, Always: evaluates all the operands of
  2097. // the instruction, and produces the resulting constant instruction as the
  2098. // result.
  2099. // - InstConstantKind::Unique: returns the `inst_id` as the resulting
  2100. // constant.
  2101. //
  2102. // Returns an error constant ID if any of the nested evaluations fail, and
  2103. // returns NotConstant if any of the nested evaluations is non-constant.
  2104. //
  2105. // This template is explicitly specialized for instructions that need special
  2106. // handling.
  2107. template <typename InstT>
  2108. static auto TryEvalTypedInst(EvalContext& eval_context, SemIR::InstId inst_id,
  2109. SemIR::Inst inst) -> SemIR::ConstantId {
  2110. constexpr auto ConstantKind = InstT::Kind.constant_kind();
  2111. if constexpr (ConstantKind == SemIR::InstConstantKind::Never) {
  2112. return SemIR::ConstantId::NotConstant;
  2113. } else if constexpr (ConstantKind == SemIR::InstConstantKind::AlwaysUnique) {
  2114. CARBON_CHECK(inst_id.has_value());
  2115. return SemIR::ConstantId::ForConcreteConstant(inst_id);
  2116. } else {
  2117. // Build a constant instruction by replacing each non-constant operand with
  2118. // its constant value.
  2119. Phase phase = Phase::Concrete;
  2120. if ((SemIR::Internal::HasTypeIdMember<InstT> &&
  2121. !ReplaceTypeWithConstantValue(eval_context, inst_id, &inst, &phase)) ||
  2122. !ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  2123. if constexpr (ConstantKind == SemIR::InstConstantKind::Always) {
  2124. CARBON_FATAL("{0} should always be constant", InstT::Kind);
  2125. }
  2126. return SemIR::ConstantId::NotConstant;
  2127. }
  2128. // If any operand of the instruction has an error in it, the instruction
  2129. // itself evaluates to an error.
  2130. if (phase == Phase::UnknownDueToError) {
  2131. return SemIR::ErrorInst::ConstantId;
  2132. }
  2133. // When canonicalizing a SpecificId, we defer resolving the specific's
  2134. // declaration until here, to avoid resolving declarations from imported
  2135. // specifics. (Imported instructions are not evaluated.)
  2136. ResolveSpecificDeclForInst(eval_context, inst);
  2137. if constexpr (ConstantKind == SemIR::InstConstantKind::Always ||
  2138. ConstantKind == SemIR::InstConstantKind::WheneverPossible) {
  2139. return MakeConstantResult(eval_context.context(), inst, phase);
  2140. } else if constexpr (ConstantKind == SemIR::InstConstantKind::InstAction) {
  2141. auto result_inst_id = PerformDelayedAction(
  2142. eval_context.context(), SemIR::LocId(inst_id), inst.As<InstT>());
  2143. if (result_inst_id.has_value()) {
  2144. // The result is an instruction.
  2145. return MakeConstantResult(
  2146. eval_context.context(),
  2147. SemIR::InstValue{
  2148. .type_id = GetSingletonType(eval_context.context(),
  2149. SemIR::InstType::TypeInstId),
  2150. .inst_id = result_inst_id},
  2151. Phase::Concrete);
  2152. }
  2153. // Couldn't perform the action because it's still dependent.
  2154. return MakeConstantResult(eval_context.context(), inst,
  2155. Phase::TemplateSymbolic);
  2156. } else if constexpr (InstT::Kind.constant_needs_inst_id() !=
  2157. SemIR::InstConstantNeedsInstIdKind::No) {
  2158. CARBON_CHECK(inst_id.has_value());
  2159. return ConvertEvalResultToConstantId(
  2160. eval_context.context(),
  2161. EvalConstantInst(eval_context.context(), inst_id, inst.As<InstT>()),
  2162. InstT::Kind, phase);
  2163. } else {
  2164. return ConvertEvalResultToConstantId(
  2165. eval_context.context(),
  2166. EvalConstantInst(eval_context.context(), inst.As<InstT>()),
  2167. InstT::Kind, phase);
  2168. }
  2169. }
  2170. }
  2171. // Specialize evaluation for array indexing because we want to check the index
  2172. // expression even if the array expression is non-constant.
  2173. template <>
  2174. auto TryEvalTypedInst<SemIR::ArrayIndex>(EvalContext& eval_context,
  2175. SemIR::InstId /*inst_id*/,
  2176. SemIR::Inst inst)
  2177. -> SemIR::ConstantId {
  2178. return PerformArrayIndex(eval_context, inst.As<SemIR::ArrayIndex>());
  2179. }
  2180. // Specialize evaluation for function calls because we want to check the callee
  2181. // expression even if an argument expression is non-constant, and because we
  2182. // will eventually want to perform control flow handling here.
  2183. template <>
  2184. auto TryEvalTypedInst<SemIR::Call>(EvalContext& eval_context,
  2185. SemIR::InstId inst_id, SemIR::Inst inst)
  2186. -> SemIR::ConstantId {
  2187. return MakeConstantForCall(eval_context, inst_id, inst.As<SemIR::Call>());
  2188. }
  2189. // ImportRefLoaded can have a constant value, but it's owned and maintained by
  2190. // `import_ref.cpp`, not by us.
  2191. // TODO: Rearrange how `ImportRefLoaded` instructions are created so we never
  2192. // call this.
  2193. template <>
  2194. auto TryEvalTypedInst<SemIR::ImportRefLoaded>(EvalContext& /*eval_context*/,
  2195. SemIR::InstId /*inst_id*/,
  2196. SemIR::Inst /*inst*/)
  2197. -> SemIR::ConstantId {
  2198. return SemIR::ConstantId::NotConstant;
  2199. }
  2200. // Symbolic bindings are a special case because they can reach into the eval
  2201. // context and produce a context-specific value.
  2202. template <>
  2203. auto TryEvalTypedInst<SemIR::SymbolicBinding>(EvalContext& eval_context,
  2204. SemIR::InstId inst_id,
  2205. SemIR::Inst inst)
  2206. -> SemIR::ConstantId {
  2207. auto bind = inst.As<SemIR::SymbolicBinding>();
  2208. // If we know which specific we're evaluating within and this is an argument
  2209. // of that specific, its constant value is the corresponding argument value.
  2210. const auto& bind_name = eval_context.entity_names().Get(bind.entity_name_id);
  2211. if (bind_name.bind_index().has_value()) {
  2212. if (auto value =
  2213. eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  2214. value.has_value()) {
  2215. return value;
  2216. }
  2217. }
  2218. // The constant form of a symbolic binding is an idealized form of the
  2219. // original, with no equivalent value.
  2220. Phase phase = Phase::Concrete;
  2221. bind.value_id = SemIR::InstId::None;
  2222. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &bind, &phase) ||
  2223. !ReplaceFieldWithConstantValue(eval_context, &bind,
  2224. &SemIR::SymbolicBinding::entity_name_id,
  2225. &phase)) {
  2226. return SemIR::ConstantId::NotConstant;
  2227. }
  2228. // This correctly handles `Phase::UnknownDueToError`.
  2229. return MakeConstantResult(eval_context.context(), bind, phase);
  2230. }
  2231. template <>
  2232. auto TryEvalTypedInst<SemIR::SymbolicBindingType>(EvalContext& eval_context,
  2233. SemIR::InstId inst_id,
  2234. SemIR::Inst inst)
  2235. -> SemIR::ConstantId {
  2236. // If a specific provides a new value for the binding with `entity_name_id`,
  2237. // the SymbolicBindingType is evaluated for that new value.
  2238. const auto& bind_name = eval_context.entity_names().Get(
  2239. inst.As<SemIR::SymbolicBindingType>().entity_name_id);
  2240. if (bind_name.bind_index().has_value()) {
  2241. if (auto value =
  2242. eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  2243. value.has_value()) {
  2244. auto value_inst_id = eval_context.constant_values().GetInstId(value);
  2245. // A SymbolicBindingType can evaluate to a FacetAccessType if the new
  2246. // value of the entity is a facet value that that does not have a concrete
  2247. // type (a FacetType) and does not have a new EntityName to point to (a
  2248. // SymbolicBinding).
  2249. auto access = SemIR::FacetAccessType{
  2250. .type_id = SemIR::TypeType::TypeId,
  2251. .facet_value_inst_id = value_inst_id,
  2252. };
  2253. return ConvertEvalResultToConstantId(
  2254. eval_context.context(),
  2255. EvalConstantInst(eval_context.context(), access),
  2256. SemIR::SymbolicBindingType::Kind,
  2257. ComputeInstPhase(eval_context.context(), access));
  2258. }
  2259. }
  2260. Phase phase = Phase::Concrete;
  2261. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &inst, &phase) ||
  2262. !ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  2263. return SemIR::ConstantId::NotConstant;
  2264. }
  2265. // Propagate error phase after getting the constant value for all fields.
  2266. if (phase == Phase::UnknownDueToError) {
  2267. return SemIR::ErrorInst::ConstantId;
  2268. }
  2269. // Evaluation of SymbolicBindingType.
  2270. //
  2271. // Like FacetAccessType, a SymbolicBindingType of a FacetValue just evaluates
  2272. // to the type inside.
  2273. //
  2274. // TODO: Look in ScopeStack with the entity_name_id to find the facet value
  2275. // and get its constant value in the current specific context. The
  2276. // facet_value_inst_id will go away.
  2277. if (auto facet_value = eval_context.insts().TryGetAs<SemIR::FacetValue>(
  2278. inst.As<SemIR::SymbolicBindingType>().facet_value_inst_id)) {
  2279. return eval_context.constant_values().Get(facet_value->type_inst_id);
  2280. }
  2281. return MakeConstantResult(eval_context.context(), inst, phase);
  2282. }
  2283. template <>
  2284. auto TryEvalTypedInst<SemIR::Temporary>(EvalContext& eval_context,
  2285. SemIR::InstId inst_id, SemIR::Inst inst)
  2286. -> SemIR::ConstantId {
  2287. auto temporary = inst.As<SemIR::Temporary>();
  2288. temporary.storage_id = SemIR::InstId::None;
  2289. Phase phase = Phase::Concrete;
  2290. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &temporary,
  2291. &phase) ||
  2292. !ReplaceFieldWithConstantValue(eval_context, &temporary,
  2293. &SemIR::Temporary::init_id, &phase)) {
  2294. return SemIR::ConstantId::NotConstant;
  2295. }
  2296. return MakeConstantResult(eval_context.context(), temporary, phase);
  2297. }
  2298. // Returns whether `const_id` is the same constant facet value as
  2299. // `facet_value_inst_id`.
  2300. //
  2301. // Compares with the canonical facet value of `const_id`, dropping any `as type`
  2302. // conversions.
  2303. static auto IsSameFacetValue(Context& context, SemIR::ConstantId const_id,
  2304. SemIR::InstId facet_value_inst_id) -> bool {
  2305. auto canon_const_id = GetCanonicalFacetOrTypeValue(context, const_id);
  2306. return canon_const_id == context.constant_values().Get(facet_value_inst_id);
  2307. }
  2308. // TODO: Convert this to an EvalConstantInst function. This will require
  2309. // providing a `GetConstantValue` overload for a requirement block.
  2310. template <>
  2311. auto TryEvalTypedInst<SemIR::WhereExpr>(EvalContext& eval_context,
  2312. SemIR::InstId where_inst_id,
  2313. SemIR::Inst inst) -> SemIR::ConstantId {
  2314. auto typed_inst = inst.As<SemIR::WhereExpr>();
  2315. Phase phase = Phase::Concrete;
  2316. SemIR::FacetTypeInfo info;
  2317. if (typed_inst.period_self_id == SemIR::ErrorInst::InstId) {
  2318. return SemIR::ErrorInst::ConstantId;
  2319. }
  2320. // Add the constraints from the `WhereExpr` instruction into `info`.
  2321. if (typed_inst.requirements_id.has_value()) {
  2322. auto insts = eval_context.inst_blocks().Get(typed_inst.requirements_id);
  2323. // Note that these requirement instructions don't have a constant value, but
  2324. // they contain only canonical instructions.
  2325. for (auto inst_id : insts) {
  2326. if (auto base =
  2327. eval_context.insts().TryGetAs<SemIR::RequirementBaseFacetType>(
  2328. inst_id)) {
  2329. if (base->base_type_inst_id == SemIR::ErrorInst::TypeInstId) {
  2330. return SemIR::ErrorInst::ConstantId;
  2331. }
  2332. if (auto base_facet_type =
  2333. eval_context.insts().TryGetAs<SemIR::FacetType>(
  2334. base->base_type_inst_id)) {
  2335. const auto& base_info =
  2336. eval_context.facet_types().Get(base_facet_type->facet_type_id);
  2337. info.extend_constraints.append(base_info.extend_constraints);
  2338. info.self_impls_constraints.append(base_info.self_impls_constraints);
  2339. info.type_impls_interfaces.append(base_info.type_impls_interfaces);
  2340. info.type_impls_named_constraints.append(
  2341. base_info.type_impls_named_constraints);
  2342. info.rewrite_constraints.append(base_info.rewrite_constraints);
  2343. info.other_requirements |= base_info.other_requirements;
  2344. }
  2345. } else if (auto rewrite =
  2346. eval_context.insts().TryGetAs<SemIR::RequirementRewrite>(
  2347. inst_id)) {
  2348. info.rewrite_constraints.push_back(
  2349. {.lhs_id = rewrite->lhs_id, .rhs_id = rewrite->rhs_id});
  2350. } else if (auto impls =
  2351. eval_context.insts().TryGetAs<SemIR::RequirementImpls>(
  2352. inst_id)) {
  2353. SemIR::ConstantId lhs_const_id =
  2354. eval_context.GetConstantValue(impls->lhs_id);
  2355. SemIR::ConstantId rhs_const_id =
  2356. eval_context.GetConstantValue(impls->rhs_id);
  2357. if (IsSameFacetValue(eval_context.context(), lhs_const_id,
  2358. typed_inst.period_self_id)) {
  2359. auto rhs_inst_id =
  2360. eval_context.constant_values().GetInstId(rhs_const_id);
  2361. if (rhs_inst_id == SemIR::ErrorInst::InstId) {
  2362. // `.Self impls <error>`.
  2363. return SemIR::ErrorInst::ConstantId;
  2364. } else if (rhs_inst_id == SemIR::TypeType::TypeInstId) {
  2365. // `.Self impls type` -> nothing to do.
  2366. } else {
  2367. auto facet_type = eval_context.insts().GetAs<SemIR::FacetType>(
  2368. RequireConstantValue(eval_context, impls->rhs_id, &phase));
  2369. const auto& more_info =
  2370. eval_context.facet_types().Get(facet_type.facet_type_id);
  2371. // The way to prevent lookup into the interface requirements of a
  2372. // facet type is to put it to the right of a `.Self impls`, which we
  2373. // accomplish by putting them into `self_impls_constraints`.
  2374. llvm::append_range(info.self_impls_constraints,
  2375. more_info.extend_constraints);
  2376. llvm::append_range(info.self_impls_constraints,
  2377. more_info.self_impls_constraints);
  2378. llvm::append_range(info.self_impls_named_constraints,
  2379. more_info.extend_named_constraints);
  2380. llvm::append_range(info.self_impls_named_constraints,
  2381. more_info.self_impls_named_constraints);
  2382. // If `.Self impls Z` and Z implies `C impls Y`, then the facet type
  2383. // of `.Self` also knows `C impls Y`.
  2384. llvm::append_range(info.type_impls_interfaces,
  2385. more_info.type_impls_interfaces);
  2386. llvm::append_range(info.type_impls_named_constraints,
  2387. more_info.type_impls_named_constraints);
  2388. // Other requirements are copied in.
  2389. llvm::append_range(info.rewrite_constraints,
  2390. more_info.rewrite_constraints);
  2391. info.other_requirements |= more_info.other_requirements;
  2392. }
  2393. } else {
  2394. // TODO: Handle `impls` constraints beyond `.Self impls`.
  2395. info.other_requirements = true;
  2396. }
  2397. } else {
  2398. // TODO: Handle other requirements.
  2399. info.other_requirements = true;
  2400. }
  2401. }
  2402. }
  2403. auto const_info = GetConstantFacetTypeInfo(
  2404. eval_context, SemIR::LocId(where_inst_id), info, &phase);
  2405. return MakeFacetTypeResult(eval_context.context(), const_info, phase);
  2406. }
  2407. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  2408. static auto TryEvalInstInContext(EvalContext& eval_context,
  2409. SemIR::InstId inst_id, SemIR::Inst inst)
  2410. -> SemIR::ConstantId {
  2411. using EvalInstFn =
  2412. auto(EvalContext & eval_context, SemIR::InstId inst_id, SemIR::Inst inst)
  2413. ->SemIR::ConstantId;
  2414. static constexpr EvalInstFn* EvalInstFns[] = {
  2415. #define CARBON_SEM_IR_INST_KIND(Kind) &TryEvalTypedInst<SemIR::Kind>,
  2416. #include "toolchain/sem_ir/inst_kind.def"
  2417. };
  2418. [[clang::musttail]] return EvalInstFns[inst.kind().AsInt()](eval_context,
  2419. inst_id, inst);
  2420. }
  2421. auto TryEvalInstUnsafe(Context& context, SemIR::InstId inst_id,
  2422. SemIR::Inst inst) -> SemIR::ConstantId {
  2423. EvalContext eval_context(&context, SemIR::LocId(inst_id));
  2424. return TryEvalInstInContext(eval_context, inst_id, inst);
  2425. }
  2426. auto TryEvalBlockForSpecific(Context& context, SemIR::LocId loc_id,
  2427. SemIR::SpecificId specific_id,
  2428. SemIR::GenericInstIndex::Region region)
  2429. -> std::pair<SemIR::InstBlockId, bool> {
  2430. auto generic_id = context.specifics().Get(specific_id).generic_id;
  2431. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  2432. auto eval_block = context.inst_blocks().Get(eval_block_id);
  2433. llvm::SmallVector<SemIR::InstId> result;
  2434. result.resize(eval_block.size(), SemIR::InstId::None);
  2435. EvalContext eval_context(&context, loc_id, specific_id,
  2436. SpecificEvalInfo{
  2437. .region = region,
  2438. .values = result,
  2439. });
  2440. Diagnostics::ContextScope diagnostic_context(
  2441. &context.emitter(), [&](auto& builder) {
  2442. CARBON_DIAGNOSTIC(ResolvingSpecificHere, SoftContext,
  2443. "unable to monomorphize specific {0}",
  2444. SemIR::SpecificId);
  2445. builder.Context(loc_id, ResolvingSpecificHere, specific_id);
  2446. });
  2447. bool has_error = false;
  2448. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  2449. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  2450. context.insts().Get(inst_id));
  2451. if (const_id == SemIR::ErrorInst::ConstantId) {
  2452. has_error = true;
  2453. }
  2454. result[i] = context.constant_values().GetInstId(const_id);
  2455. CARBON_CHECK(result[i].has_value(), "Failed to evaluate {0} in eval block",
  2456. context.insts().Get(inst_id));
  2457. }
  2458. return {context.inst_blocks().Add(result), has_error};
  2459. }
  2460. // Information about the function call we are currently executing. Unlike
  2461. // evaluation, execution sequentially interprets instructions, and can handle
  2462. // control flow and (eventually) side effects and mutable state.
  2463. class FunctionExecContext : public EvalContext {
  2464. public:
  2465. // A block argument passed to `BranchWithArg`.
  2466. struct BlockArgValue {
  2467. SemIR::InstBlockId block_id = SemIR::InstBlockId::None;
  2468. SemIR::ConstantId arg_id = SemIR::ConstantId::None;
  2469. };
  2470. FunctionExecContext(Context* context, SemIR::LocId loc_id,
  2471. SemIR::SpecificId specific_id,
  2472. Map<SemIR::InstId, SemIR::ConstantId>* locals,
  2473. SemIR::InstBlockId args_id)
  2474. : EvalContext(context, loc_id, specific_id,
  2475. LocalEvalInfo{.locals = locals}),
  2476. args_(context->inst_blocks().Get(args_id)) {}
  2477. // Returns the argument values supplied in the call to the function.
  2478. auto args() const -> llvm::ArrayRef<SemIR::InstId> { return args_; }
  2479. using EvalContext::locals;
  2480. // Branch control flow to the given block. This replaces the innermost block
  2481. // in the block stack, but doesn't affect any enclosing blocks.
  2482. auto BranchTo(SemIR::InstBlockId block_id) -> void {
  2483. blocks_.back() = inst_blocks().Get(block_id);
  2484. }
  2485. // Push a new block to be executed immediately. After the block finishes,
  2486. // control will resume after the current instruction.
  2487. auto PushBlock(SemIR::InstBlockId block_id) -> void {
  2488. blocks_.push_back(inst_blocks().Get(block_id));
  2489. }
  2490. // Pops and returns the next instruction to be executed.
  2491. auto PopNextInstId() -> SemIR::InstId {
  2492. while (blocks_.back().empty()) {
  2493. blocks_.pop_back();
  2494. CARBON_CHECK(!blocks_.empty(), "Fell off end of function");
  2495. }
  2496. return blocks_.back().consume_front();
  2497. }
  2498. // Sets the most recent block argument value provided by a `BranchWithArg`.
  2499. // This can later be retrieved by a `BlockArg`.
  2500. auto SetCurrentBlockArgValue(BlockArgValue arg) -> void {
  2501. current_block_arg_value_ = arg;
  2502. }
  2503. // Returns the most recent block argument value provided by a `BranchWithArg`.
  2504. auto current_block_arg_value() const -> BlockArgValue {
  2505. return current_block_arg_value_;
  2506. }
  2507. private:
  2508. // The stack of code blocks that we are currently evaluating. This is kept as
  2509. // a stack so that we can schedule the function body to execute after the decl
  2510. // block and so that we can handle `SpliceBlock`s. When the innermost block is
  2511. // complete, it will be popped and the next outer block will execute.
  2512. llvm::SmallVector<llvm::ArrayRef<SemIR::InstId>, 4> blocks_;
  2513. // The arguments in the function call.
  2514. llvm::ArrayRef<SemIR::InstId> args_;
  2515. // The block argument provided by the most recently executed `BranchWithArg`.
  2516. // We assume that we only need to track one of these, as the branch target
  2517. // will invoke `BlockArg` before the next `BranchWithArg` happens. We will
  2518. // need to track more than one of these if that ever changes.
  2519. BlockArgValue current_block_arg_value_;
  2520. };
  2521. // Handles the result of executing an instruction in a function. Returns an
  2522. // error the result is not a constant, and otherwise updates the locals map to
  2523. // track the result as an input to later evaluations in this function and
  2524. // returns None.
  2525. static auto HandleExecResult(FunctionExecContext& eval_context,
  2526. SemIR::InstId inst_id, SemIR::ConstantId const_id)
  2527. -> SemIR::ConstantId {
  2528. if (!const_id.has_value() || !const_id.is_constant()) {
  2529. DiagnoseNonConstantValue(eval_context, inst_id);
  2530. return SemIR::ErrorInst::ConstantId;
  2531. }
  2532. if (const_id == SemIR::ErrorInst::ConstantId) {
  2533. return const_id;
  2534. }
  2535. eval_context.locals().Update(inst_id, const_id);
  2536. return SemIR::ConstantId::None;
  2537. }
  2538. // Executes an instruction for TryEvalCall. By default, performs normal
  2539. // evaluation of the instruction within a context that supplies the values
  2540. // produced by executing prior instructions in this function execution. This is
  2541. // specialized for instructions that have special handling in function
  2542. // execution, such as those that access parameters or perform flow control. If
  2543. // execution should continue, returns `SemIR::ConstantId::None`, otherwise
  2544. // returns the result to produce for the enclosing function call, which should
  2545. // be either the returned value or an error.
  2546. template <typename InstT>
  2547. static auto TryExecTypedInst(FunctionExecContext& eval_context,
  2548. SemIR::InstId inst_id, SemIR::Inst inst)
  2549. -> SemIR::ConstantId {
  2550. if constexpr (InstT::Kind.expr_category().TryAsFixedCategory() ==
  2551. SemIR::ExprCategory::NotExpr) {
  2552. // Instructions in this category are assumed to not have a runtime effect.
  2553. // This includes some kinds of declaration.
  2554. return SemIR::ConstantId::None;
  2555. }
  2556. if constexpr (InstT::Kind.constant_kind() != SemIR::InstConstantKind::Never) {
  2557. if (eval_context.constant_values().Get(inst_id).is_concrete()) {
  2558. // Instruction has a concrete constant value that doesn't depend on the
  2559. // context. We don't need to evaluate it again.
  2560. return SemIR::ConstantId::None;
  2561. }
  2562. }
  2563. // Evaluate the instruction in the current context.
  2564. auto const_id = TryEvalTypedInst<InstT>(eval_context, inst_id, inst);
  2565. return HandleExecResult(eval_context, inst_id, const_id);
  2566. }
  2567. template <>
  2568. auto TryExecTypedInst<SemIR::BlockArg>(FunctionExecContext& eval_context,
  2569. SemIR::InstId inst_id, SemIR::Inst inst)
  2570. -> SemIR::ConstantId {
  2571. auto block_arg = inst.As<SemIR::BlockArg>();
  2572. CARBON_CHECK(
  2573. block_arg.block_id == eval_context.current_block_arg_value().block_id,
  2574. "BlockArg does not refer to most recent BranchWithArg");
  2575. eval_context.locals().Update(inst_id,
  2576. eval_context.current_block_arg_value().arg_id);
  2577. return SemIR::ConstantId::None;
  2578. }
  2579. template <>
  2580. auto TryExecTypedInst<SemIR::Branch>(FunctionExecContext& eval_context,
  2581. SemIR::InstId /*inst_id*/,
  2582. SemIR::Inst inst) -> SemIR::ConstantId {
  2583. auto branch = inst.As<SemIR::Branch>();
  2584. eval_context.BranchTo(branch.target_id);
  2585. return SemIR::ConstantId::None;
  2586. }
  2587. template <>
  2588. auto TryExecTypedInst<SemIR::BranchIf>(FunctionExecContext& eval_context,
  2589. SemIR::InstId /*inst_id*/,
  2590. SemIR::Inst inst) -> SemIR::ConstantId {
  2591. auto branch_if = inst.As<SemIR::BranchIf>();
  2592. auto cond_id = CheckConcreteValue(eval_context, branch_if.cond_id);
  2593. if (cond_id == SemIR::ErrorInst::InstId) {
  2594. return SemIR::ErrorInst::ConstantId;
  2595. }
  2596. auto cond = eval_context.insts().GetAs<SemIR::BoolLiteral>(cond_id);
  2597. if (cond.value == SemIR::BoolValue::True) {
  2598. eval_context.BranchTo(branch_if.target_id);
  2599. }
  2600. return SemIR::ConstantId::None;
  2601. }
  2602. template <>
  2603. auto TryExecTypedInst<SemIR::BranchWithArg>(FunctionExecContext& eval_context,
  2604. SemIR::InstId /*inst_id*/,
  2605. SemIR::Inst inst)
  2606. -> SemIR::ConstantId {
  2607. auto branch = inst.As<SemIR::BranchWithArg>();
  2608. eval_context.SetCurrentBlockArgValue(
  2609. {.block_id = branch.target_id,
  2610. .arg_id = eval_context.GetConstantValue(branch.arg_id)});
  2611. eval_context.BranchTo(branch.target_id);
  2612. return SemIR::ConstantId::None;
  2613. }
  2614. template <>
  2615. auto TryExecTypedInst<SemIR::Return>(FunctionExecContext& eval_context,
  2616. SemIR::InstId /*inst_id*/,
  2617. SemIR::Inst /*inst*/)
  2618. -> SemIR::ConstantId {
  2619. return MakeEmptyTupleResult(eval_context);
  2620. }
  2621. template <>
  2622. auto TryExecTypedInst<SemIR::ReturnExpr>(FunctionExecContext& eval_context,
  2623. SemIR::InstId /*inst_id*/,
  2624. SemIR::Inst inst)
  2625. -> SemIR::ConstantId {
  2626. auto return_expr = inst.As<SemIR::ReturnExpr>();
  2627. return eval_context.GetConstantValue(return_expr.expr_id);
  2628. }
  2629. template <>
  2630. auto TryExecTypedInst<SemIR::ReturnSlot>(FunctionExecContext& eval_context,
  2631. SemIR::InstId inst_id,
  2632. SemIR::Inst inst)
  2633. -> SemIR::ConstantId {
  2634. auto return_slot = inst.As<SemIR::ReturnSlot>();
  2635. // In the case where the function's return type is not in-place, the return
  2636. // slot will refer to an out parameter that doesn't have an argument. In that
  2637. // case, we don't have a constant value for storage_id. To handle this, copy
  2638. // the value directly from the locals map rather than using GetConstantValue.
  2639. //
  2640. // TODO: Remove this and use a normal call to `GetConstantValue` if we stop
  2641. // adding out parameters with no corresponding argument.
  2642. eval_context.locals().Insert(
  2643. inst_id, eval_context.locals().Lookup(return_slot.storage_id).value());
  2644. return SemIR::ConstantId::None;
  2645. }
  2646. template <>
  2647. auto TryExecTypedInst<SemIR::SpliceBlock>(FunctionExecContext& eval_context,
  2648. SemIR::InstId /*inst_id*/,
  2649. SemIR::Inst inst)
  2650. -> SemIR::ConstantId {
  2651. auto splice_block = inst.As<SemIR::SpliceBlock>();
  2652. eval_context.PushBlock(splice_block.block_id);
  2653. // TODO: Copy the values from the result_id instruction to the result of
  2654. // the splice_block instruction once the spliced block finishes.
  2655. return SemIR::ConstantId::None;
  2656. }
  2657. // Executes the introduction of a parameter into the local scope. Copies the
  2658. // argument supplied by the caller for the parameter into the locals map.
  2659. static auto TryExecTypedParam(FunctionExecContext& eval_context,
  2660. SemIR::InstId inst_id, SemIR::Inst inst)
  2661. -> SemIR::ConstantId {
  2662. auto param = inst.As<SemIR::AnyParam>();
  2663. CARBON_CHECK(static_cast<size_t>(param.index.index) <
  2664. eval_context.args().size());
  2665. eval_context.locals().Insert(inst_id,
  2666. eval_context.constant_values().Get(
  2667. eval_context.args()[param.index.index]));
  2668. return SemIR::ConstantId::None;
  2669. }
  2670. template <>
  2671. auto TryExecTypedInst<SemIR::OutParam>(FunctionExecContext& eval_context,
  2672. SemIR::InstId inst_id, SemIR::Inst inst)
  2673. -> SemIR::ConstantId {
  2674. auto param = inst.As<SemIR::OutParam>();
  2675. if (static_cast<size_t>(param.index.index) >= eval_context.args().size()) {
  2676. // For return values that have a copy initializing representation, the SemIR
  2677. // has an OutParam with an index that has no corresponding argument. In that
  2678. // case, we do not have a constant value for the parameter, but this doesn't
  2679. // prevent the call from being constant.
  2680. //
  2681. // TODO: Remove this once we stop adding out parameters with no
  2682. // corresponding argument.
  2683. eval_context.locals().Insert(inst_id, SemIR::ConstantId::None);
  2684. return SemIR::ConstantId::None;
  2685. }
  2686. if (!eval_context.args()[param.index.index].has_value()) {
  2687. // The argument will be `None` for an index corresponding to a return
  2688. // storage argument for return values that have an in-place initializing
  2689. // representation. Produce an opaque "out parameter" variable for now, so
  2690. // that references to it can still successfully evaluate.
  2691. //
  2692. // TODO: Create and track mutable storage for the return value here. This is
  2693. // necessary to support things like `returned var`.
  2694. eval_context.locals().Insert(
  2695. inst_id,
  2696. MakeConstantResult(
  2697. eval_context.context(),
  2698. SemIR::VarStorage{.type_id = inst.type_id(),
  2699. .pattern_id = SemIR::AbsoluteInstId::None},
  2700. Phase::Concrete));
  2701. return SemIR::ConstantId::None;
  2702. }
  2703. return TryExecTypedParam(eval_context, inst_id, inst);
  2704. }
  2705. template <>
  2706. auto TryExecTypedInst<SemIR::RefParam>(FunctionExecContext& eval_context,
  2707. SemIR::InstId inst_id, SemIR::Inst inst)
  2708. -> SemIR::ConstantId {
  2709. return TryExecTypedParam(eval_context, inst_id, inst);
  2710. }
  2711. template <>
  2712. auto TryExecTypedInst<SemIR::ValueParam>(FunctionExecContext& eval_context,
  2713. SemIR::InstId inst_id,
  2714. SemIR::Inst inst)
  2715. -> SemIR::ConstantId {
  2716. return TryExecTypedParam(eval_context, inst_id, inst);
  2717. }
  2718. template <>
  2719. auto TryExecTypedInst<SemIR::ValueBinding>(FunctionExecContext& eval_context,
  2720. SemIR::InstId inst_id,
  2721. SemIR::Inst inst)
  2722. -> SemIR::ConstantId {
  2723. auto value_binding = inst.As<SemIR::ValueBinding>();
  2724. auto local_value_id = eval_context.GetConstantValue(value_binding.value_id);
  2725. eval_context.locals().Insert(inst_id, local_value_id);
  2726. return SemIR::ConstantId::None;
  2727. }
  2728. static auto TryExecInst(FunctionExecContext& eval_context,
  2729. SemIR::InstId inst_id, SemIR::Inst inst)
  2730. -> SemIR::ConstantId {
  2731. using ExecInstFn = auto(FunctionExecContext & eval_context,
  2732. SemIR::InstId inst_id, SemIR::Inst inst)
  2733. ->SemIR::ConstantId;
  2734. static constexpr ExecInstFn* ExecInstFns[] = {
  2735. #define CARBON_SEM_IR_INST_KIND(Kind) &TryExecTypedInst<SemIR::Kind>,
  2736. #include "toolchain/sem_ir/inst_kind.def"
  2737. };
  2738. [[clang::musttail]] return ExecInstFns[inst.kind().AsInt()](eval_context,
  2739. inst_id, inst);
  2740. }
  2741. // Evaluates a call to an `eval` or `musteval` function by executing the
  2742. // function body.
  2743. static auto TryEvalCall(EvalContext& outer_eval_context, SemIR::LocId loc_id,
  2744. const SemIR::Function& function,
  2745. SemIR::SpecificId specific_id,
  2746. SemIR::InstBlockId args_id) -> SemIR::ConstantId {
  2747. if (function.clang_decl_id != SemIR::ClangDeclId::None) {
  2748. return EvalCppCall(outer_eval_context.context(), loc_id,
  2749. function.clang_decl_id, args_id);
  2750. } else if (function.body_block_ids.empty()) {
  2751. // TODO: Diagnose this.
  2752. return SemIR::ConstantId::NotConstant;
  2753. }
  2754. // TODO: Consider tracking the lowest and highest inst_id in the function and
  2755. // using an array instead of a map. We would still need a map for instantiated
  2756. // portions of a function template.
  2757. Map<SemIR::InstId, SemIR::ConstantId> locals;
  2758. FunctionExecContext eval_context(&outer_eval_context.context(), loc_id,
  2759. specific_id, &locals, args_id);
  2760. Diagnostics::AnnotationScope annotate_diagnostics(
  2761. &eval_context.emitter(), [&](auto& builder) {
  2762. CARBON_DIAGNOSTIC(InCallToEvalFn, Note, "in call to {0} here",
  2763. SemIR::NameId);
  2764. builder.Note(loc_id, InCallToEvalFn, function.name_id);
  2765. });
  2766. // Execute the function decl block followed by the body.
  2767. eval_context.PushBlock(function.body_block_ids.front());
  2768. eval_context.PushBlock(eval_context.insts()
  2769. .GetAs<SemIR::FunctionDecl>(function.definition_id)
  2770. .decl_block_id);
  2771. // Execute the blocks. This is mostly expression evaluation, with special
  2772. // handling for control flow and parameters.
  2773. while (true) {
  2774. auto inst_id = eval_context.PopNextInstId();
  2775. auto inst = eval_context.context().insts().Get(inst_id);
  2776. if (auto result = TryExecInst(eval_context, inst_id, inst);
  2777. result.has_value()) {
  2778. return result;
  2779. }
  2780. }
  2781. }
  2782. } // namespace Carbon::Check