eval.cpp 121 KB

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