eval.cpp 134 KB

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