eval.cpp 82 KB

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