eval.cpp 82 KB

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