eval.cpp 135 KB

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