eval.cpp 130 KB

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