eval.cpp 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117
  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 "toolchain/base/kind_switch.h"
  10. #include "toolchain/check/action.h"
  11. #include "toolchain/check/diagnostic_helpers.h"
  12. #include "toolchain/check/eval_inst.h"
  13. #include "toolchain/check/facet_type.h"
  14. #include "toolchain/check/generic.h"
  15. #include "toolchain/check/import_ref.h"
  16. #include "toolchain/check/type.h"
  17. #include "toolchain/check/type_completion.h"
  18. #include "toolchain/diagnostics/diagnostic_emitter.h"
  19. #include "toolchain/diagnostics/format_providers.h"
  20. #include "toolchain/sem_ir/builtin_function_kind.h"
  21. #include "toolchain/sem_ir/constant.h"
  22. #include "toolchain/sem_ir/function.h"
  23. #include "toolchain/sem_ir/generic.h"
  24. #include "toolchain/sem_ir/id_kind.h"
  25. #include "toolchain/sem_ir/ids.h"
  26. #include "toolchain/sem_ir/inst_kind.h"
  27. #include "toolchain/sem_ir/typed_insts.h"
  28. namespace Carbon::Check {
  29. namespace {
  30. // Information about an eval block of a specific that we are currently building.
  31. struct SpecificEvalInfo {
  32. // The region within the specific whose eval block we are building.
  33. SemIR::GenericInstIndex::Region region;
  34. // The work-in-progress contents of the eval block.
  35. llvm::ArrayRef<SemIR::InstId> values;
  36. };
  37. // Information about the context within which we are performing evaluation.
  38. // `context` must not be null.
  39. class EvalContext {
  40. public:
  41. explicit EvalContext(
  42. Context* context, SemIR::LocId fallback_loc_id,
  43. SemIR::SpecificId specific_id = SemIR::SpecificId::None,
  44. std::optional<SpecificEvalInfo> specific_eval_info = std::nullopt)
  45. : context_(context),
  46. fallback_loc_id_(fallback_loc_id),
  47. specific_id_(specific_id),
  48. specific_eval_info_(specific_eval_info) {}
  49. // Gets the location to use for diagnostics if a better location is
  50. // unavailable.
  51. // TODO: This is also sometimes unavailable.
  52. auto fallback_loc_id() const -> SemIR::LocId { return fallback_loc_id_; }
  53. // Returns a location to use to point at an instruction in a diagnostic, given
  54. // a list of instructions that might have an attached location. This is the
  55. // location of the first instruction in the list that has a location if there
  56. // is one, and otherwise the fallback location.
  57. auto GetDiagnosticLoc(llvm::ArrayRef<SemIR::InstId> inst_ids)
  58. -> SemIR::LocId {
  59. for (auto inst_id : inst_ids) {
  60. if (inst_id.has_value()) {
  61. auto loc_id = context_->insts().GetCanonicalLocId(inst_id);
  62. if (loc_id.has_value()) {
  63. return loc_id;
  64. }
  65. }
  66. }
  67. return fallback_loc_id_;
  68. }
  69. // Gets the value of the specified compile-time binding in this context.
  70. // Returns `None` if the value is not fixed in this context.
  71. auto GetCompileTimeBindValue(SemIR::CompileTimeBindIndex bind_index)
  72. -> SemIR::ConstantId {
  73. if (!bind_index.has_value() || !specific_id_.has_value()) {
  74. return SemIR::ConstantId::None;
  75. }
  76. const auto& specific = specifics().Get(specific_id_);
  77. auto args = inst_blocks().Get(specific.args_id);
  78. // Bindings past the ones with known arguments can appear as local
  79. // bindings of entities declared within this generic.
  80. if (static_cast<size_t>(bind_index.index) >= args.size()) {
  81. return SemIR::ConstantId::None;
  82. }
  83. return constant_values().Get(args[bind_index.index]);
  84. }
  85. // Given information about a symbolic constant, determine its value in the
  86. // currently-being-evaluated eval block, if it refers to that eval block. If
  87. // we can't find a value in this way, returns `None`.
  88. auto GetInEvaluatedSpecific(const SemIR::SymbolicConstant& symbolic_info)
  89. -> SemIR::ConstantId {
  90. if (!specific_eval_info_ || !symbolic_info.index.has_value()) {
  91. return SemIR::ConstantId::None;
  92. }
  93. CARBON_CHECK(
  94. symbolic_info.generic_id == specifics().Get(specific_id_).generic_id,
  95. "Instruction has constant operand in wrong generic");
  96. if (symbolic_info.index.region() != specific_eval_info_->region) {
  97. return SemIR::ConstantId::None;
  98. }
  99. auto inst_id = specific_eval_info_->values[symbolic_info.index.index()];
  100. CARBON_CHECK(inst_id.has_value(),
  101. "Forward reference in eval block: index {0} referenced "
  102. "before evaluation",
  103. symbolic_info.index.index());
  104. return constant_values().Get(inst_id);
  105. }
  106. // Gets the constant value of the specified instruction in this context.
  107. auto GetConstantValue(SemIR::InstId inst_id) -> SemIR::ConstantId {
  108. auto const_id = constant_values().GetAttached(inst_id);
  109. if (!const_id.is_symbolic()) {
  110. return const_id;
  111. }
  112. // While resolving a specific, map from previous instructions in the eval
  113. // block into their evaluated values. These values won't be present on the
  114. // specific itself yet, so `GetConstantValueInSpecific` won't be able to
  115. // find them.
  116. const auto& symbolic_info = constant_values().GetSymbolicConstant(const_id);
  117. if (auto eval_block_const_id = GetInEvaluatedSpecific(symbolic_info);
  118. eval_block_const_id.has_value()) {
  119. return eval_block_const_id;
  120. }
  121. return GetConstantValueInSpecific(sem_ir(), specific_id_, inst_id);
  122. }
  123. // Gets the type of the specified instruction in this context.
  124. auto GetTypeOfInst(SemIR::InstId inst_id) -> SemIR::TypeId {
  125. auto type_id = insts().GetAttachedType(inst_id);
  126. if (!type_id.is_symbolic()) {
  127. return type_id;
  128. }
  129. // While resolving a specific, map from previous instructions in the eval
  130. // block into their evaluated values. These values won't be present on the
  131. // specific itself yet, so `GetTypeOfInstInSpecific` won't be able to
  132. // find them.
  133. const auto& symbolic_info =
  134. constant_values().GetSymbolicConstant(types().GetConstantId(type_id));
  135. if (auto eval_block_const_id = GetInEvaluatedSpecific(symbolic_info);
  136. eval_block_const_id.has_value()) {
  137. return types().GetTypeIdForTypeConstantId(eval_block_const_id);
  138. }
  139. return GetTypeOfInstInSpecific(sem_ir(), specific_id_, inst_id);
  140. }
  141. auto ints() -> SharedValueStores::IntStore& { return sem_ir().ints(); }
  142. auto floats() -> SharedValueStores::FloatStore& { return sem_ir().floats(); }
  143. auto entity_names() -> SemIR::EntityNameStore& {
  144. return sem_ir().entity_names();
  145. }
  146. auto functions() -> const ValueStore<SemIR::FunctionId>& {
  147. return sem_ir().functions();
  148. }
  149. auto classes() -> const ValueStore<SemIR::ClassId>& {
  150. return sem_ir().classes();
  151. }
  152. auto interfaces() -> const ValueStore<SemIR::InterfaceId>& {
  153. return sem_ir().interfaces();
  154. }
  155. auto specific_interfaces()
  156. -> CanonicalValueStore<SemIR::SpecificInterfaceId>& {
  157. return sem_ir().specific_interfaces();
  158. }
  159. auto facet_types() -> CanonicalValueStore<SemIR::FacetTypeId>& {
  160. return sem_ir().facet_types();
  161. }
  162. auto generics() -> const SemIR::GenericStore& { return sem_ir().generics(); }
  163. auto specifics() -> const SemIR::SpecificStore& {
  164. return sem_ir().specifics();
  165. }
  166. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  167. auto inst_blocks() -> SemIR::InstBlockStore& {
  168. return sem_ir().inst_blocks();
  169. }
  170. // Gets the constant value store. Note that this does not provide the constant
  171. // values that should be used from this evaluation context, and so should be
  172. // used with caution.
  173. auto constant_values() -> const SemIR::ConstantValueStore& {
  174. return sem_ir().constant_values();
  175. }
  176. // Gets the types store. Note that this does not provide the type values that
  177. // should be used from this evaluation context, and so should be used with
  178. // caution.
  179. auto types() -> const SemIR::TypeStore& { return sem_ir().types(); }
  180. auto context() -> Context& { return *context_; }
  181. auto sem_ir() -> SemIR::File& { return context().sem_ir(); }
  182. auto emitter() -> DiagnosticEmitterBase& { return context().emitter(); }
  183. private:
  184. // The type-checking context in which we're performing evaluation.
  185. Context* context_;
  186. // The location to use for diagnostics when a better location isn't available.
  187. SemIR::LocId fallback_loc_id_;
  188. // The specific that we are evaluating within.
  189. SemIR::SpecificId specific_id_;
  190. // If we are currently evaluating an eval block for `specific_id_`,
  191. // information about that evaluation.
  192. std::optional<SpecificEvalInfo> specific_eval_info_;
  193. };
  194. } // namespace
  195. namespace {
  196. // The evaluation phase for an expression, computed by evaluation. These are
  197. // ordered so that the phase of an expression is the numerically highest phase
  198. // of its constituent evaluations. Note that an expression with any runtime
  199. // component is known to have Runtime phase even if it involves an evaluation
  200. // with UnknownDueToError phase.
  201. enum class Phase : uint8_t {
  202. // Value could be entirely and concretely computed.
  203. Concrete,
  204. // Evaluation phase is symbolic because the expression involves specifically a
  205. // reference to `.Self`.
  206. PeriodSelfSymbolic,
  207. // Evaluation phase is symbolic because the expression involves a reference to
  208. // a non-template symbolic binding other than `.Self`.
  209. CheckedSymbolic,
  210. // Evaluation phase is symbolic because the expression involves a reference to
  211. // a template parameter, or otherwise depends on something template dependent.
  212. // The expression might also reference non-template symbolic bindings.
  213. TemplateSymbolic,
  214. // The evaluation phase is unknown because evaluation encountered an
  215. // already-diagnosed semantic or syntax error. This is treated as being
  216. // potentially constant, but with an unknown phase.
  217. UnknownDueToError,
  218. // The expression has runtime phase because of a non-constant subexpression.
  219. Runtime,
  220. };
  221. } // namespace
  222. // Returns whether the specified phase is a constant phase.
  223. static auto IsConstant(Phase phase) -> bool {
  224. return phase < Phase::UnknownDueToError;
  225. }
  226. // Gets the phase in which the value of a constant will become available.
  227. static auto GetPhase(const SemIR::ConstantValueStore& constant_values,
  228. SemIR::ConstantId constant_id) -> Phase {
  229. if (!constant_id.is_constant()) {
  230. return Phase::Runtime;
  231. } else if (constant_id == SemIR::ErrorInst::ConstantId) {
  232. return Phase::UnknownDueToError;
  233. }
  234. switch (constant_values.GetDependence(constant_id)) {
  235. case SemIR::ConstantDependence::None:
  236. return Phase::Concrete;
  237. case SemIR::ConstantDependence::PeriodSelf:
  238. return Phase::PeriodSelfSymbolic;
  239. case SemIR::ConstantDependence::Checked:
  240. return Phase::CheckedSymbolic;
  241. case SemIR::ConstantDependence::Template:
  242. return Phase::TemplateSymbolic;
  243. }
  244. }
  245. // Returns the later of two phases.
  246. static auto LatestPhase(Phase a, Phase b) -> Phase {
  247. return static_cast<Phase>(
  248. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  249. }
  250. // Forms a `constant_id` describing a given evaluation result.
  251. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  252. -> SemIR::ConstantId {
  253. switch (phase) {
  254. case Phase::Concrete:
  255. return context.constants().GetOrAdd(inst,
  256. SemIR::ConstantDependence::None);
  257. case Phase::PeriodSelfSymbolic:
  258. return context.constants().GetOrAdd(
  259. inst, SemIR::ConstantDependence::PeriodSelf);
  260. case Phase::CheckedSymbolic:
  261. return context.constants().GetOrAdd(inst,
  262. SemIR::ConstantDependence::Checked);
  263. case Phase::TemplateSymbolic:
  264. return context.constants().GetOrAdd(inst,
  265. SemIR::ConstantDependence::Template);
  266. case Phase::UnknownDueToError:
  267. return SemIR::ErrorInst::ConstantId;
  268. case Phase::Runtime:
  269. return SemIR::ConstantId::NotConstant;
  270. }
  271. }
  272. // Forms a `constant_id` describing why an evaluation was not constant.
  273. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  274. return phase == Phase::UnknownDueToError ? SemIR::ErrorInst::ConstantId
  275. : SemIR::ConstantId::NotConstant;
  276. }
  277. // Converts a bool value into a ConstantId.
  278. static auto MakeBoolResult(Context& context, SemIR::TypeId bool_type_id,
  279. bool result) -> SemIR::ConstantId {
  280. return MakeConstantResult(
  281. context,
  282. SemIR::BoolLiteral{.type_id = bool_type_id,
  283. .value = SemIR::BoolValue::From(result)},
  284. Phase::Concrete);
  285. }
  286. // Converts an APInt value into a ConstantId.
  287. static auto MakeIntResult(Context& context, SemIR::TypeId type_id,
  288. bool is_signed, llvm::APInt value)
  289. -> SemIR::ConstantId {
  290. CARBON_CHECK(is_signed == context.types().IsSignedInt(type_id));
  291. auto result = is_signed ? context.ints().AddSigned(std::move(value))
  292. : context.ints().AddUnsigned(std::move(value));
  293. return MakeConstantResult(
  294. context, SemIR::IntValue{.type_id = type_id, .int_id = result},
  295. Phase::Concrete);
  296. }
  297. // Converts an APFloat value into a ConstantId.
  298. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  299. llvm::APFloat value) -> SemIR::ConstantId {
  300. auto result = context.floats().Add(std::move(value));
  301. return MakeConstantResult(
  302. context, SemIR::FloatLiteral{.type_id = type_id, .float_id = result},
  303. Phase::Concrete);
  304. }
  305. // Creates a FacetType constant.
  306. static auto MakeFacetTypeResult(Context& context,
  307. const SemIR::FacetTypeInfo& info, Phase phase)
  308. -> SemIR::ConstantId {
  309. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  310. return MakeConstantResult(context,
  311. SemIR::FacetType{.type_id = SemIR::TypeType::TypeId,
  312. .facet_type_id = facet_type_id},
  313. phase);
  314. }
  315. // `GetConstantValue` checks to see whether the provided ID describes a value
  316. // with constant phase, and if so, returns the corresponding constant value.
  317. // Overloads are provided for different kinds of ID.
  318. // AbsoluteInstId can not have its values substituted, so this overload is
  319. // deleted. This prevents conversion to InstId.
  320. static auto GetConstantValue(EvalContext& eval_context,
  321. SemIR::AbsoluteInstId inst_id, Phase* phase)
  322. -> SemIR::InstId = delete;
  323. // If the given instruction is constant, returns its constant value.
  324. static auto GetConstantValue(EvalContext& eval_context, SemIR::InstId inst_id,
  325. Phase* phase) -> SemIR::InstId {
  326. if (!inst_id.has_value()) {
  327. return SemIR::InstId::None;
  328. }
  329. auto const_id = eval_context.GetConstantValue(inst_id);
  330. *phase =
  331. LatestPhase(*phase, GetPhase(eval_context.constant_values(), const_id));
  332. return eval_context.constant_values().GetInstId(const_id);
  333. }
  334. // If the given instruction is constant, returns its constant value. When
  335. // determining the phase of the result, ignore any dependence on `.Self`.
  336. //
  337. // This is used when evaluating facet types, for which `where` expressions using
  338. // `.Self` should not be considered symbolic
  339. // - `Interface where .Self impls I and .A = bool` -> concrete
  340. // - `T:! type` ... `Interface where .A = T` -> symbolic, since uses `T` which
  341. // is symbolic and not due to `.Self`.
  342. static auto GetConstantValueIgnoringPeriodSelf(EvalContext& eval_context,
  343. SemIR::InstId inst_id,
  344. Phase* phase) -> SemIR::InstId {
  345. if (!inst_id.has_value()) {
  346. return SemIR::InstId::None;
  347. }
  348. auto const_id = eval_context.GetConstantValue(inst_id);
  349. Phase constant_phase = GetPhase(eval_context.constant_values(), const_id);
  350. // Since LatestPhase(x, Phase::Concrete) == x, this is equivalent to replacing
  351. // Phase::PeriodSelfSymbolic with Phase::Concrete.
  352. if (constant_phase != Phase::PeriodSelfSymbolic) {
  353. *phase = LatestPhase(*phase, constant_phase);
  354. }
  355. return eval_context.constant_values().GetInstId(const_id);
  356. }
  357. // Find the instruction that the given instruction instantiates to, and return
  358. // that.
  359. static auto GetConstantValue(EvalContext& eval_context,
  360. SemIR::MetaInstId inst_id, Phase* phase)
  361. -> SemIR::MetaInstId {
  362. Phase inner_phase = Phase::Concrete;
  363. if (auto const_inst_id =
  364. GetConstantValue(eval_context, SemIR::InstId(inst_id), &inner_phase);
  365. const_inst_id.has_value()) {
  366. // The instruction has a constant value. Use that as the operand of the
  367. // action.
  368. *phase = LatestPhase(*phase, inner_phase);
  369. return const_inst_id;
  370. }
  371. // If this instruction is splicing in an action result, that action result is
  372. // our operand.
  373. if (auto splice = eval_context.insts().TryGetAs<SemIR::SpliceInst>(inst_id)) {
  374. if (auto spliced_inst_id =
  375. GetConstantValue(eval_context, splice->inst_id, phase);
  376. spliced_inst_id.has_value()) {
  377. if (auto inst_value_id = eval_context.insts().TryGetAs<SemIR::InstValue>(
  378. spliced_inst_id)) {
  379. return inst_value_id->inst_id;
  380. }
  381. }
  382. }
  383. // Otherwise, this is a normal instruction.
  384. if (OperandIsDependent(eval_context.context(), inst_id)) {
  385. *phase = LatestPhase(*phase, Phase::TemplateSymbolic);
  386. }
  387. return inst_id;
  388. }
  389. static auto GetConstantValue(EvalContext& eval_context,
  390. SemIR::TypeInstId inst_id, Phase* phase)
  391. -> SemIR::TypeInstId {
  392. // The input instruction is a TypeInstId, and eval does not change concrete
  393. // types (like TypeType which TypeInstId implies), so the result is also a
  394. // valid TypeInstId.
  395. return SemIR::TypeInstId::UnsafeMake(GetConstantValue(
  396. eval_context, static_cast<SemIR::InstId>(inst_id), phase));
  397. }
  398. // Explicitly discard a `DestInstId`, because we should not be using the
  399. // destination as part of evaluation.
  400. static auto GetConstantValue(EvalContext& /*eval_context*/,
  401. SemIR::DestInstId /*inst_id*/, Phase* /*phase*/)
  402. -> SemIR::DestInstId {
  403. return SemIR::InstId::None;
  404. }
  405. // Given an instruction whose type may refer to a generic parameter, returns the
  406. // corresponding type in the evaluation context.
  407. static auto GetTypeOfInst(EvalContext& eval_context, SemIR::InstId inst_id,
  408. Phase* phase) -> SemIR::TypeId {
  409. auto type_id = eval_context.GetTypeOfInst(inst_id);
  410. *phase = LatestPhase(*phase,
  411. GetPhase(eval_context.constant_values(),
  412. eval_context.types().GetConstantId(type_id)));
  413. return type_id;
  414. }
  415. // AbsoluteInstBlockId can not have its values substituted, so this overload is
  416. // deleted. This prevents conversion to InstBlockId.
  417. static auto GetConstantValue(EvalContext& eval_context,
  418. SemIR::AbsoluteInstBlockId inst_block_id,
  419. Phase* phase) -> SemIR::InstBlockId = delete;
  420. // If the given instruction block contains only constants, returns a
  421. // corresponding block of those values.
  422. static auto GetConstantValue(EvalContext& eval_context,
  423. SemIR::InstBlockId inst_block_id, Phase* phase)
  424. -> SemIR::InstBlockId {
  425. if (!inst_block_id.has_value()) {
  426. return SemIR::InstBlockId::None;
  427. }
  428. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  429. llvm::SmallVector<SemIR::InstId> const_insts;
  430. for (auto inst_id : insts) {
  431. auto const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  432. if (!const_inst_id.has_value()) {
  433. return SemIR::InstBlockId::None;
  434. }
  435. // Once we leave the small buffer, we know the first few elements are all
  436. // constant, so it's likely that the entire block is constant. Resize to the
  437. // target size given that we're going to allocate memory now anyway.
  438. if (const_insts.size() == const_insts.capacity()) {
  439. const_insts.reserve(insts.size());
  440. }
  441. const_insts.push_back(const_inst_id);
  442. }
  443. // TODO: If the new block is identical to the original block, and we know the
  444. // old ID was canonical, return the original ID.
  445. return eval_context.inst_blocks().AddCanonical(const_insts);
  446. }
  447. // Compute the constant value of a type block. This may be different from the
  448. // input type block if we have known generic arguments.
  449. static auto GetConstantValue(EvalContext& eval_context,
  450. SemIR::StructTypeFieldsId fields_id, Phase* phase)
  451. -> SemIR::StructTypeFieldsId {
  452. if (!fields_id.has_value()) {
  453. return SemIR::StructTypeFieldsId::None;
  454. }
  455. auto fields = eval_context.context().struct_type_fields().Get(fields_id);
  456. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  457. for (auto field : fields) {
  458. auto new_type_inst_id =
  459. GetConstantValue(eval_context, field.type_inst_id, phase);
  460. if (!new_type_inst_id.has_value()) {
  461. return SemIR::StructTypeFieldsId::None;
  462. }
  463. // Once we leave the small buffer, we know the first few elements are all
  464. // constant, so it's likely that the entire block is constant. Resize to the
  465. // target size given that we're going to allocate memory now anyway.
  466. if (new_fields.size() == new_fields.capacity()) {
  467. new_fields.reserve(fields.size());
  468. }
  469. new_fields.push_back(
  470. {.name_id = field.name_id, .type_inst_id = new_type_inst_id});
  471. }
  472. // TODO: If the new block is identical to the original block, and we know the
  473. // old ID was canonical, return the original ID.
  474. return eval_context.context().struct_type_fields().AddCanonical(new_fields);
  475. }
  476. // The constant value of a specific is the specific with the corresponding
  477. // constant values for its arguments.
  478. static auto GetConstantValue(EvalContext& eval_context,
  479. SemIR::SpecificId specific_id, Phase* phase)
  480. -> SemIR::SpecificId {
  481. if (!specific_id.has_value()) {
  482. return SemIR::SpecificId::None;
  483. }
  484. const auto& specific = eval_context.specifics().Get(specific_id);
  485. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  486. if (!args_id.has_value()) {
  487. return SemIR::SpecificId::None;
  488. }
  489. // Generally, when making a new specific, it's done through MakeSpecific(),
  490. // which will ensure the declaration is resolved.
  491. //
  492. // However, the SpecificId returned here is intentionally left without its
  493. // declaration resolved. Imported instructions with SpecificIds should not
  494. // have the specific's declaration resolved, but other instructions which
  495. // include a new SpecificId should.
  496. //
  497. // The resolving of the specific's declaration will be ensured later when
  498. // evaluating the instruction containing the SpecificId.
  499. if (args_id == specific.args_id) {
  500. return specific_id;
  501. }
  502. return eval_context.context().specifics().GetOrAdd(specific.generic_id,
  503. args_id);
  504. }
  505. static auto GetConstantValue(EvalContext& eval_context,
  506. SemIR::SpecificInterfaceId specific_interface_id,
  507. Phase* phase) -> SemIR::SpecificInterfaceId {
  508. const auto& interface =
  509. eval_context.specific_interfaces().Get(specific_interface_id);
  510. if (!interface.specific_id.has_value()) {
  511. return specific_interface_id;
  512. }
  513. return eval_context.specific_interfaces().Add(
  514. {.interface_id = interface.interface_id,
  515. .specific_id =
  516. GetConstantValue(eval_context, interface.specific_id, phase)});
  517. }
  518. // Like `GetConstantValue` but does a `FacetTypeId` -> `FacetTypeInfo`
  519. // conversion. Does not perform canonicalization.
  520. static auto GetConstantFacetTypeInfo(EvalContext& eval_context,
  521. SemIR::FacetTypeId facet_type_id,
  522. Phase* phase) -> SemIR::FacetTypeInfo {
  523. const auto& orig = eval_context.facet_types().Get(facet_type_id);
  524. SemIR::FacetTypeInfo info;
  525. info.extend_constraints.reserve(orig.extend_constraints.size());
  526. for (const auto& interface : orig.extend_constraints) {
  527. info.extend_constraints.push_back(
  528. {.interface_id = interface.interface_id,
  529. .specific_id =
  530. GetConstantValue(eval_context, interface.specific_id, phase)});
  531. }
  532. info.self_impls_constraints.reserve(orig.self_impls_constraints.size());
  533. for (const auto& interface : orig.self_impls_constraints) {
  534. info.self_impls_constraints.push_back(
  535. {.interface_id = interface.interface_id,
  536. .specific_id =
  537. GetConstantValue(eval_context, interface.specific_id, phase)});
  538. }
  539. info.rewrite_constraints.reserve(orig.rewrite_constraints.size());
  540. for (const auto& rewrite : orig.rewrite_constraints) {
  541. // `where` requirements using `.Self` should not be considered symbolic.
  542. auto lhs_id =
  543. GetConstantValueIgnoringPeriodSelf(eval_context, rewrite.lhs_id, phase);
  544. auto rhs_id =
  545. GetConstantValueIgnoringPeriodSelf(eval_context, rewrite.rhs_id, phase);
  546. info.rewrite_constraints.push_back({.lhs_id = lhs_id, .rhs_id = rhs_id});
  547. }
  548. // TODO: Process other requirements.
  549. info.other_requirements = orig.other_requirements;
  550. return info;
  551. }
  552. static auto GetConstantValue(EvalContext& eval_context,
  553. SemIR::FacetTypeId facet_type_id, Phase* phase)
  554. -> SemIR::FacetTypeId {
  555. SemIR::FacetTypeInfo info =
  556. GetConstantFacetTypeInfo(eval_context, facet_type_id, phase);
  557. info.Canonicalize();
  558. // TODO: Return `facet_type_id` if we can detect nothing has changed.
  559. return eval_context.facet_types().Add(info);
  560. }
  561. static auto GetConstantValue(EvalContext& eval_context,
  562. SemIR::EntityNameId entity_name_id, Phase* phase)
  563. -> SemIR::EntityNameId {
  564. const auto& bind_name = eval_context.entity_names().Get(entity_name_id);
  565. Phase name_phase;
  566. if (bind_name.name_id == SemIR::NameId::PeriodSelf) {
  567. name_phase = Phase::PeriodSelfSymbolic;
  568. } else if (!bind_name.bind_index().has_value()) {
  569. name_phase = Phase::Concrete;
  570. } else if (bind_name.is_template) {
  571. name_phase = Phase::TemplateSymbolic;
  572. } else {
  573. name_phase = Phase::CheckedSymbolic;
  574. }
  575. *phase = LatestPhase(*phase, name_phase);
  576. return eval_context.entity_names().MakeCanonical(entity_name_id);
  577. }
  578. // Replaces the specified field of the given typed instruction with its constant
  579. // value, if it has constant phase. Returns true on success, false if the value
  580. // has runtime phase.
  581. template <typename InstT, typename FieldIdT>
  582. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  583. InstT* inst, FieldIdT InstT::* field,
  584. Phase* phase) -> bool {
  585. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  586. if (!unwrapped.has_value() && (inst->*field).has_value()) {
  587. return false;
  588. }
  589. inst->*field = unwrapped;
  590. return true;
  591. }
  592. // Function template that can be called with an argument of type `T`. Used below
  593. // to detect which overloads of `GetConstantValue` exist.
  594. template <typename T>
  595. static void Accept(T /*arg*/) {}
  596. // Determines whether a `GetConstantValue` overload exists for a given ID type.
  597. // Note that we do not check whether `GetConstantValue` is *callable* with a
  598. // given ID type, because that would use the `InstId` overload for
  599. // `AbsoluteInstId` and similar wrapper types, which should be left alone.
  600. template <typename IdT>
  601. static constexpr bool HasGetConstantValueOverload = requires {
  602. Accept<auto (*)(EvalContext&, IdT, Phase*)->IdT>(GetConstantValue);
  603. };
  604. using ArgHandlerFnT = auto(EvalContext& context, int32_t arg, Phase* phase)
  605. -> int32_t;
  606. // Returns a lookup table to get constants by Id::Kind. Requires a null IdKind
  607. // as a parameter in order to get the type pack.
  608. template <typename... Types>
  609. static constexpr auto MakeArgHandlerTable(TypeEnum<Types...>* /*id_kind*/)
  610. -> std::array<ArgHandlerFnT*, SemIR::IdKind::NumValues> {
  611. std::array<ArgHandlerFnT*, SemIR::IdKind::NumValues> table = {};
  612. ((table[SemIR::IdKind::template For<Types>.ToIndex()] =
  613. [](EvalContext& eval_context, int32_t arg, Phase* phase) -> int32_t {
  614. auto id = SemIR::Inst::FromRaw<Types>(arg);
  615. if constexpr (HasGetConstantValueOverload<Types>) {
  616. // If we have a custom `GetConstantValue` overload, call it.
  617. return SemIR::Inst::ToRaw(GetConstantValue(eval_context, id, phase));
  618. } else {
  619. // Otherwise, we assume the value is already constant.
  620. return arg;
  621. }
  622. }),
  623. ...);
  624. table[SemIR::IdKind::Invalid.ToIndex()] = [](EvalContext& /*context*/,
  625. int32_t /*arg*/,
  626. Phase* /*phase*/) -> int32_t {
  627. CARBON_FATAL("Instruction has argument with invalid IdKind");
  628. };
  629. table[SemIR::IdKind::None.ToIndex()] =
  630. [](EvalContext& /*context*/, int32_t arg, Phase* /*phase*/) -> int32_t {
  631. return arg;
  632. };
  633. return table;
  634. }
  635. // Given the stored value `arg` of an instruction field and its corresponding
  636. // kind `kind`, returns the constant value to use for that field, if it has a
  637. // constant phase. `*phase` is updated to include the new constant value. If
  638. // the resulting phase is not constant, the returned value is not useful and
  639. // will typically be `NoneIndex`.
  640. static auto GetConstantValueForArg(EvalContext& eval_context,
  641. SemIR::Inst::ArgAndKind arg_and_kind,
  642. Phase* phase) -> int32_t {
  643. static constexpr auto Table =
  644. MakeArgHandlerTable(static_cast<SemIR::IdKind*>(nullptr));
  645. return Table[arg_and_kind.kind().ToIndex()](eval_context,
  646. arg_and_kind.value(), phase);
  647. }
  648. // Given an instruction, replaces its operands with their constant values from
  649. // the specified evaluation context. `*phase` is updated to describe the
  650. // constant phase of the result. Returns whether `*phase` is a constant phase;
  651. // if not, `inst` may not be fully updated and should not be used.
  652. static auto ReplaceAllFieldsWithConstantValues(EvalContext& eval_context,
  653. SemIR::Inst* inst, Phase* phase)
  654. -> bool {
  655. auto arg0 =
  656. GetConstantValueForArg(eval_context, inst->arg0_and_kind(), phase);
  657. if (!IsConstant(*phase)) {
  658. return false;
  659. }
  660. auto arg1 =
  661. GetConstantValueForArg(eval_context, inst->arg1_and_kind(), phase);
  662. if (!IsConstant(*phase)) {
  663. return false;
  664. }
  665. inst->SetArgs(arg0, arg1);
  666. return true;
  667. }
  668. // Given an instruction and its ID, replaces its type with the corresponding
  669. // value in this evaluation context. Updates `*phase` to describe the phase of
  670. // the result, and returns whether `*phase` is a constant phase.
  671. //
  672. // If the `InstId` is not provided, the instruction is assumed to be new and
  673. // therefore unattached, so the type is not updated.
  674. static auto ReplaceTypeWithConstantValue(EvalContext& eval_context,
  675. SemIR::InstId inst_id,
  676. SemIR::Inst* inst, Phase* phase)
  677. -> bool {
  678. if (inst_id.has_value()) {
  679. inst->SetType(GetTypeOfInst(eval_context, inst_id, phase));
  680. }
  681. return IsConstant(*phase);
  682. }
  683. template <typename InstT>
  684. static auto ReplaceTypeWithConstantValue(EvalContext& eval_context,
  685. SemIR::InstId inst_id, InstT* inst,
  686. Phase* phase) -> bool {
  687. if (inst_id.has_value()) {
  688. inst->type_id = GetTypeOfInst(eval_context, inst_id, phase);
  689. }
  690. return IsConstant(*phase);
  691. }
  692. template <typename... Types>
  693. static auto KindHasGetConstantValueOverload(TypeEnum<Types...> e) -> bool {
  694. static constexpr std::array<bool, SemIR::IdKind::NumTypes> Values = {
  695. (HasGetConstantValueOverload<Types>)...};
  696. return Values[e.ToIndex()];
  697. }
  698. static auto ResolveSpecificDeclForSpecificId(EvalContext& eval_context,
  699. SemIR::SpecificId specific_id)
  700. -> void {
  701. if (!specific_id.has_value()) {
  702. return;
  703. }
  704. const auto& specific = eval_context.specifics().Get(specific_id);
  705. const auto& generic = eval_context.generics().Get(specific.generic_id);
  706. if (specific_id == generic.self_specific_id) {
  707. // Impl witness table construction happens before its generic decl is
  708. // finish, in order to make the table's instructions dependent
  709. // instructions of the Impl's generic. But those instructions can refer to
  710. // the generic's self specific. We can not resolve the specific
  711. // declaration for the self specific until the generic is finished, but it
  712. // is explicitly resolved at that time in `FinishGenericDecl()`.
  713. return;
  714. }
  715. ResolveSpecificDecl(eval_context.context(), eval_context.fallback_loc_id(),
  716. specific_id);
  717. }
  718. // Resolves the specific declarations for a specific id in any field of the
  719. // `inst` instruction.
  720. static auto ResolveSpecificDeclForInst(EvalContext& eval_context,
  721. const SemIR::Inst& inst) -> void {
  722. for (auto arg_and_kind : {inst.arg0_and_kind(), inst.arg1_and_kind()}) {
  723. // This switch must handle any field type that has a GetConstantValue()
  724. // overload which canonicalizes a specific (and thus potentially forms a new
  725. // specific) as part of forming its constant value.
  726. CARBON_KIND_SWITCH(arg_and_kind) {
  727. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  728. const auto& info =
  729. eval_context.context().facet_types().Get(facet_type_id);
  730. for (const auto& interface : info.extend_constraints) {
  731. ResolveSpecificDeclForSpecificId(eval_context, interface.specific_id);
  732. }
  733. for (const auto& interface : info.self_impls_constraints) {
  734. ResolveSpecificDeclForSpecificId(eval_context, interface.specific_id);
  735. }
  736. break;
  737. }
  738. case CARBON_KIND(SemIR::SpecificId specific_id): {
  739. ResolveSpecificDeclForSpecificId(eval_context, specific_id);
  740. break;
  741. }
  742. case CARBON_KIND(SemIR::SpecificInterfaceId specific_interface_id): {
  743. ResolveSpecificDeclForSpecificId(eval_context,
  744. eval_context.specific_interfaces()
  745. .Get(specific_interface_id)
  746. .specific_id);
  747. break;
  748. }
  749. // These id types have a GetConstantValue() overload but that overload
  750. // does not canonicalize any SpecificId in the value type.
  751. case SemIR::IdKind::For<SemIR::DestInstId>:
  752. case SemIR::IdKind::For<SemIR::EntityNameId>:
  753. case SemIR::IdKind::For<SemIR::InstBlockId>:
  754. case SemIR::IdKind::For<SemIR::InstId>:
  755. case SemIR::IdKind::For<SemIR::MetaInstId>:
  756. case SemIR::IdKind::For<SemIR::StructTypeFieldsId>:
  757. case SemIR::IdKind::For<SemIR::TypeInstId>:
  758. break;
  759. case SemIR::IdKind::None:
  760. // No arg.
  761. break;
  762. default:
  763. CARBON_CHECK(
  764. !KindHasGetConstantValueOverload(arg_and_kind.kind()),
  765. "Missing case for {0} which has a GetConstantValue() overload",
  766. arg_and_kind.kind());
  767. break;
  768. }
  769. }
  770. }
  771. auto AddImportedConstant(Context& context, SemIR::Inst inst)
  772. -> SemIR::ConstantId {
  773. EvalContext eval_context(&context, SemIR::LocId::None);
  774. CARBON_CHECK(inst.kind().has_type(), "Can't import untyped instructions: {0}",
  775. inst.kind());
  776. Phase phase = GetPhase(context.constant_values(),
  777. context.types().GetConstantId(inst.type_id()));
  778. if (!ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  779. return SemIR::ConstantId::NotConstant;
  780. }
  781. return MakeConstantResult(context, inst, phase);
  782. }
  783. // Performs an index into a homogeneous aggregate, retrieving the specified
  784. // element.
  785. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  786. -> SemIR::ConstantId {
  787. Phase phase = Phase::Concrete;
  788. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  789. if (!index_id.has_value()) {
  790. return MakeNonConstantResult(phase);
  791. }
  792. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  793. if (!index) {
  794. CARBON_CHECK(phase != Phase::Concrete,
  795. "Concrete constant integer should be a literal");
  796. return MakeNonConstantResult(phase);
  797. }
  798. // Array indexing is invalid if the index is constant and out of range,
  799. // regardless of whether the array itself is constant.
  800. const auto& index_val = eval_context.ints().Get(index->int_id);
  801. auto aggregate_type_id = eval_context.GetTypeOfInst(inst.array_id);
  802. if (auto array_type =
  803. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  804. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  805. array_type->bound_id)) {
  806. // This awkward call to `getZExtValue` is a workaround for APInt not
  807. // supporting comparisons between integers of different bit widths.
  808. if (index_val.getActiveBits() > 64 ||
  809. eval_context.ints()
  810. .Get(bound->int_id)
  811. .ule(index_val.getZExtValue())) {
  812. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  813. "array index `{0}` is past the end of type {1}",
  814. TypedInt, SemIR::TypeId);
  815. eval_context.emitter().Emit(
  816. eval_context.GetDiagnosticLoc(inst.index_id), ArrayIndexOutOfBounds,
  817. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  818. return SemIR::ErrorInst::ConstantId;
  819. }
  820. }
  821. }
  822. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  823. if (!aggregate_id.has_value()) {
  824. return MakeNonConstantResult(phase);
  825. }
  826. auto aggregate =
  827. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  828. if (!aggregate) {
  829. // TODO: Consider forming a symbolic constant or reference constant array
  830. // index in this case.
  831. return MakeNonConstantResult(phase);
  832. }
  833. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  834. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  835. }
  836. // Forms a constant int type as an evaluation result. Requires that width_id is
  837. // constant.
  838. static auto MakeIntTypeResult(Context& context, SemIR::LocId loc_id,
  839. SemIR::IntKind int_kind, SemIR::InstId width_id,
  840. Phase phase) -> SemIR::ConstantId {
  841. auto result = SemIR::IntType{
  842. .type_id = GetSingletonType(context, SemIR::TypeType::TypeInstId),
  843. .int_kind = int_kind,
  844. .bit_width_id = width_id};
  845. if (!ValidateIntType(context, loc_id, result)) {
  846. return SemIR::ErrorInst::ConstantId;
  847. }
  848. return MakeConstantResult(context, result, phase);
  849. }
  850. // Performs a conversion between integer types, truncating if the value doesn't
  851. // fit in the destination type.
  852. static auto PerformIntConvert(Context& context, SemIR::InstId arg_id,
  853. SemIR::TypeId dest_type_id) -> SemIR::ConstantId {
  854. auto arg_val =
  855. context.ints().Get(context.insts().GetAs<SemIR::IntValue>(arg_id).int_id);
  856. auto [dest_is_signed, bit_width_id] =
  857. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  858. if (bit_width_id.has_value()) {
  859. // TODO: If the value fits in the destination type, reuse the existing
  860. // int_id rather than recomputing it. This is probably the most common case.
  861. bool src_is_signed = context.sem_ir().types().IsSignedInt(
  862. context.insts().Get(arg_id).type_id());
  863. unsigned width = context.ints().Get(bit_width_id).getZExtValue();
  864. arg_val =
  865. src_is_signed ? arg_val.sextOrTrunc(width) : arg_val.zextOrTrunc(width);
  866. }
  867. return MakeIntResult(context, dest_type_id, dest_is_signed, arg_val);
  868. }
  869. // Performs a conversion between integer types, diagnosing if the value doesn't
  870. // fit in the destination type.
  871. static auto PerformCheckedIntConvert(Context& context, SemIR::LocId loc_id,
  872. SemIR::InstId arg_id,
  873. SemIR::TypeId dest_type_id)
  874. -> SemIR::ConstantId {
  875. auto arg = context.insts().GetAs<SemIR::IntValue>(arg_id);
  876. auto arg_val = context.ints().Get(arg.int_id);
  877. auto [is_signed, bit_width_id] =
  878. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  879. auto width = bit_width_id.has_value()
  880. ? context.ints().Get(bit_width_id).getZExtValue()
  881. : arg_val.getBitWidth();
  882. if (!is_signed && arg_val.isNegative()) {
  883. CARBON_DIAGNOSTIC(
  884. NegativeIntInUnsignedType, Error,
  885. "negative integer value {0} converted to unsigned type {1}", TypedInt,
  886. SemIR::TypeId);
  887. context.emitter().Emit(loc_id, NegativeIntInUnsignedType,
  888. {.type = arg.type_id, .value = arg_val},
  889. dest_type_id);
  890. }
  891. unsigned arg_non_sign_bits = arg_val.getSignificantBits() - 1;
  892. if (arg_non_sign_bits + is_signed > width) {
  893. CARBON_DIAGNOSTIC(IntTooLargeForType, Error,
  894. "integer value {0} too large for type {1}", TypedInt,
  895. SemIR::TypeId);
  896. context.emitter().Emit(loc_id, IntTooLargeForType,
  897. {.type = arg.type_id, .value = arg_val},
  898. dest_type_id);
  899. }
  900. return MakeConstantResult(
  901. context, SemIR::IntValue{.type_id = dest_type_id, .int_id = arg.int_id},
  902. Phase::Concrete);
  903. }
  904. // Issues a diagnostic for a compile-time division by zero.
  905. static auto DiagnoseDivisionByZero(Context& context, SemIR::LocId loc_id)
  906. -> void {
  907. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  908. context.emitter().Emit(loc_id, CompileTimeDivisionByZero);
  909. }
  910. // Get an integer at a suitable bit-width: either `bit_width_id` if it has a
  911. // value, or the canonical width from the value store if not.
  912. static auto GetIntAtSuitableWidth(Context& context, IntId int_id,
  913. IntId bit_width_id) -> llvm::APInt {
  914. return bit_width_id.has_value()
  915. ? context.ints().GetAtWidth(int_id, bit_width_id)
  916. : context.ints().Get(int_id);
  917. }
  918. // Performs a builtin unary integer -> integer operation.
  919. static auto PerformBuiltinUnaryIntOp(Context& context, SemIR::LocId loc_id,
  920. SemIR::BuiltinFunctionKind builtin_kind,
  921. SemIR::InstId arg_id)
  922. -> SemIR::ConstantId {
  923. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  924. auto [is_signed, bit_width_id] =
  925. context.sem_ir().types().GetIntTypeInfo(op.type_id);
  926. llvm::APInt op_val = GetIntAtSuitableWidth(context, op.int_id, bit_width_id);
  927. switch (builtin_kind) {
  928. case SemIR::BuiltinFunctionKind::IntSNegate:
  929. if (op_val.isMinSignedValue()) {
  930. if (bit_width_id.has_value()) {
  931. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  932. "integer overflow in negation of {0}", TypedInt);
  933. context.emitter().Emit(loc_id, CompileTimeIntegerNegateOverflow,
  934. {.type = op.type_id, .value = op_val});
  935. } else {
  936. // Widen the integer so we don't overflow into the sign bit.
  937. op_val = op_val.sext(op_val.getBitWidth() +
  938. llvm::APInt::APINT_BITS_PER_WORD);
  939. }
  940. }
  941. op_val.negate();
  942. break;
  943. case SemIR::BuiltinFunctionKind::IntUNegate:
  944. CARBON_CHECK(bit_width_id.has_value(), "Unsigned negate on unsized int");
  945. op_val.negate();
  946. break;
  947. case SemIR::BuiltinFunctionKind::IntComplement:
  948. // TODO: Should we have separate builtins for signed and unsigned
  949. // complement? Like with signed/unsigned negate, these operations do
  950. // different things to the integer value, even though they do the same
  951. // thing to the bits. We treat IntLiteral complement as signed complement,
  952. // given that the result of unsigned complement depends on the bit width.
  953. op_val.flipAllBits();
  954. break;
  955. default:
  956. CARBON_FATAL("Unexpected builtin kind");
  957. }
  958. return MakeIntResult(context, op.type_id, is_signed, std::move(op_val));
  959. }
  960. namespace {
  961. // A pair of APInts that are the operands of a binary operator. We use an
  962. // aggregate rather than `std::pair` to allow RVO of the individual ints.
  963. struct APIntBinaryOperands {
  964. llvm::APInt lhs;
  965. llvm::APInt rhs;
  966. };
  967. } // namespace
  968. // Get a pair of integers at the same suitable bit-width: either their actual
  969. // width if they have a fixed width, or the smallest canonical width in which
  970. // they both fit otherwise.
  971. static auto GetIntsAtSuitableWidth(Context& context, IntId lhs_id, IntId rhs_id,
  972. IntId bit_width_id) -> APIntBinaryOperands {
  973. // Unsized operands: take the wider of the bit widths.
  974. if (!bit_width_id.has_value()) {
  975. APIntBinaryOperands result = {.lhs = context.ints().Get(lhs_id),
  976. .rhs = context.ints().Get(rhs_id)};
  977. if (result.lhs.getBitWidth() != result.rhs.getBitWidth()) {
  978. if (result.lhs.getBitWidth() > result.rhs.getBitWidth()) {
  979. result.rhs = result.rhs.sext(result.lhs.getBitWidth());
  980. } else {
  981. result.lhs = result.lhs.sext(result.rhs.getBitWidth());
  982. }
  983. }
  984. return result;
  985. }
  986. return {.lhs = context.ints().GetAtWidth(lhs_id, bit_width_id),
  987. .rhs = context.ints().GetAtWidth(rhs_id, bit_width_id)};
  988. }
  989. namespace {
  990. // The result of performing a binary int operation.
  991. struct BinaryIntOpResult {
  992. llvm::APInt result_val;
  993. bool overflow;
  994. Lex::TokenKind op_token;
  995. };
  996. } // namespace
  997. // Computes the result of a homogeneous binary (int, int) -> int operation.
  998. static auto ComputeBinaryIntOpResult(SemIR::BuiltinFunctionKind builtin_kind,
  999. const llvm::APInt& lhs_val,
  1000. const llvm::APInt& rhs_val)
  1001. -> BinaryIntOpResult {
  1002. llvm::APInt result_val;
  1003. bool overflow = false;
  1004. Lex::TokenKind op_token = Lex::TokenKind::Not;
  1005. switch (builtin_kind) {
  1006. // Arithmetic.
  1007. case SemIR::BuiltinFunctionKind::IntSAdd:
  1008. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  1009. op_token = Lex::TokenKind::Plus;
  1010. break;
  1011. case SemIR::BuiltinFunctionKind::IntSSub:
  1012. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  1013. op_token = Lex::TokenKind::Minus;
  1014. break;
  1015. case SemIR::BuiltinFunctionKind::IntSMul:
  1016. result_val = lhs_val.smul_ov(rhs_val, overflow);
  1017. op_token = Lex::TokenKind::Star;
  1018. break;
  1019. case SemIR::BuiltinFunctionKind::IntSDiv:
  1020. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  1021. op_token = Lex::TokenKind::Slash;
  1022. break;
  1023. case SemIR::BuiltinFunctionKind::IntSMod:
  1024. result_val = lhs_val.srem(rhs_val);
  1025. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  1026. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  1027. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  1028. op_token = Lex::TokenKind::Percent;
  1029. break;
  1030. case SemIR::BuiltinFunctionKind::IntUAdd:
  1031. result_val = lhs_val + rhs_val;
  1032. op_token = Lex::TokenKind::Plus;
  1033. break;
  1034. case SemIR::BuiltinFunctionKind::IntUSub:
  1035. result_val = lhs_val - rhs_val;
  1036. op_token = Lex::TokenKind::Minus;
  1037. break;
  1038. case SemIR::BuiltinFunctionKind::IntUMul:
  1039. result_val = lhs_val * rhs_val;
  1040. op_token = Lex::TokenKind::Star;
  1041. break;
  1042. case SemIR::BuiltinFunctionKind::IntUDiv:
  1043. result_val = lhs_val.udiv(rhs_val);
  1044. op_token = Lex::TokenKind::Slash;
  1045. break;
  1046. case SemIR::BuiltinFunctionKind::IntUMod:
  1047. result_val = lhs_val.urem(rhs_val);
  1048. op_token = Lex::TokenKind::Percent;
  1049. break;
  1050. // Bitwise.
  1051. case SemIR::BuiltinFunctionKind::IntAnd:
  1052. result_val = lhs_val & rhs_val;
  1053. op_token = Lex::TokenKind::And;
  1054. break;
  1055. case SemIR::BuiltinFunctionKind::IntOr:
  1056. result_val = lhs_val | rhs_val;
  1057. op_token = Lex::TokenKind::Pipe;
  1058. break;
  1059. case SemIR::BuiltinFunctionKind::IntXor:
  1060. result_val = lhs_val ^ rhs_val;
  1061. op_token = Lex::TokenKind::Caret;
  1062. break;
  1063. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1064. case SemIR::BuiltinFunctionKind::IntRightShift:
  1065. CARBON_FATAL("Non-homogeneous operation handled separately.");
  1066. default:
  1067. CARBON_FATAL("Unexpected operation kind.");
  1068. }
  1069. return {.result_val = std::move(result_val),
  1070. .overflow = overflow,
  1071. .op_token = op_token};
  1072. }
  1073. // Performs a builtin integer bit shift operation.
  1074. static auto PerformBuiltinIntShiftOp(Context& context, SemIR::LocId loc_id,
  1075. SemIR::BuiltinFunctionKind builtin_kind,
  1076. SemIR::InstId lhs_id, SemIR::InstId rhs_id)
  1077. -> SemIR::ConstantId {
  1078. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1079. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1080. auto [lhs_is_signed, lhs_bit_width_id] =
  1081. context.sem_ir().types().GetIntTypeInfo(lhs.type_id);
  1082. llvm::APInt lhs_val =
  1083. GetIntAtSuitableWidth(context, lhs.int_id, lhs_bit_width_id);
  1084. const auto& rhs_orig_val = context.ints().Get(rhs.int_id);
  1085. if (lhs_bit_width_id.has_value() && rhs_orig_val.uge(lhs_val.getBitWidth())) {
  1086. CARBON_DIAGNOSTIC(
  1087. CompileTimeShiftOutOfRange, Error,
  1088. "shift distance >= type width of {0} in `{1} {2:<<|>>} {3}`", unsigned,
  1089. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1090. context.emitter().Emit(
  1091. loc_id, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  1092. {.type = lhs.type_id, .value = lhs_val},
  1093. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1094. {.type = rhs.type_id, .value = rhs_orig_val});
  1095. // TODO: Is it useful to recover by returning 0 or -1?
  1096. return SemIR::ErrorInst::ConstantId;
  1097. }
  1098. if (rhs_orig_val.isNegative() &&
  1099. context.sem_ir().types().IsSignedInt(rhs.type_id)) {
  1100. CARBON_DIAGNOSTIC(CompileTimeShiftNegative, Error,
  1101. "shift distance negative in `{0} {1:<<|>>} {2}`",
  1102. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1103. context.emitter().Emit(
  1104. loc_id, CompileTimeShiftNegative,
  1105. {.type = lhs.type_id, .value = lhs_val},
  1106. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1107. {.type = rhs.type_id, .value = rhs_orig_val});
  1108. // TODO: Is it useful to recover by returning 0 or -1?
  1109. return SemIR::ErrorInst::ConstantId;
  1110. }
  1111. llvm::APInt result_val;
  1112. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  1113. if (!lhs_bit_width_id.has_value() && !lhs_val.isZero()) {
  1114. // Ensure we don't generate a ridiculously large integer through a bit
  1115. // shift.
  1116. auto width = rhs_orig_val.trySExtValue();
  1117. if (!width ||
  1118. *width > IntStore::MaxIntWidth - lhs_val.getSignificantBits()) {
  1119. CARBON_DIAGNOSTIC(CompileTimeUnsizedShiftOutOfRange, Error,
  1120. "shift distance of {0} would result in an "
  1121. "integer whose width is greater than the "
  1122. "maximum supported width of {1}",
  1123. TypedInt, int);
  1124. context.emitter().Emit(loc_id, CompileTimeUnsizedShiftOutOfRange,
  1125. {.type = rhs.type_id, .value = rhs_orig_val},
  1126. IntStore::MaxIntWidth);
  1127. return SemIR::ErrorInst::ConstantId;
  1128. }
  1129. lhs_val = lhs_val.sext(
  1130. IntStore::CanonicalBitWidth(lhs_val.getSignificantBits() + *width));
  1131. }
  1132. result_val =
  1133. lhs_val.shl(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1134. } else if (lhs_is_signed) {
  1135. result_val =
  1136. lhs_val.ashr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1137. } else {
  1138. CARBON_CHECK(lhs_bit_width_id.has_value(), "Logical shift on unsized int");
  1139. result_val =
  1140. lhs_val.lshr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1141. }
  1142. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  1143. std::move(result_val));
  1144. }
  1145. // Performs a homogeneous builtin binary integer -> integer operation.
  1146. static auto PerformBuiltinBinaryIntOp(Context& context, SemIR::LocId loc_id,
  1147. SemIR::BuiltinFunctionKind builtin_kind,
  1148. SemIR::InstId lhs_id,
  1149. SemIR::InstId rhs_id)
  1150. -> SemIR::ConstantId {
  1151. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1152. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1153. CARBON_CHECK(rhs.type_id == lhs.type_id, "Heterogeneous builtin integer op!");
  1154. auto type_id = lhs.type_id;
  1155. auto [is_signed, bit_width_id] =
  1156. context.sem_ir().types().GetIntTypeInfo(type_id);
  1157. auto [lhs_val, rhs_val] =
  1158. GetIntsAtSuitableWidth(context, lhs.int_id, rhs.int_id, bit_width_id);
  1159. // Check for division by zero.
  1160. switch (builtin_kind) {
  1161. case SemIR::BuiltinFunctionKind::IntSDiv:
  1162. case SemIR::BuiltinFunctionKind::IntSMod:
  1163. case SemIR::BuiltinFunctionKind::IntUDiv:
  1164. case SemIR::BuiltinFunctionKind::IntUMod:
  1165. if (rhs_val.isZero()) {
  1166. DiagnoseDivisionByZero(context, loc_id);
  1167. return SemIR::ErrorInst::ConstantId;
  1168. }
  1169. break;
  1170. default:
  1171. break;
  1172. }
  1173. BinaryIntOpResult result =
  1174. ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1175. if (result.overflow && !bit_width_id.has_value()) {
  1176. // Retry with a larger bit width. Most operations can only overflow by one
  1177. // bit, but signed n-bit multiplication can overflow to 2n-1 bits. We don't
  1178. // need to handle unsigned multiplication here because it's not permitted
  1179. // for unsized integers.
  1180. //
  1181. // Note that we speculatively first perform the calculation in the width of
  1182. // the wider operand: smaller operations are faster and overflow to a wider
  1183. // integer is unlikely to be needed, especially given that the width will
  1184. // have been rounded up to a multiple of 64 bits by the int store.
  1185. CARBON_CHECK(builtin_kind != SemIR::BuiltinFunctionKind::IntUMul,
  1186. "Unsigned arithmetic requires a fixed bitwidth");
  1187. int new_width =
  1188. builtin_kind == SemIR::BuiltinFunctionKind::IntSMul
  1189. ? lhs_val.getBitWidth() * 2
  1190. : IntStore::CanonicalBitWidth(lhs_val.getBitWidth() + 1);
  1191. new_width = std::min(new_width, IntStore::MaxIntWidth);
  1192. lhs_val = context.ints().GetAtWidth(lhs.int_id, new_width);
  1193. rhs_val = context.ints().GetAtWidth(rhs.int_id, new_width);
  1194. // Note that this can in theory still overflow if we limited `new_width` to
  1195. // `MaxIntWidth`. In that case we fall through to the signed overflow
  1196. // diagnostic below.
  1197. result = ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1198. CARBON_CHECK(!result.overflow || new_width == IntStore::MaxIntWidth);
  1199. }
  1200. if (result.overflow) {
  1201. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  1202. "integer overflow in calculation `{0} {1} {2}`", TypedInt,
  1203. Lex::TokenKind, TypedInt);
  1204. context.emitter().Emit(loc_id, CompileTimeIntegerOverflow,
  1205. {.type = type_id, .value = lhs_val}, result.op_token,
  1206. {.type = type_id, .value = rhs_val});
  1207. }
  1208. return MakeIntResult(context, type_id, is_signed,
  1209. std::move(result.result_val));
  1210. }
  1211. // Performs a builtin integer comparison.
  1212. static auto PerformBuiltinIntComparison(Context& context,
  1213. SemIR::BuiltinFunctionKind builtin_kind,
  1214. SemIR::InstId lhs_id,
  1215. SemIR::InstId rhs_id,
  1216. SemIR::TypeId bool_type_id)
  1217. -> SemIR::ConstantId {
  1218. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1219. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1220. llvm::APInt lhs_val = context.ints().Get(lhs.int_id);
  1221. llvm::APInt rhs_val = context.ints().Get(rhs.int_id);
  1222. bool result;
  1223. switch (builtin_kind) {
  1224. case SemIR::BuiltinFunctionKind::IntEq:
  1225. result = (lhs_val == rhs_val);
  1226. break;
  1227. case SemIR::BuiltinFunctionKind::IntNeq:
  1228. result = (lhs_val != rhs_val);
  1229. break;
  1230. case SemIR::BuiltinFunctionKind::IntLess:
  1231. result = lhs_val.slt(rhs_val);
  1232. break;
  1233. case SemIR::BuiltinFunctionKind::IntLessEq:
  1234. result = lhs_val.sle(rhs_val);
  1235. break;
  1236. case SemIR::BuiltinFunctionKind::IntGreater:
  1237. result = lhs_val.sgt(rhs_val);
  1238. break;
  1239. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  1240. result = lhs_val.sge(rhs_val);
  1241. break;
  1242. default:
  1243. CARBON_FATAL("Unexpected operation kind.");
  1244. }
  1245. return MakeBoolResult(context, bool_type_id, result);
  1246. }
  1247. // Performs a builtin unary float -> float operation.
  1248. static auto PerformBuiltinUnaryFloatOp(Context& context,
  1249. SemIR::BuiltinFunctionKind builtin_kind,
  1250. SemIR::InstId arg_id)
  1251. -> SemIR::ConstantId {
  1252. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  1253. auto op_val = context.floats().Get(op.float_id);
  1254. switch (builtin_kind) {
  1255. case SemIR::BuiltinFunctionKind::FloatNegate:
  1256. op_val.changeSign();
  1257. break;
  1258. default:
  1259. CARBON_FATAL("Unexpected builtin kind");
  1260. }
  1261. return MakeFloatResult(context, op.type_id, std::move(op_val));
  1262. }
  1263. // Performs a builtin binary float -> float operation.
  1264. static auto PerformBuiltinBinaryFloatOp(Context& context,
  1265. SemIR::BuiltinFunctionKind builtin_kind,
  1266. SemIR::InstId lhs_id,
  1267. SemIR::InstId rhs_id)
  1268. -> SemIR::ConstantId {
  1269. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  1270. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  1271. auto lhs_val = context.floats().Get(lhs.float_id);
  1272. auto rhs_val = context.floats().Get(rhs.float_id);
  1273. llvm::APFloat result_val(lhs_val.getSemantics());
  1274. switch (builtin_kind) {
  1275. case SemIR::BuiltinFunctionKind::FloatAdd:
  1276. result_val = lhs_val + rhs_val;
  1277. break;
  1278. case SemIR::BuiltinFunctionKind::FloatSub:
  1279. result_val = lhs_val - rhs_val;
  1280. break;
  1281. case SemIR::BuiltinFunctionKind::FloatMul:
  1282. result_val = lhs_val * rhs_val;
  1283. break;
  1284. case SemIR::BuiltinFunctionKind::FloatDiv:
  1285. result_val = lhs_val / rhs_val;
  1286. break;
  1287. default:
  1288. CARBON_FATAL("Unexpected operation kind.");
  1289. }
  1290. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  1291. }
  1292. // Performs a builtin float comparison.
  1293. static auto PerformBuiltinFloatComparison(
  1294. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1295. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  1296. -> SemIR::ConstantId {
  1297. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  1298. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  1299. const auto& lhs_val = context.floats().Get(lhs.float_id);
  1300. const auto& rhs_val = context.floats().Get(rhs.float_id);
  1301. bool result;
  1302. switch (builtin_kind) {
  1303. case SemIR::BuiltinFunctionKind::FloatEq:
  1304. result = (lhs_val == rhs_val);
  1305. break;
  1306. case SemIR::BuiltinFunctionKind::FloatNeq:
  1307. result = (lhs_val != rhs_val);
  1308. break;
  1309. case SemIR::BuiltinFunctionKind::FloatLess:
  1310. result = lhs_val < rhs_val;
  1311. break;
  1312. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1313. result = lhs_val <= rhs_val;
  1314. break;
  1315. case SemIR::BuiltinFunctionKind::FloatGreater:
  1316. result = lhs_val > rhs_val;
  1317. break;
  1318. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  1319. result = lhs_val >= rhs_val;
  1320. break;
  1321. default:
  1322. CARBON_FATAL("Unexpected operation kind.");
  1323. }
  1324. return MakeBoolResult(context, bool_type_id, result);
  1325. }
  1326. // Performs a builtin boolean comparison.
  1327. static auto PerformBuiltinBoolComparison(
  1328. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1329. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id) {
  1330. bool lhs = context.insts().GetAs<SemIR::BoolLiteral>(lhs_id).value.ToBool();
  1331. bool rhs = context.insts().GetAs<SemIR::BoolLiteral>(rhs_id).value.ToBool();
  1332. return MakeBoolResult(context, bool_type_id,
  1333. builtin_kind == SemIR::BuiltinFunctionKind::BoolEq
  1334. ? lhs == rhs
  1335. : lhs != rhs);
  1336. }
  1337. // Returns a constant for a call to a builtin function.
  1338. static auto MakeConstantForBuiltinCall(EvalContext& eval_context,
  1339. SemIR::LocId loc_id, SemIR::Call call,
  1340. SemIR::BuiltinFunctionKind builtin_kind,
  1341. llvm::ArrayRef<SemIR::InstId> arg_ids,
  1342. Phase phase) -> SemIR::ConstantId {
  1343. auto& context = eval_context.context();
  1344. switch (builtin_kind) {
  1345. case SemIR::BuiltinFunctionKind::None:
  1346. CARBON_FATAL("Not a builtin function.");
  1347. case SemIR::BuiltinFunctionKind::NoOp: {
  1348. // Return an empty tuple value.
  1349. auto type_id = GetTupleType(eval_context.context(), {});
  1350. return MakeConstantResult(
  1351. eval_context.context(),
  1352. SemIR::TupleValue{.type_id = type_id,
  1353. .elements_id = SemIR::InstBlockId::Empty},
  1354. phase);
  1355. }
  1356. case SemIR::BuiltinFunctionKind::PrintChar:
  1357. case SemIR::BuiltinFunctionKind::PrintInt:
  1358. case SemIR::BuiltinFunctionKind::ReadChar:
  1359. case SemIR::BuiltinFunctionKind::IntSAddAssign:
  1360. case SemIR::BuiltinFunctionKind::IntSSubAssign:
  1361. case SemIR::BuiltinFunctionKind::IntSMulAssign:
  1362. case SemIR::BuiltinFunctionKind::IntSDivAssign:
  1363. case SemIR::BuiltinFunctionKind::IntSModAssign:
  1364. case SemIR::BuiltinFunctionKind::IntUAddAssign:
  1365. case SemIR::BuiltinFunctionKind::IntUSubAssign:
  1366. case SemIR::BuiltinFunctionKind::IntUMulAssign:
  1367. case SemIR::BuiltinFunctionKind::IntUDivAssign:
  1368. case SemIR::BuiltinFunctionKind::IntUModAssign:
  1369. case SemIR::BuiltinFunctionKind::IntAndAssign:
  1370. case SemIR::BuiltinFunctionKind::IntOrAssign:
  1371. case SemIR::BuiltinFunctionKind::IntXorAssign:
  1372. case SemIR::BuiltinFunctionKind::IntLeftShiftAssign:
  1373. case SemIR::BuiltinFunctionKind::IntRightShiftAssign: {
  1374. // These are runtime-only builtins.
  1375. // TODO: Consider tracking this on the `BuiltinFunctionKind`.
  1376. return SemIR::ConstantId::NotConstant;
  1377. }
  1378. case SemIR::BuiltinFunctionKind::TypeAnd: {
  1379. CARBON_CHECK(arg_ids.size() == 2);
  1380. auto lhs_facet_type_id = SemIR::FacetTypeId::None;
  1381. auto rhs_facet_type_id = SemIR::FacetTypeId::None;
  1382. for (auto [facet_type_id, type_arg_id] :
  1383. llvm::zip(std::to_array({&lhs_facet_type_id, &rhs_facet_type_id}),
  1384. context.types().GetBlockAsTypeInstIds(arg_ids))) {
  1385. if (auto facet_type =
  1386. context.insts().TryGetAs<SemIR::FacetType>(type_arg_id)) {
  1387. *facet_type_id = facet_type->facet_type_id;
  1388. } else {
  1389. CARBON_DIAGNOSTIC(FacetTypeRequiredForTypeAndOperator, Error,
  1390. "non-facet type {0} combined with `&` operator",
  1391. SemIR::TypeId);
  1392. // TODO: Find a location for the lhs or rhs specifically, instead of
  1393. // the whole thing. If that's not possible we can change the text to
  1394. // say if it's referring to the left or the right side for the error.
  1395. // The `arg_id` instruction has no location in it for some reason.
  1396. context.emitter().Emit(
  1397. loc_id, FacetTypeRequiredForTypeAndOperator,
  1398. context.types().GetTypeIdForTypeInstId(type_arg_id));
  1399. }
  1400. }
  1401. // Allow errors to be diagnosed for both sides of the operator before
  1402. // returning here if any error occurred on either side.
  1403. if (!lhs_facet_type_id.has_value() || !rhs_facet_type_id.has_value()) {
  1404. return SemIR::ErrorInst::ConstantId;
  1405. }
  1406. // Reuse one of the argument instructions if nothing has changed.
  1407. if (lhs_facet_type_id == rhs_facet_type_id) {
  1408. return context.types().GetConstantId(
  1409. context.types().GetTypeIdForTypeInstId(arg_ids[0]));
  1410. }
  1411. auto info = SemIR::FacetTypeInfo::Combine(
  1412. context.facet_types().Get(lhs_facet_type_id),
  1413. context.facet_types().Get(rhs_facet_type_id));
  1414. info.Canonicalize();
  1415. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1416. }
  1417. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  1418. return context.constant_values().Get(SemIR::IntLiteralType::TypeInstId);
  1419. }
  1420. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  1421. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Signed,
  1422. arg_ids[0], phase);
  1423. }
  1424. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  1425. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Unsigned,
  1426. arg_ids[0], phase);
  1427. }
  1428. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  1429. // TODO: Support a symbolic constant width.
  1430. if (phase != Phase::Concrete) {
  1431. break;
  1432. }
  1433. if (!ValidateFloatBitWidth(context, loc_id, arg_ids[0])) {
  1434. return SemIR::ErrorInst::ConstantId;
  1435. }
  1436. return context.constant_values().Get(SemIR::LegacyFloatType::TypeInstId);
  1437. }
  1438. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  1439. return context.constant_values().Get(SemIR::BoolType::TypeInstId);
  1440. }
  1441. // Integer conversions.
  1442. case SemIR::BuiltinFunctionKind::IntConvert: {
  1443. if (phase != Phase::Concrete) {
  1444. return MakeConstantResult(context, call, phase);
  1445. }
  1446. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1447. }
  1448. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  1449. if (phase != Phase::Concrete) {
  1450. return MakeConstantResult(context, call, phase);
  1451. }
  1452. return PerformCheckedIntConvert(context, loc_id, arg_ids[0],
  1453. call.type_id);
  1454. }
  1455. // Unary integer -> integer operations.
  1456. case SemIR::BuiltinFunctionKind::IntSNegate:
  1457. case SemIR::BuiltinFunctionKind::IntUNegate:
  1458. case SemIR::BuiltinFunctionKind::IntComplement: {
  1459. if (phase != Phase::Concrete) {
  1460. break;
  1461. }
  1462. return PerformBuiltinUnaryIntOp(context, loc_id, builtin_kind,
  1463. arg_ids[0]);
  1464. }
  1465. // Homogeneous binary integer -> integer operations.
  1466. case SemIR::BuiltinFunctionKind::IntSAdd:
  1467. case SemIR::BuiltinFunctionKind::IntSSub:
  1468. case SemIR::BuiltinFunctionKind::IntSMul:
  1469. case SemIR::BuiltinFunctionKind::IntSDiv:
  1470. case SemIR::BuiltinFunctionKind::IntSMod:
  1471. case SemIR::BuiltinFunctionKind::IntUAdd:
  1472. case SemIR::BuiltinFunctionKind::IntUSub:
  1473. case SemIR::BuiltinFunctionKind::IntUMul:
  1474. case SemIR::BuiltinFunctionKind::IntUDiv:
  1475. case SemIR::BuiltinFunctionKind::IntUMod:
  1476. case SemIR::BuiltinFunctionKind::IntAnd:
  1477. case SemIR::BuiltinFunctionKind::IntOr:
  1478. case SemIR::BuiltinFunctionKind::IntXor: {
  1479. if (phase != Phase::Concrete) {
  1480. break;
  1481. }
  1482. return PerformBuiltinBinaryIntOp(context, loc_id, builtin_kind,
  1483. arg_ids[0], arg_ids[1]);
  1484. }
  1485. // Bit shift operations.
  1486. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1487. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1488. if (phase != Phase::Concrete) {
  1489. break;
  1490. }
  1491. return PerformBuiltinIntShiftOp(context, loc_id, builtin_kind, arg_ids[0],
  1492. arg_ids[1]);
  1493. }
  1494. // Integer comparisons.
  1495. case SemIR::BuiltinFunctionKind::IntEq:
  1496. case SemIR::BuiltinFunctionKind::IntNeq:
  1497. case SemIR::BuiltinFunctionKind::IntLess:
  1498. case SemIR::BuiltinFunctionKind::IntLessEq:
  1499. case SemIR::BuiltinFunctionKind::IntGreater:
  1500. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1501. if (phase != Phase::Concrete) {
  1502. break;
  1503. }
  1504. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1505. arg_ids[1], call.type_id);
  1506. }
  1507. // Unary float -> float operations.
  1508. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1509. if (phase != Phase::Concrete) {
  1510. break;
  1511. }
  1512. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1513. }
  1514. // Binary float -> float operations.
  1515. case SemIR::BuiltinFunctionKind::FloatAdd:
  1516. case SemIR::BuiltinFunctionKind::FloatSub:
  1517. case SemIR::BuiltinFunctionKind::FloatMul:
  1518. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1519. if (phase != Phase::Concrete) {
  1520. break;
  1521. }
  1522. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1523. arg_ids[1]);
  1524. }
  1525. // Float comparisons.
  1526. case SemIR::BuiltinFunctionKind::FloatEq:
  1527. case SemIR::BuiltinFunctionKind::FloatNeq:
  1528. case SemIR::BuiltinFunctionKind::FloatLess:
  1529. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1530. case SemIR::BuiltinFunctionKind::FloatGreater:
  1531. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1532. if (phase != Phase::Concrete) {
  1533. break;
  1534. }
  1535. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1536. arg_ids[1], call.type_id);
  1537. }
  1538. // Bool comparisons.
  1539. case SemIR::BuiltinFunctionKind::BoolEq:
  1540. case SemIR::BuiltinFunctionKind::BoolNeq: {
  1541. if (phase != Phase::Concrete) {
  1542. break;
  1543. }
  1544. return PerformBuiltinBoolComparison(context, builtin_kind, arg_ids[0],
  1545. arg_ids[1], call.type_id);
  1546. }
  1547. }
  1548. return SemIR::ConstantId::NotConstant;
  1549. }
  1550. // Makes a constant for a call instruction.
  1551. static auto MakeConstantForCall(EvalContext& eval_context,
  1552. SemIR::InstId inst_id, SemIR::Call call)
  1553. -> SemIR::ConstantId {
  1554. Phase phase = Phase::Concrete;
  1555. // A call with an invalid argument list is used to represent an erroneous
  1556. // call.
  1557. //
  1558. // TODO: Use a better representation for this.
  1559. if (call.args_id == SemIR::InstBlockId::None) {
  1560. return SemIR::ErrorInst::ConstantId;
  1561. }
  1562. // Find the constant value of the callee.
  1563. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1564. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1565. auto callee_function =
  1566. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  1567. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1568. if (callee_function.function_id.has_value()) {
  1569. // Calls to builtins might be constant.
  1570. builtin_kind = eval_context.functions()
  1571. .Get(callee_function.function_id)
  1572. .builtin_function_kind;
  1573. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  1574. // TODO: Eventually we'll want to treat some kinds of non-builtin
  1575. // functions as producing constants.
  1576. return SemIR::ConstantId::NotConstant;
  1577. }
  1578. } else {
  1579. // Calls to non-functions, such as calls to generic entity names, might be
  1580. // constant.
  1581. }
  1582. // Find the argument values and the return type.
  1583. bool has_constant_operands =
  1584. has_constant_callee &&
  1585. ReplaceTypeWithConstantValue(eval_context, inst_id, &call, &phase) &&
  1586. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1587. &phase);
  1588. if (phase == Phase::UnknownDueToError) {
  1589. return SemIR::ErrorInst::ConstantId;
  1590. }
  1591. // If any operand of the call is non-constant, the call is non-constant.
  1592. // TODO: Some builtin calls might allow some operands to be non-constant.
  1593. if (!has_constant_operands) {
  1594. if (builtin_kind.IsCompTimeOnly(
  1595. eval_context.sem_ir(), eval_context.inst_blocks().Get(call.args_id),
  1596. call.type_id)) {
  1597. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1598. "non-constant call to compile-time-only function");
  1599. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1600. "compile-time-only function declared here");
  1601. eval_context.emitter()
  1602. .Build(inst_id, NonConstantCallToCompTimeOnlyFunction)
  1603. .Note(eval_context.functions()
  1604. .Get(callee_function.function_id)
  1605. .latest_decl_id(),
  1606. CompTimeOnlyFunctionHere)
  1607. .Emit();
  1608. }
  1609. return SemIR::ConstantId::NotConstant;
  1610. }
  1611. // Handle calls to builtins.
  1612. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1613. return MakeConstantForBuiltinCall(
  1614. eval_context, SemIR::LocId(inst_id), call, builtin_kind,
  1615. eval_context.inst_blocks().Get(call.args_id), phase);
  1616. }
  1617. return SemIR::ConstantId::NotConstant;
  1618. }
  1619. // Given an instruction, compute its phase based on its operands.
  1620. static auto ComputeInstPhase(Context& context, SemIR::Inst inst) -> Phase {
  1621. EvalContext eval_context(&context, SemIR::LocId::None);
  1622. auto phase = GetPhase(context.constant_values(),
  1623. context.types().GetConstantId(inst.type_id()));
  1624. GetConstantValueForArg(eval_context, inst.arg0_and_kind(), &phase);
  1625. GetConstantValueForArg(eval_context, inst.arg1_and_kind(), &phase);
  1626. CARBON_CHECK(phase != Phase::Runtime);
  1627. return phase;
  1628. }
  1629. // Convert a ConstantEvalResult to a ConstantId. Factored out of
  1630. // TryEvalTypedInst to avoid repeated instantiation of common code.
  1631. static auto ConvertEvalResultToConstantId(Context& context,
  1632. ConstantEvalResult result,
  1633. Phase orig_phase)
  1634. -> SemIR::ConstantId {
  1635. if (result.is_new()) {
  1636. return MakeConstantResult(
  1637. context, result.new_inst(),
  1638. result.same_phase_as_inst()
  1639. ? orig_phase
  1640. : ComputeInstPhase(context, result.new_inst()));
  1641. }
  1642. return result.existing();
  1643. }
  1644. // Evaluates an instruction of a known type in an evaluation context. The
  1645. // default behavior of this function depends on the constant kind of the
  1646. // instruction:
  1647. //
  1648. // - InstConstantKind::Never: returns ConstantId::NotConstant.
  1649. // - InstConstantKind::Indirect, SymbolicOnly, SymbolicOrReference,
  1650. // Conditional: evaluates all the operands of the instruction, and calls
  1651. // `EvalConstantInst` to evaluate the resulting constant instruction.
  1652. // - InstConstantKind::WheneverPossible, Always: evaluates all the operands of
  1653. // the instruction, and produces the resulting constant instruction as the
  1654. // result.
  1655. // - InstConstantKind::Unique: returns the `inst_id` as the resulting
  1656. // constant.
  1657. //
  1658. // Returns an error constant ID if any of the nested evaluations fail, and
  1659. // returns NotConstant if any of the nested evaluations is non-constant.
  1660. //
  1661. // This template is explicitly specialized for instructions that need special
  1662. // handling.
  1663. template <typename InstT>
  1664. static auto TryEvalTypedInst(EvalContext& eval_context, SemIR::InstId inst_id,
  1665. SemIR::Inst inst) -> SemIR::ConstantId {
  1666. constexpr auto ConstantKind = InstT::Kind.constant_kind();
  1667. if constexpr (ConstantKind == SemIR::InstConstantKind::Never) {
  1668. return SemIR::ConstantId::NotConstant;
  1669. } else if constexpr (ConstantKind == SemIR::InstConstantKind::AlwaysUnique) {
  1670. CARBON_CHECK(inst_id.has_value());
  1671. return SemIR::ConstantId::ForConcreteConstant(inst_id);
  1672. } else {
  1673. // Build a constant instruction by replacing each non-constant operand with
  1674. // its constant value.
  1675. Phase phase = Phase::Concrete;
  1676. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &inst, &phase) ||
  1677. !ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  1678. if constexpr (ConstantKind == SemIR::InstConstantKind::Always) {
  1679. CARBON_CHECK(phase == Phase::UnknownDueToError,
  1680. "{0} should always be constant", InstT::Kind);
  1681. }
  1682. return MakeNonConstantResult(phase);
  1683. }
  1684. // When canonicalizing a SpecificId, we defer resolving the specific's
  1685. // declaration until here, to avoid resolving declarations from imported
  1686. // specifics. (Imported instructions are not evaluated.)
  1687. ResolveSpecificDeclForInst(eval_context, inst);
  1688. if constexpr (ConstantKind == SemIR::InstConstantKind::Always ||
  1689. ConstantKind == SemIR::InstConstantKind::WheneverPossible) {
  1690. return MakeConstantResult(eval_context.context(), inst, phase);
  1691. } else if constexpr (ConstantKind == SemIR::InstConstantKind::InstAction) {
  1692. auto result_inst_id = PerformDelayedAction(
  1693. eval_context.context(), SemIR::LocId(inst_id), inst.As<InstT>());
  1694. if (result_inst_id.has_value()) {
  1695. // The result is an instruction.
  1696. return MakeConstantResult(
  1697. eval_context.context(),
  1698. SemIR::InstValue{.type_id = SemIR::InstType::TypeId,
  1699. .inst_id = result_inst_id},
  1700. Phase::Concrete);
  1701. }
  1702. // Couldn't perform the action because it's still dependent.
  1703. return MakeConstantResult(eval_context.context(), inst,
  1704. Phase::TemplateSymbolic);
  1705. } else if constexpr (InstT::Kind.constant_needs_inst_id() !=
  1706. SemIR::InstConstantNeedsInstIdKind::No) {
  1707. CARBON_CHECK(inst_id.has_value());
  1708. return ConvertEvalResultToConstantId(
  1709. eval_context.context(),
  1710. EvalConstantInst(eval_context.context(), inst_id, inst.As<InstT>()),
  1711. phase);
  1712. } else {
  1713. return ConvertEvalResultToConstantId(
  1714. eval_context.context(),
  1715. EvalConstantInst(eval_context.context(), inst.As<InstT>()), phase);
  1716. }
  1717. }
  1718. }
  1719. // Specialize evaluation for array indexing because we want to check the index
  1720. // expression even if the array expression is non-constant.
  1721. template <>
  1722. auto TryEvalTypedInst<SemIR::ArrayIndex>(EvalContext& eval_context,
  1723. SemIR::InstId /*inst_id*/,
  1724. SemIR::Inst inst)
  1725. -> SemIR::ConstantId {
  1726. return PerformArrayIndex(eval_context, inst.As<SemIR::ArrayIndex>());
  1727. }
  1728. // Specialize evaluation for function calls because we want to check the callee
  1729. // expression even if an argument expression is non-constant, and because we
  1730. // will eventually want to perform control flow handling here.
  1731. template <>
  1732. auto TryEvalTypedInst<SemIR::Call>(EvalContext& eval_context,
  1733. SemIR::InstId inst_id, SemIR::Inst inst)
  1734. -> SemIR::ConstantId {
  1735. return MakeConstantForCall(eval_context, inst_id, inst.As<SemIR::Call>());
  1736. }
  1737. // ImportRefLoaded can have a constant value, but it's owned and maintained by
  1738. // `import_ref.cpp`, not by us.
  1739. // TODO: Rearrange how `ImportRefLoaded` instructions are created so we never
  1740. // call this.
  1741. template <>
  1742. auto TryEvalTypedInst<SemIR::ImportRefLoaded>(EvalContext& /*eval_context*/,
  1743. SemIR::InstId /*inst_id*/,
  1744. SemIR::Inst /*inst*/)
  1745. -> SemIR::ConstantId {
  1746. return SemIR::ConstantId::NotConstant;
  1747. }
  1748. // Symbolic bindings are a special case because they can reach into the eval
  1749. // context and produce a context-specific value.
  1750. template <>
  1751. auto TryEvalTypedInst<SemIR::BindSymbolicName>(EvalContext& eval_context,
  1752. SemIR::InstId inst_id,
  1753. SemIR::Inst inst)
  1754. -> SemIR::ConstantId {
  1755. auto bind = inst.As<SemIR::BindSymbolicName>();
  1756. // If we know which specific we're evaluating within and this is an argument
  1757. // of that specific, its constant value is the corresponding argument value.
  1758. const auto& bind_name = eval_context.entity_names().Get(bind.entity_name_id);
  1759. if (bind_name.bind_index().has_value()) {
  1760. if (auto value =
  1761. eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  1762. value.has_value()) {
  1763. return value;
  1764. }
  1765. }
  1766. // The constant form of a symbolic binding is an idealized form of the
  1767. // original, with no equivalent value.
  1768. Phase phase = Phase::Concrete;
  1769. bind.value_id = SemIR::InstId::None;
  1770. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &bind, &phase) ||
  1771. !ReplaceFieldWithConstantValue(eval_context, &bind,
  1772. &SemIR::BindSymbolicName::entity_name_id,
  1773. &phase)) {
  1774. return MakeNonConstantResult(phase);
  1775. }
  1776. return MakeConstantResult(eval_context.context(), bind, phase);
  1777. }
  1778. static auto IsPeriodSelf(EvalContext& eval_context, SemIR::ConstantId const_id)
  1779. -> bool {
  1780. // This also rejects the singleton Error value as it's concrete.
  1781. if (!const_id.is_symbolic()) {
  1782. return false;
  1783. }
  1784. const auto& symbolic =
  1785. eval_context.constant_values().GetSymbolicConstant(const_id);
  1786. // Fast early reject before doing more expensive operations.
  1787. if (symbolic.dependence != SemIR::ConstantDependence::PeriodSelf) {
  1788. return false;
  1789. }
  1790. auto inst_id = symbolic.inst_id;
  1791. // Unwrap the `FacetAccessType` instruction, which we get when the `.Self` is
  1792. // converted to `type`.
  1793. if (auto facet_access_type =
  1794. eval_context.insts().TryGetAs<SemIR::FacetAccessType>(inst_id)) {
  1795. inst_id = facet_access_type->facet_value_inst_id;
  1796. }
  1797. if (auto bind_symbolic_name =
  1798. eval_context.insts().TryGetAs<SemIR::BindSymbolicName>(inst_id)) {
  1799. const auto& bind_name =
  1800. eval_context.entity_names().Get(bind_symbolic_name->entity_name_id);
  1801. return bind_name.name_id == SemIR::NameId::PeriodSelf;
  1802. }
  1803. return false;
  1804. }
  1805. // TODO: Convert this to an EvalConstantInst instruction. This will require
  1806. // providing a `GetConstantValue` overload for a requirement block.
  1807. template <>
  1808. auto TryEvalTypedInst<SemIR::WhereExpr>(EvalContext& eval_context,
  1809. SemIR::InstId /*inst_id*/,
  1810. SemIR::Inst inst) -> SemIR::ConstantId {
  1811. auto typed_inst = inst.As<SemIR::WhereExpr>();
  1812. Phase phase = Phase::Concrete;
  1813. SemIR::TypeId base_facet_type_id =
  1814. eval_context.GetTypeOfInst(typed_inst.period_self_id);
  1815. SemIR::Inst base_facet_inst =
  1816. eval_context.types().GetAsInst(base_facet_type_id);
  1817. SemIR::FacetTypeInfo info = {.other_requirements = false};
  1818. // `where` provides that the base facet is an error, `type`, or a facet
  1819. // type.
  1820. if (auto facet_type = base_facet_inst.TryAs<SemIR::FacetType>()) {
  1821. info = GetConstantFacetTypeInfo(eval_context, facet_type->facet_type_id,
  1822. &phase);
  1823. } else if (base_facet_type_id == SemIR::ErrorInst::TypeId) {
  1824. return SemIR::ErrorInst::ConstantId;
  1825. } else {
  1826. CARBON_CHECK(base_facet_type_id == SemIR::TypeType::TypeId,
  1827. "Unexpected type_id: {0}, inst: {1}", base_facet_type_id,
  1828. base_facet_inst);
  1829. }
  1830. if (typed_inst.requirements_id.has_value()) {
  1831. auto insts = eval_context.inst_blocks().Get(typed_inst.requirements_id);
  1832. for (auto inst_id : insts) {
  1833. if (auto rewrite =
  1834. eval_context.insts().TryGetAs<SemIR::RequirementRewrite>(
  1835. inst_id)) {
  1836. // `where` requirements using `.Self` should not be considered
  1837. // symbolic.
  1838. auto lhs_id = GetConstantValueIgnoringPeriodSelf(
  1839. eval_context, rewrite->lhs_id, &phase);
  1840. auto rhs_id = GetConstantValueIgnoringPeriodSelf(
  1841. eval_context, rewrite->rhs_id, &phase);
  1842. info.rewrite_constraints.push_back(
  1843. {.lhs_id = lhs_id, .rhs_id = rhs_id});
  1844. } else if (auto impls =
  1845. eval_context.insts().TryGetAs<SemIR::RequirementImpls>(
  1846. inst_id)) {
  1847. SemIR::ConstantId lhs = eval_context.GetConstantValue(impls->lhs_id);
  1848. SemIR::ConstantId rhs = eval_context.GetConstantValue(impls->rhs_id);
  1849. if (rhs != SemIR::ErrorInst::ConstantId &&
  1850. IsPeriodSelf(eval_context, lhs)) {
  1851. auto rhs_inst_id = eval_context.constant_values().GetInstId(rhs);
  1852. if (rhs_inst_id == SemIR::TypeType::TypeInstId) {
  1853. // `.Self impls type` -> nothing to do.
  1854. } else {
  1855. auto facet_type =
  1856. eval_context.insts().GetAs<SemIR::FacetType>(rhs_inst_id);
  1857. SemIR::FacetTypeInfo more_info = GetConstantFacetTypeInfo(
  1858. eval_context, facet_type.facet_type_id, &phase);
  1859. // The way to prevent lookup into the interface requirements of a
  1860. // facet type is to put it to the right of a `.Self impls`, which we
  1861. // accomplish by putting them into `self_impls_constraints`.
  1862. llvm::append_range(info.self_impls_constraints,
  1863. more_info.extend_constraints);
  1864. llvm::append_range(info.self_impls_constraints,
  1865. more_info.self_impls_constraints);
  1866. // Other requirements are copied in.
  1867. llvm::append_range(info.rewrite_constraints,
  1868. more_info.rewrite_constraints);
  1869. info.other_requirements |= more_info.other_requirements;
  1870. }
  1871. } else {
  1872. // TODO: Handle `impls` constraints beyond `.Self impls`.
  1873. info.other_requirements = true;
  1874. }
  1875. } else {
  1876. // TODO: Handle other requirements
  1877. info.other_requirements = true;
  1878. }
  1879. }
  1880. }
  1881. info.Canonicalize();
  1882. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1883. }
  1884. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1885. static auto TryEvalInstInContext(EvalContext& eval_context,
  1886. SemIR::InstId inst_id, SemIR::Inst inst)
  1887. -> SemIR::ConstantId {
  1888. using EvalInstFn =
  1889. auto(EvalContext & eval_context, SemIR::InstId inst_id, SemIR::Inst inst)
  1890. ->SemIR::ConstantId;
  1891. static constexpr EvalInstFn* EvalInstFns[] = {
  1892. #define CARBON_SEM_IR_INST_KIND(Kind) &TryEvalTypedInst<SemIR::Kind>,
  1893. #include "toolchain/sem_ir/inst_kind.def"
  1894. };
  1895. [[clang::musttail]] return EvalInstFns[inst.kind().AsInt()](eval_context,
  1896. inst_id, inst);
  1897. }
  1898. auto TryEvalInstUnsafe(Context& context, SemIR::InstId inst_id,
  1899. SemIR::Inst inst) -> SemIR::ConstantId {
  1900. EvalContext eval_context(&context, SemIR::LocId(inst_id));
  1901. return TryEvalInstInContext(eval_context, inst_id, inst);
  1902. }
  1903. auto TryEvalBlockForSpecific(Context& context, SemIR::LocId loc_id,
  1904. SemIR::SpecificId specific_id,
  1905. SemIR::GenericInstIndex::Region region)
  1906. -> SemIR::InstBlockId {
  1907. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1908. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1909. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1910. llvm::SmallVector<SemIR::InstId> result;
  1911. result.resize(eval_block.size(), SemIR::InstId::None);
  1912. EvalContext eval_context(&context, loc_id, specific_id,
  1913. SpecificEvalInfo{
  1914. .region = region,
  1915. .values = result,
  1916. });
  1917. Diagnostics::AnnotationScope annotate_diagnostics(
  1918. &context.emitter(), [&](auto& builder) {
  1919. CARBON_DIAGNOSTIC(ResolvingSpecificHere, Note, "in {0} used here",
  1920. SemIR::SpecificId);
  1921. builder.Note(loc_id, ResolvingSpecificHere, specific_id);
  1922. });
  1923. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1924. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1925. context.insts().Get(inst_id));
  1926. result[i] = context.constant_values().GetInstId(const_id);
  1927. CARBON_CHECK(result[i].has_value(), "Failed to evaluate {0} in eval block",
  1928. context.insts().Get(inst_id));
  1929. }
  1930. return context.inst_blocks().Add(result);
  1931. }
  1932. } // namespace Carbon::Check