eval.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  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/diagnostic_helpers.h"
  7. #include "toolchain/check/generic.h"
  8. #include "toolchain/diagnostics/diagnostic_emitter.h"
  9. #include "toolchain/diagnostics/format_providers.h"
  10. #include "toolchain/sem_ir/builtin_function_kind.h"
  11. #include "toolchain/sem_ir/function.h"
  12. #include "toolchain/sem_ir/generic.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/inst_kind.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::Check {
  17. namespace {
  18. // Information about an eval block of a specific that we are currently building.
  19. struct SpecificEvalInfo {
  20. // The region within the specific whose eval block we are building.
  21. SemIR::GenericInstIndex::Region region;
  22. // The work-in-progress contents of the eval block.
  23. llvm::ArrayRef<SemIR::InstId> values;
  24. };
  25. // Information about the context within which we are performing evaluation.
  26. class EvalContext {
  27. public:
  28. explicit EvalContext(
  29. Context& context,
  30. SemIR::SpecificId specific_id = SemIR::SpecificId::Invalid,
  31. std::optional<SpecificEvalInfo> specific_eval_info = std::nullopt)
  32. : context_(context),
  33. specific_id_(specific_id),
  34. specific_eval_info_(specific_eval_info) {}
  35. // Gets the value of the specified compile-time binding in this context.
  36. // Returns `Invalid` if the value is not fixed in this context.
  37. auto GetCompileTimeBindValue(SemIR::CompileTimeBindIndex bind_index)
  38. -> SemIR::ConstantId {
  39. if (!bind_index.is_valid() || !specific_id_.is_valid()) {
  40. return SemIR::ConstantId::Invalid;
  41. }
  42. const auto& specific = specifics().Get(specific_id_);
  43. auto args = inst_blocks().Get(specific.args_id);
  44. // Bindings past the ones with known arguments can appear as local
  45. // bindings of entities declared within this generic.
  46. if (static_cast<size_t>(bind_index.index) >= args.size()) {
  47. return SemIR::ConstantId::Invalid;
  48. }
  49. return constant_values().Get(args[bind_index.index]);
  50. }
  51. // Given a constant value from the SemIR we're evaluating, finds the
  52. // corresponding constant value to use in the context of this evaluation.
  53. // This can be different if the original SemIR is for a generic and we are
  54. // evaluating with specific arguments for the generic parameters.
  55. auto GetInContext(SemIR::ConstantId const_id) -> SemIR::ConstantId {
  56. if (!const_id.is_symbolic()) {
  57. return const_id;
  58. }
  59. // While resolving a specific, map from previous instructions in the eval
  60. // block into their evaluated values. These values won't be present on the
  61. // specific itself yet, so `GetConstantInSpecific` won't be able to find
  62. // them.
  63. if (specific_eval_info_) {
  64. const auto& symbolic_info =
  65. constant_values().GetSymbolicConstant(const_id);
  66. if (symbolic_info.index.is_valid() &&
  67. symbolic_info.generic_id ==
  68. specifics().Get(specific_id_).generic_id &&
  69. symbolic_info.index.region() == specific_eval_info_->region) {
  70. auto inst_id = specific_eval_info_->values[symbolic_info.index.index()];
  71. CARBON_CHECK(inst_id.is_valid(),
  72. "Forward reference in eval block: index {0} referenced "
  73. "before evaluation",
  74. symbolic_info.index.index());
  75. return constant_values().Get(inst_id);
  76. }
  77. }
  78. // Map from a specific constant value to the canonical value.
  79. return GetConstantInSpecific(sem_ir(), specific_id_, const_id);
  80. }
  81. // Gets the constant value of the specified instruction in this context.
  82. auto GetConstantValue(SemIR::InstId inst_id) -> SemIR::ConstantId {
  83. return GetInContext(constant_values().Get(inst_id));
  84. }
  85. // Gets the constant value of the specified type in this context.
  86. auto GetConstantValue(SemIR::TypeId type_id) -> SemIR::ConstantId {
  87. return GetInContext(types().GetConstantId(type_id));
  88. }
  89. // Gets the constant value of the specified type in this context.
  90. auto GetConstantValueAsType(SemIR::TypeId id) -> SemIR::TypeId {
  91. return context().GetTypeIdForTypeConstant(GetConstantValue(id));
  92. }
  93. // Gets the instruction describing the constant value of the specified type in
  94. // this context.
  95. auto GetConstantValueAsInst(SemIR::TypeId id) -> SemIR::Inst {
  96. return insts().Get(
  97. context().constant_values().GetInstId(GetConstantValue(id)));
  98. }
  99. auto ints() -> CanonicalValueStore<IntId>& { return sem_ir().ints(); }
  100. auto floats() -> FloatValueStore& { return sem_ir().floats(); }
  101. auto entity_names() -> SemIR::EntityNameStore& {
  102. return sem_ir().entity_names();
  103. }
  104. auto functions() -> const ValueStore<SemIR::FunctionId>& {
  105. return sem_ir().functions();
  106. }
  107. auto classes() -> const ValueStore<SemIR::ClassId>& {
  108. return sem_ir().classes();
  109. }
  110. auto interfaces() -> const ValueStore<SemIR::InterfaceId>& {
  111. return sem_ir().interfaces();
  112. }
  113. auto specifics() -> const SemIR::SpecificStore& {
  114. return sem_ir().specifics();
  115. }
  116. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  117. return sem_ir().type_blocks();
  118. }
  119. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  120. auto inst_blocks() -> SemIR::InstBlockStore& {
  121. return sem_ir().inst_blocks();
  122. }
  123. // Gets the constant value store. Note that this does not provide the constant
  124. // values that should be used from this evaluation context, and so should be
  125. // used with caution.
  126. auto constant_values() -> const SemIR::ConstantValueStore& {
  127. return sem_ir().constant_values();
  128. }
  129. // Gets the types store. Note that this does not provide the type values that
  130. // should be used from this evaluation context, and so should be used with
  131. // caution.
  132. auto types() -> const SemIR::TypeStore& { return sem_ir().types(); }
  133. auto context() -> Context& { return context_; }
  134. auto sem_ir() -> SemIR::File& { return context().sem_ir(); }
  135. auto emitter() -> Context::DiagnosticEmitter& { return context().emitter(); }
  136. private:
  137. // The type-checking context in which we're performing evaluation.
  138. Context& context_;
  139. // The specific that we are evaluating within.
  140. SemIR::SpecificId specific_id_;
  141. // If we are currently evaluating an eval block for `specific_id_`,
  142. // information about that evaluation.
  143. std::optional<SpecificEvalInfo> specific_eval_info_;
  144. };
  145. } // namespace
  146. namespace {
  147. // The evaluation phase for an expression, computed by evaluation. These are
  148. // ordered so that the phase of an expression is the numerically highest phase
  149. // of its constituent evaluations. Note that an expression with any runtime
  150. // component is known to have Runtime phase even if it involves an evaluation
  151. // with UnknownDueToError phase.
  152. enum class Phase : uint8_t {
  153. // Value could be entirely and concretely computed.
  154. Template,
  155. // Evaluation phase is symbolic because the expression involves a reference to
  156. // a symbolic binding.
  157. Symbolic,
  158. // The evaluation phase is unknown because evaluation encountered an
  159. // already-diagnosed semantic or syntax error. This is treated as being
  160. // potentially constant, but with an unknown phase.
  161. UnknownDueToError,
  162. // The expression has runtime phase because of a non-constant subexpression.
  163. Runtime,
  164. };
  165. } // namespace
  166. // Gets the phase in which the value of a constant will become available.
  167. static auto GetPhase(SemIR::ConstantId constant_id) -> Phase {
  168. if (!constant_id.is_constant()) {
  169. return Phase::Runtime;
  170. } else if (constant_id == SemIR::ConstantId::Error) {
  171. return Phase::UnknownDueToError;
  172. } else if (constant_id.is_template()) {
  173. return Phase::Template;
  174. } else {
  175. CARBON_CHECK(constant_id.is_symbolic());
  176. return Phase::Symbolic;
  177. }
  178. }
  179. // Returns the later of two phases.
  180. static auto LatestPhase(Phase a, Phase b) -> Phase {
  181. return static_cast<Phase>(
  182. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  183. }
  184. // Forms a `constant_id` describing a given evaluation result.
  185. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  186. -> SemIR::ConstantId {
  187. switch (phase) {
  188. case Phase::Template:
  189. return context.AddConstant(inst, /*is_symbolic=*/false);
  190. case Phase::Symbolic:
  191. return context.AddConstant(inst, /*is_symbolic=*/true);
  192. case Phase::UnknownDueToError:
  193. return SemIR::ConstantId::Error;
  194. case Phase::Runtime:
  195. return SemIR::ConstantId::NotConstant;
  196. }
  197. }
  198. // Forms a `constant_id` describing why an evaluation was not constant.
  199. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  200. return phase == Phase::UnknownDueToError ? SemIR::ConstantId::Error
  201. : SemIR::ConstantId::NotConstant;
  202. }
  203. // Converts a bool value into a ConstantId.
  204. static auto MakeBoolResult(Context& context, SemIR::TypeId bool_type_id,
  205. bool result) -> SemIR::ConstantId {
  206. return MakeConstantResult(
  207. context,
  208. SemIR::BoolLiteral{.type_id = bool_type_id,
  209. .value = SemIR::BoolValue::From(result)},
  210. Phase::Template);
  211. }
  212. // Converts an APInt value into a ConstantId.
  213. static auto MakeIntResult(Context& context, SemIR::TypeId type_id,
  214. llvm::APInt value) -> SemIR::ConstantId {
  215. auto result = context.ints().Add(std::move(value));
  216. return MakeConstantResult(
  217. context, SemIR::IntValue{.type_id = type_id, .int_id = result},
  218. Phase::Template);
  219. }
  220. // Converts an APFloat value into a ConstantId.
  221. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  222. llvm::APFloat value) -> SemIR::ConstantId {
  223. auto result = context.floats().Add(std::move(value));
  224. return MakeConstantResult(
  225. context, SemIR::FloatLiteral{.type_id = type_id, .float_id = result},
  226. Phase::Template);
  227. }
  228. // `GetConstantValue` checks to see whether the provided ID describes a value
  229. // with constant phase, and if so, returns the corresponding constant value.
  230. // Overloads are provided for different kinds of ID.
  231. // If the given instruction is constant, returns its constant value.
  232. static auto GetConstantValue(EvalContext& eval_context, SemIR::InstId inst_id,
  233. Phase* phase) -> SemIR::InstId {
  234. auto const_id = eval_context.GetConstantValue(inst_id);
  235. *phase = LatestPhase(*phase, GetPhase(const_id));
  236. return eval_context.constant_values().GetInstId(const_id);
  237. }
  238. // Given a type which may refer to a generic parameter, returns the
  239. // corresponding type in the evaluation context.
  240. static auto GetConstantValue(EvalContext& eval_context, SemIR::TypeId type_id,
  241. Phase* phase) -> SemIR::TypeId {
  242. auto const_id = eval_context.GetConstantValue(type_id);
  243. *phase = LatestPhase(*phase, GetPhase(const_id));
  244. return eval_context.context().GetTypeIdForTypeConstant(const_id);
  245. }
  246. // If the given instruction block contains only constants, returns a
  247. // corresponding block of those values.
  248. static auto GetConstantValue(EvalContext& eval_context,
  249. SemIR::InstBlockId inst_block_id, Phase* phase)
  250. -> SemIR::InstBlockId {
  251. if (!inst_block_id.is_valid()) {
  252. return SemIR::InstBlockId::Invalid;
  253. }
  254. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  255. llvm::SmallVector<SemIR::InstId> const_insts;
  256. for (auto inst_id : insts) {
  257. auto const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  258. if (!const_inst_id.is_valid()) {
  259. return SemIR::InstBlockId::Invalid;
  260. }
  261. // Once we leave the small buffer, we know the first few elements are all
  262. // constant, so it's likely that the entire block is constant. Resize to the
  263. // target size given that we're going to allocate memory now anyway.
  264. if (const_insts.size() == const_insts.capacity()) {
  265. const_insts.reserve(insts.size());
  266. }
  267. const_insts.push_back(const_inst_id);
  268. }
  269. // TODO: If the new block is identical to the original block, and we know the
  270. // old ID was canonical, return the original ID.
  271. return eval_context.inst_blocks().AddCanonical(const_insts);
  272. }
  273. // Compute the constant value of a type block. This may be different from the
  274. // input type block if we have known generic arguments.
  275. static auto GetConstantValue(EvalContext& eval_context,
  276. SemIR::TypeBlockId type_block_id, Phase* phase)
  277. -> SemIR::TypeBlockId {
  278. if (!type_block_id.is_valid()) {
  279. return SemIR::TypeBlockId::Invalid;
  280. }
  281. auto types = eval_context.type_blocks().Get(type_block_id);
  282. llvm::SmallVector<SemIR::TypeId> new_types;
  283. for (auto type_id : types) {
  284. auto new_type_id = GetConstantValue(eval_context, type_id, phase);
  285. if (!new_type_id.is_valid()) {
  286. return SemIR::TypeBlockId::Invalid;
  287. }
  288. // Once we leave the small buffer, we know the first few elements are all
  289. // constant, so it's likely that the entire block is constant. Resize to the
  290. // target size given that we're going to allocate memory now anyway.
  291. if (new_types.size() == new_types.capacity()) {
  292. new_types.reserve(types.size());
  293. }
  294. new_types.push_back(new_type_id);
  295. }
  296. // TODO: If the new block is identical to the original block, and we know the
  297. // old ID was canonical, return the original ID.
  298. return eval_context.type_blocks().AddCanonical(new_types);
  299. }
  300. // The constant value of a specific is the specific with the corresponding
  301. // constant values for its arguments.
  302. static auto GetConstantValue(EvalContext& eval_context,
  303. SemIR::SpecificId specific_id, Phase* phase)
  304. -> SemIR::SpecificId {
  305. if (!specific_id.is_valid()) {
  306. return SemIR::SpecificId::Invalid;
  307. }
  308. const auto& specific = eval_context.specifics().Get(specific_id);
  309. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  310. if (!args_id.is_valid()) {
  311. return SemIR::SpecificId::Invalid;
  312. }
  313. if (args_id == specific.args_id) {
  314. return specific_id;
  315. }
  316. return MakeSpecific(eval_context.context(), specific.generic_id, args_id);
  317. }
  318. // Replaces the specified field of the given typed instruction with its constant
  319. // value, if it has constant phase. Returns true on success, false if the value
  320. // has runtime phase.
  321. template <typename InstT, typename FieldIdT>
  322. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  323. InstT* inst, FieldIdT InstT::*field,
  324. Phase* phase) -> bool {
  325. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  326. if (!unwrapped.is_valid() && (inst->*field).is_valid()) {
  327. return false;
  328. }
  329. inst->*field = unwrapped;
  330. return true;
  331. }
  332. // If the specified fields of the given typed instruction have constant values,
  333. // replaces the fields with their constant values and builds a corresponding
  334. // constant value. Otherwise returns `ConstantId::NotConstant`. Returns
  335. // `ConstantId::Error` if any subexpression is an error.
  336. //
  337. // The constant value is then checked by calling `validate_fn(typed_inst)`,
  338. // which should return a `bool` indicating whether the new constant is valid. If
  339. // validation passes, `transform_fn(typed_inst)` is called to produce the final
  340. // constant instruction, and a corresponding ConstantId for the new constant is
  341. // returned. If validation fails, it should produce a suitable error message.
  342. // `ConstantId::Error` is returned.
  343. template <typename InstT, typename ValidateFn, typename TransformFn,
  344. typename... EachFieldIdT>
  345. static auto RebuildIfFieldsAreConstantImpl(
  346. EvalContext& eval_context, SemIR::Inst inst, ValidateFn validate_fn,
  347. TransformFn transform_fn, EachFieldIdT InstT::*... each_field_id)
  348. -> SemIR::ConstantId {
  349. // Build a constant instruction by replacing each non-constant operand with
  350. // its constant value.
  351. auto typed_inst = inst.As<InstT>();
  352. Phase phase = Phase::Template;
  353. if ((ReplaceFieldWithConstantValue(eval_context, &typed_inst, each_field_id,
  354. &phase) &&
  355. ...)) {
  356. if (phase == Phase::UnknownDueToError || !validate_fn(typed_inst)) {
  357. return SemIR::ConstantId::Error;
  358. }
  359. return MakeConstantResult(eval_context.context(), transform_fn(typed_inst),
  360. phase);
  361. }
  362. return MakeNonConstantResult(phase);
  363. }
  364. // Same as above but with an identity transform function.
  365. template <typename InstT, typename ValidateFn, typename... EachFieldIdT>
  366. static auto RebuildAndValidateIfFieldsAreConstant(
  367. EvalContext& eval_context, SemIR::Inst inst, ValidateFn validate_fn,
  368. EachFieldIdT InstT::*... each_field_id) -> SemIR::ConstantId {
  369. return RebuildIfFieldsAreConstantImpl(eval_context, inst, validate_fn,
  370. std::identity{}, each_field_id...);
  371. }
  372. // Same as above but with no validation step.
  373. template <typename InstT, typename TransformFn, typename... EachFieldIdT>
  374. static auto TransformIfFieldsAreConstant(EvalContext& eval_context,
  375. SemIR::Inst inst,
  376. TransformFn transform_fn,
  377. EachFieldIdT InstT::*... each_field_id)
  378. -> SemIR::ConstantId {
  379. return RebuildIfFieldsAreConstantImpl(
  380. eval_context, inst, [](...) { return true; }, transform_fn,
  381. each_field_id...);
  382. }
  383. // Same as above but with no validation or transform step.
  384. template <typename InstT, typename... EachFieldIdT>
  385. static auto RebuildIfFieldsAreConstant(EvalContext& eval_context,
  386. SemIR::Inst inst,
  387. EachFieldIdT InstT::*... each_field_id)
  388. -> SemIR::ConstantId {
  389. return RebuildIfFieldsAreConstantImpl(
  390. eval_context, inst, [](...) { return true; }, std::identity{},
  391. each_field_id...);
  392. }
  393. // Rebuilds the given aggregate initialization instruction as a corresponding
  394. // constant aggregate value, if its elements are all constants.
  395. static auto RebuildInitAsValue(EvalContext& eval_context, SemIR::Inst inst,
  396. SemIR::InstKind value_kind)
  397. -> SemIR::ConstantId {
  398. return TransformIfFieldsAreConstant(
  399. eval_context, inst,
  400. [&](SemIR::AnyAggregateInit result) {
  401. return SemIR::AnyAggregateValue{.kind = value_kind,
  402. .type_id = result.type_id,
  403. .elements_id = result.elements_id};
  404. },
  405. &SemIR::AnyAggregateInit::type_id, &SemIR::AnyAggregateInit::elements_id);
  406. }
  407. // Performs an access into an aggregate, retrieving the specified element.
  408. static auto PerformAggregateAccess(EvalContext& eval_context, SemIR::Inst inst)
  409. -> SemIR::ConstantId {
  410. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  411. Phase phase = Phase::Template;
  412. if (auto aggregate_id =
  413. GetConstantValue(eval_context, access_inst.aggregate_id, &phase);
  414. aggregate_id.is_valid()) {
  415. if (auto aggregate =
  416. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(
  417. aggregate_id)) {
  418. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  419. auto index = static_cast<size_t>(access_inst.index.index);
  420. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  421. // `Phase` is not used here. If this element is a template constant, then
  422. // so is the result of indexing, even if the aggregate also contains a
  423. // symbolic context.
  424. return eval_context.GetConstantValue(elements[index]);
  425. } else {
  426. CARBON_CHECK(phase != Phase::Template,
  427. "Failed to evaluate template constant {0}", inst);
  428. }
  429. }
  430. return MakeNonConstantResult(phase);
  431. }
  432. // Performs an index into a homogeneous aggregate, retrieving the specified
  433. // element.
  434. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  435. -> SemIR::ConstantId {
  436. Phase phase = Phase::Template;
  437. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  438. if (!index_id.is_valid()) {
  439. return MakeNonConstantResult(phase);
  440. }
  441. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  442. if (!index) {
  443. CARBON_CHECK(phase != Phase::Template,
  444. "Template constant integer should be a literal");
  445. return MakeNonConstantResult(phase);
  446. }
  447. // Array indexing is invalid if the index is constant and out of range,
  448. // regardless of whether the array itself is constant.
  449. const auto& index_val = eval_context.ints().Get(index->int_id);
  450. auto aggregate_type_id = eval_context.GetConstantValueAsType(
  451. eval_context.insts().Get(inst.array_id).type_id());
  452. if (auto array_type =
  453. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  454. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  455. array_type->bound_id)) {
  456. // This awkward call to `getZExtValue` is a workaround for APInt not
  457. // supporting comparisons between integers of different bit widths.
  458. if (index_val.getActiveBits() > 64 ||
  459. eval_context.ints()
  460. .Get(bound->int_id)
  461. .ule(index_val.getZExtValue())) {
  462. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  463. "array index `{0}` is past the end of type {1}",
  464. TypedInt, SemIR::TypeId);
  465. eval_context.emitter().Emit(
  466. inst.index_id, ArrayIndexOutOfBounds,
  467. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  468. return SemIR::ConstantId::Error;
  469. }
  470. }
  471. }
  472. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  473. if (!aggregate_id.is_valid()) {
  474. return MakeNonConstantResult(phase);
  475. }
  476. auto aggregate =
  477. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  478. if (!aggregate) {
  479. CARBON_CHECK(phase != Phase::Template,
  480. "Unexpected representation for template constant aggregate");
  481. return MakeNonConstantResult(phase);
  482. }
  483. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  484. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  485. }
  486. // Enforces that an integer type has a valid bit width.
  487. static auto ValidateIntType(Context& context, SemIRLoc loc,
  488. SemIR::IntType result) -> bool {
  489. auto bit_width =
  490. context.insts().TryGetAs<SemIR::IntValue>(result.bit_width_id);
  491. if (!bit_width) {
  492. // Symbolic bit width.
  493. return true;
  494. }
  495. const auto& bit_width_val = context.ints().Get(bit_width->int_id);
  496. if (bit_width_val.isZero() ||
  497. (context.types().IsSignedInt(bit_width->type_id) &&
  498. bit_width_val.isNegative())) {
  499. CARBON_DIAGNOSTIC(IntWidthNotPositive, Error,
  500. "integer type width of {0} is not positive", TypedInt);
  501. context.emitter().Emit(
  502. loc, IntWidthNotPositive,
  503. {.type = bit_width->type_id, .value = bit_width_val});
  504. return false;
  505. }
  506. // TODO: Pick a maximum size and document it in the design. For now
  507. // we use 2^^23, because that's the largest size that LLVM supports.
  508. constexpr int MaxIntWidth = 1 << 23;
  509. if (bit_width_val.ugt(MaxIntWidth)) {
  510. CARBON_DIAGNOSTIC(IntWidthTooLarge, Error,
  511. "integer type width of {0} is greater than the "
  512. "maximum supported width of {1}",
  513. TypedInt, int);
  514. context.emitter().Emit(loc, IntWidthTooLarge,
  515. {.type = bit_width->type_id, .value = bit_width_val},
  516. MaxIntWidth);
  517. return false;
  518. }
  519. return true;
  520. }
  521. // Forms a constant int type as an evaluation result. Requires that width_id is
  522. // constant.
  523. static auto MakeIntTypeResult(Context& context, SemIRLoc loc,
  524. SemIR::IntKind int_kind, SemIR::InstId width_id,
  525. Phase phase) -> SemIR::ConstantId {
  526. auto result = SemIR::IntType{
  527. .type_id = context.GetBuiltinType(SemIR::BuiltinInstKind::TypeType),
  528. .int_kind = int_kind,
  529. .bit_width_id = width_id};
  530. if (!ValidateIntType(context, loc, result)) {
  531. return SemIR::ConstantId::Error;
  532. }
  533. return MakeConstantResult(context, result, phase);
  534. }
  535. // Enforces that the bit width is 64 for a float.
  536. static auto ValidateFloatBitWidth(Context& context, SemIRLoc loc,
  537. SemIR::InstId inst_id) -> bool {
  538. auto inst = context.insts().GetAs<SemIR::IntValue>(inst_id);
  539. if (context.ints().Get(inst.int_id) == 64) {
  540. return true;
  541. }
  542. CARBON_DIAGNOSTIC(CompileTimeFloatBitWidth, Error, "bit width must be 64");
  543. context.emitter().Emit(loc, CompileTimeFloatBitWidth);
  544. return false;
  545. }
  546. // Enforces that a float type has a valid bit width.
  547. static auto ValidateFloatType(Context& context, SemIRLoc loc,
  548. SemIR::FloatType result) -> bool {
  549. auto bit_width =
  550. context.insts().TryGetAs<SemIR::IntValue>(result.bit_width_id);
  551. if (!bit_width) {
  552. // Symbolic bit width.
  553. return true;
  554. }
  555. return ValidateFloatBitWidth(context, loc, result.bit_width_id);
  556. }
  557. // Issues a diagnostic for a compile-time division by zero.
  558. static auto DiagnoseDivisionByZero(Context& context, SemIRLoc loc) -> void {
  559. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  560. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  561. }
  562. // Performs a builtin unary integer -> integer operation.
  563. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLoc loc,
  564. SemIR::BuiltinFunctionKind builtin_kind,
  565. SemIR::InstId arg_id)
  566. -> SemIR::ConstantId {
  567. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  568. auto op_val = context.ints().Get(op.int_id);
  569. switch (builtin_kind) {
  570. case SemIR::BuiltinFunctionKind::IntSNegate:
  571. if (context.types().IsSignedInt(op.type_id) &&
  572. op_val.isMinSignedValue()) {
  573. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  574. "integer overflow in negation of {0}", TypedInt);
  575. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  576. {.type = op.type_id, .value = op_val});
  577. }
  578. op_val.negate();
  579. break;
  580. case SemIR::BuiltinFunctionKind::IntUNegate:
  581. op_val.negate();
  582. break;
  583. case SemIR::BuiltinFunctionKind::IntComplement:
  584. op_val.flipAllBits();
  585. break;
  586. default:
  587. CARBON_FATAL("Unexpected builtin kind");
  588. }
  589. return MakeIntResult(context, op.type_id, std::move(op_val));
  590. }
  591. // Performs a builtin binary integer -> integer operation.
  592. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLoc loc,
  593. SemIR::BuiltinFunctionKind builtin_kind,
  594. SemIR::InstId lhs_id,
  595. SemIR::InstId rhs_id)
  596. -> SemIR::ConstantId {
  597. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  598. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  599. const auto& lhs_val = context.ints().Get(lhs.int_id);
  600. const auto& rhs_val = context.ints().Get(rhs.int_id);
  601. // Check for division by zero.
  602. switch (builtin_kind) {
  603. case SemIR::BuiltinFunctionKind::IntSDiv:
  604. case SemIR::BuiltinFunctionKind::IntSMod:
  605. case SemIR::BuiltinFunctionKind::IntUDiv:
  606. case SemIR::BuiltinFunctionKind::IntUMod:
  607. if (rhs_val.isZero()) {
  608. DiagnoseDivisionByZero(context, loc);
  609. return SemIR::ConstantId::Error;
  610. }
  611. break;
  612. default:
  613. break;
  614. }
  615. bool overflow = false;
  616. llvm::APInt result_val;
  617. Lex::TokenKind op_token = Lex::TokenKind::Not;
  618. switch (builtin_kind) {
  619. // Arithmetic.
  620. case SemIR::BuiltinFunctionKind::IntSAdd:
  621. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  622. op_token = Lex::TokenKind::Plus;
  623. break;
  624. case SemIR::BuiltinFunctionKind::IntSSub:
  625. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  626. op_token = Lex::TokenKind::Minus;
  627. break;
  628. case SemIR::BuiltinFunctionKind::IntSMul:
  629. result_val = lhs_val.smul_ov(rhs_val, overflow);
  630. op_token = Lex::TokenKind::Star;
  631. break;
  632. case SemIR::BuiltinFunctionKind::IntSDiv:
  633. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  634. op_token = Lex::TokenKind::Slash;
  635. break;
  636. case SemIR::BuiltinFunctionKind::IntSMod:
  637. result_val = lhs_val.srem(rhs_val);
  638. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  639. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  640. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  641. op_token = Lex::TokenKind::Percent;
  642. break;
  643. case SemIR::BuiltinFunctionKind::IntUAdd:
  644. result_val = lhs_val + rhs_val;
  645. op_token = Lex::TokenKind::Plus;
  646. break;
  647. case SemIR::BuiltinFunctionKind::IntUSub:
  648. result_val = lhs_val - rhs_val;
  649. op_token = Lex::TokenKind::Minus;
  650. break;
  651. case SemIR::BuiltinFunctionKind::IntUMul:
  652. result_val = lhs_val * rhs_val;
  653. op_token = Lex::TokenKind::Star;
  654. break;
  655. case SemIR::BuiltinFunctionKind::IntUDiv:
  656. result_val = lhs_val.udiv(rhs_val);
  657. op_token = Lex::TokenKind::Slash;
  658. break;
  659. case SemIR::BuiltinFunctionKind::IntUMod:
  660. result_val = lhs_val.urem(rhs_val);
  661. op_token = Lex::TokenKind::Percent;
  662. break;
  663. // Bitwise.
  664. case SemIR::BuiltinFunctionKind::IntAnd:
  665. result_val = lhs_val & rhs_val;
  666. op_token = Lex::TokenKind::And;
  667. break;
  668. case SemIR::BuiltinFunctionKind::IntOr:
  669. result_val = lhs_val | rhs_val;
  670. op_token = Lex::TokenKind::Pipe;
  671. break;
  672. case SemIR::BuiltinFunctionKind::IntXor:
  673. result_val = lhs_val ^ rhs_val;
  674. op_token = Lex::TokenKind::Caret;
  675. break;
  676. // Bit shift.
  677. case SemIR::BuiltinFunctionKind::IntLeftShift:
  678. case SemIR::BuiltinFunctionKind::IntRightShift:
  679. if (rhs_val.uge(lhs_val.getBitWidth()) ||
  680. (rhs_val.isNegative() && context.types().IsSignedInt(rhs.type_id))) {
  681. CARBON_DIAGNOSTIC(
  682. CompileTimeShiftOutOfRange, Error,
  683. "shift distance not in range [0, {0}) in {1} {2:<<|>>} {3}",
  684. unsigned, TypedInt, BoolAsSelect, TypedInt);
  685. context.emitter().Emit(
  686. loc, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  687. {.type = lhs.type_id, .value = lhs_val},
  688. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  689. {.type = rhs.type_id, .value = rhs_val});
  690. // TODO: Is it useful to recover by returning 0 or -1?
  691. return SemIR::ConstantId::Error;
  692. }
  693. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  694. result_val = lhs_val.shl(rhs_val);
  695. } else if (context.types().IsSignedInt(lhs.type_id)) {
  696. result_val = lhs_val.ashr(rhs_val);
  697. } else {
  698. result_val = lhs_val.lshr(rhs_val);
  699. }
  700. break;
  701. default:
  702. CARBON_FATAL("Unexpected operation kind.");
  703. }
  704. if (overflow) {
  705. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  706. "integer overflow in calculation {0} {1} {2}", TypedInt,
  707. Lex::TokenKind, TypedInt);
  708. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  709. {.type = lhs.type_id, .value = lhs_val}, op_token,
  710. {.type = rhs.type_id, .value = rhs_val});
  711. }
  712. return MakeIntResult(context, lhs.type_id, std::move(result_val));
  713. }
  714. // Performs a builtin integer comparison.
  715. static auto PerformBuiltinIntComparison(Context& context,
  716. SemIR::BuiltinFunctionKind builtin_kind,
  717. SemIR::InstId lhs_id,
  718. SemIR::InstId rhs_id,
  719. SemIR::TypeId bool_type_id)
  720. -> SemIR::ConstantId {
  721. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  722. const auto& lhs_val = context.ints().Get(lhs.int_id);
  723. const auto& rhs_val =
  724. context.ints().Get(context.insts().GetAs<SemIR::IntValue>(rhs_id).int_id);
  725. bool is_signed = context.types().IsSignedInt(lhs.type_id);
  726. bool result;
  727. switch (builtin_kind) {
  728. case SemIR::BuiltinFunctionKind::IntEq:
  729. result = (lhs_val == rhs_val);
  730. break;
  731. case SemIR::BuiltinFunctionKind::IntNeq:
  732. result = (lhs_val != rhs_val);
  733. break;
  734. case SemIR::BuiltinFunctionKind::IntLess:
  735. result = is_signed ? lhs_val.slt(rhs_val) : lhs_val.ult(rhs_val);
  736. break;
  737. case SemIR::BuiltinFunctionKind::IntLessEq:
  738. result = is_signed ? lhs_val.sle(rhs_val) : lhs_val.ule(rhs_val);
  739. break;
  740. case SemIR::BuiltinFunctionKind::IntGreater:
  741. result = is_signed ? lhs_val.sgt(rhs_val) : lhs_val.sgt(rhs_val);
  742. break;
  743. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  744. result = is_signed ? lhs_val.sge(rhs_val) : lhs_val.sge(rhs_val);
  745. break;
  746. default:
  747. CARBON_FATAL("Unexpected operation kind.");
  748. }
  749. return MakeBoolResult(context, bool_type_id, result);
  750. }
  751. // Performs a builtin unary float -> float operation.
  752. static auto PerformBuiltinUnaryFloatOp(Context& context,
  753. SemIR::BuiltinFunctionKind builtin_kind,
  754. SemIR::InstId arg_id)
  755. -> SemIR::ConstantId {
  756. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  757. auto op_val = context.floats().Get(op.float_id);
  758. switch (builtin_kind) {
  759. case SemIR::BuiltinFunctionKind::FloatNegate:
  760. op_val.changeSign();
  761. break;
  762. default:
  763. CARBON_FATAL("Unexpected builtin kind");
  764. }
  765. return MakeFloatResult(context, op.type_id, std::move(op_val));
  766. }
  767. // Performs a builtin binary float -> float operation.
  768. static auto PerformBuiltinBinaryFloatOp(Context& context,
  769. SemIR::BuiltinFunctionKind builtin_kind,
  770. SemIR::InstId lhs_id,
  771. SemIR::InstId rhs_id)
  772. -> SemIR::ConstantId {
  773. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  774. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  775. auto lhs_val = context.floats().Get(lhs.float_id);
  776. auto rhs_val = context.floats().Get(rhs.float_id);
  777. llvm::APFloat result_val(lhs_val.getSemantics());
  778. switch (builtin_kind) {
  779. case SemIR::BuiltinFunctionKind::FloatAdd:
  780. result_val = lhs_val + rhs_val;
  781. break;
  782. case SemIR::BuiltinFunctionKind::FloatSub:
  783. result_val = lhs_val - rhs_val;
  784. break;
  785. case SemIR::BuiltinFunctionKind::FloatMul:
  786. result_val = lhs_val * rhs_val;
  787. break;
  788. case SemIR::BuiltinFunctionKind::FloatDiv:
  789. result_val = lhs_val / rhs_val;
  790. break;
  791. default:
  792. CARBON_FATAL("Unexpected operation kind.");
  793. }
  794. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  795. }
  796. // Performs a builtin float comparison.
  797. static auto PerformBuiltinFloatComparison(
  798. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  799. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  800. -> SemIR::ConstantId {
  801. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  802. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  803. const auto& lhs_val = context.floats().Get(lhs.float_id);
  804. const auto& rhs_val = context.floats().Get(rhs.float_id);
  805. bool result;
  806. switch (builtin_kind) {
  807. case SemIR::BuiltinFunctionKind::FloatEq:
  808. result = (lhs_val == rhs_val);
  809. break;
  810. case SemIR::BuiltinFunctionKind::FloatNeq:
  811. result = (lhs_val != rhs_val);
  812. break;
  813. case SemIR::BuiltinFunctionKind::FloatLess:
  814. result = lhs_val < rhs_val;
  815. break;
  816. case SemIR::BuiltinFunctionKind::FloatLessEq:
  817. result = lhs_val <= rhs_val;
  818. break;
  819. case SemIR::BuiltinFunctionKind::FloatGreater:
  820. result = lhs_val > rhs_val;
  821. break;
  822. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  823. result = lhs_val >= rhs_val;
  824. break;
  825. default:
  826. CARBON_FATAL("Unexpected operation kind.");
  827. }
  828. return MakeBoolResult(context, bool_type_id, result);
  829. }
  830. // Returns a constant for a call to a builtin function.
  831. static auto MakeConstantForBuiltinCall(Context& context, SemIRLoc loc,
  832. SemIR::Call call,
  833. SemIR::BuiltinFunctionKind builtin_kind,
  834. llvm::ArrayRef<SemIR::InstId> arg_ids,
  835. Phase phase) -> SemIR::ConstantId {
  836. switch (builtin_kind) {
  837. case SemIR::BuiltinFunctionKind::None:
  838. CARBON_FATAL("Not a builtin function.");
  839. case SemIR::BuiltinFunctionKind::PrintInt: {
  840. // Providing a constant result would allow eliding the function call.
  841. return SemIR::ConstantId::NotConstant;
  842. }
  843. case SemIR::BuiltinFunctionKind::BigIntMakeType: {
  844. return context.constant_values().Get(SemIR::InstId::BuiltinBigIntType);
  845. }
  846. case SemIR::BuiltinFunctionKind::IntMakeType32: {
  847. return context.constant_values().Get(SemIR::InstId::BuiltinIntType);
  848. }
  849. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  850. return MakeIntTypeResult(context, loc, SemIR::IntKind::Signed, arg_ids[0],
  851. phase);
  852. }
  853. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  854. return MakeIntTypeResult(context, loc, SemIR::IntKind::Unsigned,
  855. arg_ids[0], phase);
  856. }
  857. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  858. // TODO: Support a symbolic constant width.
  859. if (phase != Phase::Template) {
  860. break;
  861. }
  862. if (!ValidateFloatBitWidth(context, loc, arg_ids[0])) {
  863. return SemIR::ConstantId::Error;
  864. }
  865. return context.constant_values().Get(SemIR::InstId::BuiltinFloatType);
  866. }
  867. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  868. return context.constant_values().Get(SemIR::InstId::BuiltinBoolType);
  869. }
  870. // Unary integer -> integer operations.
  871. case SemIR::BuiltinFunctionKind::IntSNegate:
  872. case SemIR::BuiltinFunctionKind::IntUNegate:
  873. case SemIR::BuiltinFunctionKind::IntComplement: {
  874. if (phase != Phase::Template) {
  875. break;
  876. }
  877. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  878. }
  879. // Binary integer -> integer operations.
  880. case SemIR::BuiltinFunctionKind::IntSAdd:
  881. case SemIR::BuiltinFunctionKind::IntSSub:
  882. case SemIR::BuiltinFunctionKind::IntSMul:
  883. case SemIR::BuiltinFunctionKind::IntSDiv:
  884. case SemIR::BuiltinFunctionKind::IntSMod:
  885. case SemIR::BuiltinFunctionKind::IntUAdd:
  886. case SemIR::BuiltinFunctionKind::IntUSub:
  887. case SemIR::BuiltinFunctionKind::IntUMul:
  888. case SemIR::BuiltinFunctionKind::IntUDiv:
  889. case SemIR::BuiltinFunctionKind::IntUMod:
  890. case SemIR::BuiltinFunctionKind::IntAnd:
  891. case SemIR::BuiltinFunctionKind::IntOr:
  892. case SemIR::BuiltinFunctionKind::IntXor:
  893. case SemIR::BuiltinFunctionKind::IntLeftShift:
  894. case SemIR::BuiltinFunctionKind::IntRightShift: {
  895. if (phase != Phase::Template) {
  896. break;
  897. }
  898. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  899. arg_ids[1]);
  900. }
  901. // Integer comparisons.
  902. case SemIR::BuiltinFunctionKind::IntEq:
  903. case SemIR::BuiltinFunctionKind::IntNeq:
  904. case SemIR::BuiltinFunctionKind::IntLess:
  905. case SemIR::BuiltinFunctionKind::IntLessEq:
  906. case SemIR::BuiltinFunctionKind::IntGreater:
  907. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  908. if (phase != Phase::Template) {
  909. break;
  910. }
  911. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  912. arg_ids[1], call.type_id);
  913. }
  914. // Unary float -> float operations.
  915. case SemIR::BuiltinFunctionKind::FloatNegate: {
  916. if (phase != Phase::Template) {
  917. break;
  918. }
  919. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  920. }
  921. // Binary float -> float operations.
  922. case SemIR::BuiltinFunctionKind::FloatAdd:
  923. case SemIR::BuiltinFunctionKind::FloatSub:
  924. case SemIR::BuiltinFunctionKind::FloatMul:
  925. case SemIR::BuiltinFunctionKind::FloatDiv: {
  926. if (phase != Phase::Template) {
  927. break;
  928. }
  929. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  930. arg_ids[1]);
  931. }
  932. // Float comparisons.
  933. case SemIR::BuiltinFunctionKind::FloatEq:
  934. case SemIR::BuiltinFunctionKind::FloatNeq:
  935. case SemIR::BuiltinFunctionKind::FloatLess:
  936. case SemIR::BuiltinFunctionKind::FloatLessEq:
  937. case SemIR::BuiltinFunctionKind::FloatGreater:
  938. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  939. if (phase != Phase::Template) {
  940. break;
  941. }
  942. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  943. arg_ids[1], call.type_id);
  944. }
  945. }
  946. return SemIR::ConstantId::NotConstant;
  947. }
  948. // Makes a constant for a call instruction.
  949. static auto MakeConstantForCall(EvalContext& eval_context, SemIRLoc loc,
  950. SemIR::Call call) -> SemIR::ConstantId {
  951. Phase phase = Phase::Template;
  952. // A call with an invalid argument list is used to represent an erroneous
  953. // call.
  954. //
  955. // TODO: Use a better representation for this.
  956. if (call.args_id == SemIR::InstBlockId::Invalid) {
  957. return SemIR::ConstantId::Error;
  958. }
  959. // If the callee or return type isn't constant, this is not a constant call.
  960. if (!ReplaceFieldWithConstantValue(eval_context, &call,
  961. &SemIR::Call::callee_id, &phase) ||
  962. !ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::type_id,
  963. &phase)) {
  964. return SemIR::ConstantId::NotConstant;
  965. }
  966. auto callee_function =
  967. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  968. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  969. if (callee_function.function_id.is_valid()) {
  970. // Calls to builtins might be constant.
  971. builtin_kind = eval_context.functions()
  972. .Get(callee_function.function_id)
  973. .builtin_function_kind;
  974. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  975. // TODO: Eventually we'll want to treat some kinds of non-builtin
  976. // functions as producing constants.
  977. return SemIR::ConstantId::NotConstant;
  978. }
  979. } else {
  980. // Calls to non-functions, such as calls to generic entity names, might be
  981. // constant.
  982. }
  983. // If the arguments aren't constant, this is not a constant call.
  984. if (!ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  985. &phase)) {
  986. return SemIR::ConstantId::NotConstant;
  987. }
  988. if (phase == Phase::UnknownDueToError) {
  989. return SemIR::ConstantId::Error;
  990. }
  991. // Handle calls to builtins.
  992. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  993. return MakeConstantForBuiltinCall(
  994. eval_context.context(), loc, call, builtin_kind,
  995. eval_context.inst_blocks().Get(call.args_id), phase);
  996. }
  997. return SemIR::ConstantId::NotConstant;
  998. }
  999. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1000. static auto TryEvalInstInContext(EvalContext& eval_context,
  1001. SemIR::InstId inst_id, SemIR::Inst inst)
  1002. -> SemIR::ConstantId {
  1003. // TODO: Ensure we have test coverage for each of these cases that can result
  1004. // in a constant, once those situations are all reachable.
  1005. CARBON_KIND_SWITCH(inst) {
  1006. // These cases are constants if their operands are.
  1007. case SemIR::AddrOf::Kind:
  1008. return RebuildIfFieldsAreConstant(eval_context, inst,
  1009. &SemIR::AddrOf::type_id,
  1010. &SemIR::AddrOf::lvalue_id);
  1011. case CARBON_KIND(SemIR::ArrayType array_type): {
  1012. return RebuildAndValidateIfFieldsAreConstant(
  1013. eval_context, inst,
  1014. [&](SemIR::ArrayType result) {
  1015. auto bound_id = array_type.bound_id;
  1016. auto int_bound =
  1017. eval_context.insts().TryGetAs<SemIR::IntValue>(result.bound_id);
  1018. if (!int_bound) {
  1019. // TODO: Permit symbolic array bounds. This will require fixing
  1020. // callers of `GetArrayBoundValue`.
  1021. eval_context.context().TODO(bound_id, "symbolic array bound");
  1022. return false;
  1023. }
  1024. // TODO: We should check that the size of the resulting array type
  1025. // fits in 64 bits, not just that the bound does. Should we use a
  1026. // 32-bit limit for 32-bit targets?
  1027. const auto& bound_val = eval_context.ints().Get(int_bound->int_id);
  1028. if (eval_context.types().IsSignedInt(int_bound->type_id) &&
  1029. bound_val.isNegative()) {
  1030. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  1031. "array bound of {0} is negative", TypedInt);
  1032. eval_context.emitter().Emit(
  1033. bound_id, ArrayBoundNegative,
  1034. {.type = int_bound->type_id, .value = bound_val});
  1035. return false;
  1036. }
  1037. if (bound_val.getActiveBits() > 64) {
  1038. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  1039. "array bound of {0} is too large", TypedInt);
  1040. eval_context.emitter().Emit(
  1041. bound_id, ArrayBoundTooLarge,
  1042. {.type = int_bound->type_id, .value = bound_val});
  1043. return false;
  1044. }
  1045. return true;
  1046. },
  1047. &SemIR::ArrayType::bound_id, &SemIR::ArrayType::element_type_id);
  1048. }
  1049. case SemIR::AssociatedEntity::Kind:
  1050. return RebuildIfFieldsAreConstant(eval_context, inst,
  1051. &SemIR::AssociatedEntity::type_id);
  1052. case SemIR::AssociatedEntityType::Kind:
  1053. return RebuildIfFieldsAreConstant(
  1054. eval_context, inst, &SemIR::AssociatedEntityType::interface_type_id,
  1055. &SemIR::AssociatedEntityType::entity_type_id);
  1056. case SemIR::BoundMethod::Kind:
  1057. return RebuildIfFieldsAreConstant(
  1058. eval_context, inst, &SemIR::BoundMethod::type_id,
  1059. &SemIR::BoundMethod::object_id, &SemIR::BoundMethod::function_id);
  1060. case SemIR::ClassType::Kind:
  1061. return RebuildIfFieldsAreConstant(eval_context, inst,
  1062. &SemIR::ClassType::specific_id);
  1063. case SemIR::CompleteTypeWitness::Kind:
  1064. return RebuildIfFieldsAreConstant(
  1065. eval_context, inst, &SemIR::CompleteTypeWitness::object_repr_id);
  1066. case SemIR::FunctionType::Kind:
  1067. return RebuildIfFieldsAreConstant(eval_context, inst,
  1068. &SemIR::FunctionType::specific_id);
  1069. case SemIR::GenericClassType::Kind:
  1070. return RebuildIfFieldsAreConstant(
  1071. eval_context, inst, &SemIR::GenericClassType::enclosing_specific_id);
  1072. case SemIR::GenericInterfaceType::Kind:
  1073. return RebuildIfFieldsAreConstant(
  1074. eval_context, inst,
  1075. &SemIR::GenericInterfaceType::enclosing_specific_id);
  1076. case SemIR::InterfaceType::Kind:
  1077. return RebuildIfFieldsAreConstant(eval_context, inst,
  1078. &SemIR::InterfaceType::specific_id);
  1079. case SemIR::InterfaceWitness::Kind:
  1080. return RebuildIfFieldsAreConstant(eval_context, inst,
  1081. &SemIR::InterfaceWitness::elements_id);
  1082. case CARBON_KIND(SemIR::IntType int_type): {
  1083. return RebuildAndValidateIfFieldsAreConstant(
  1084. eval_context, inst,
  1085. [&](SemIR::IntType result) {
  1086. return ValidateIntType(
  1087. eval_context.context(),
  1088. inst_id.is_valid() ? inst_id : int_type.bit_width_id, result);
  1089. },
  1090. &SemIR::IntType::bit_width_id);
  1091. }
  1092. case SemIR::PointerType::Kind:
  1093. return RebuildIfFieldsAreConstant(eval_context, inst,
  1094. &SemIR::PointerType::pointee_id);
  1095. case CARBON_KIND(SemIR::FloatType float_type): {
  1096. return RebuildAndValidateIfFieldsAreConstant(
  1097. eval_context, inst,
  1098. [&](SemIR::FloatType result) {
  1099. return ValidateFloatType(eval_context.context(),
  1100. float_type.bit_width_id, result);
  1101. },
  1102. &SemIR::FloatType::bit_width_id);
  1103. }
  1104. case SemIR::SpecificFunction::Kind:
  1105. return RebuildIfFieldsAreConstant(eval_context, inst,
  1106. &SemIR::SpecificFunction::callee_id,
  1107. &SemIR::SpecificFunction::specific_id);
  1108. case SemIR::StructType::Kind:
  1109. return RebuildIfFieldsAreConstant(eval_context, inst,
  1110. &SemIR::StructType::fields_id);
  1111. case SemIR::StructTypeField::Kind:
  1112. return RebuildIfFieldsAreConstant(eval_context, inst,
  1113. &SemIR::StructTypeField::field_type_id);
  1114. case SemIR::StructValue::Kind:
  1115. return RebuildIfFieldsAreConstant(eval_context, inst,
  1116. &SemIR::StructValue::type_id,
  1117. &SemIR::StructValue::elements_id);
  1118. case SemIR::TupleType::Kind:
  1119. return RebuildIfFieldsAreConstant(eval_context, inst,
  1120. &SemIR::TupleType::elements_id);
  1121. case SemIR::TupleValue::Kind:
  1122. return RebuildIfFieldsAreConstant(eval_context, inst,
  1123. &SemIR::TupleValue::type_id,
  1124. &SemIR::TupleValue::elements_id);
  1125. case SemIR::UnboundElementType::Kind:
  1126. return RebuildIfFieldsAreConstant(
  1127. eval_context, inst, &SemIR::UnboundElementType::class_type_id,
  1128. &SemIR::UnboundElementType::element_type_id);
  1129. // Initializers evaluate to a value of the object representation.
  1130. case SemIR::ArrayInit::Kind:
  1131. // TODO: Add an `ArrayValue` to represent a constant array object
  1132. // representation instead of using a `TupleValue`.
  1133. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1134. case SemIR::ClassInit::Kind:
  1135. // TODO: Add a `ClassValue` to represent a constant class object
  1136. // representation instead of using a `StructValue`.
  1137. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1138. case SemIR::StructInit::Kind:
  1139. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1140. case SemIR::TupleInit::Kind:
  1141. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1142. case SemIR::BuiltinInst::Kind:
  1143. // Builtins are always template constants.
  1144. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1145. case CARBON_KIND(SemIR::FunctionDecl fn_decl): {
  1146. return TransformIfFieldsAreConstant(
  1147. eval_context, fn_decl,
  1148. [&](SemIR::FunctionDecl result) {
  1149. return SemIR::StructValue{.type_id = result.type_id,
  1150. .elements_id = SemIR::InstBlockId::Empty};
  1151. },
  1152. &SemIR::FunctionDecl::type_id);
  1153. }
  1154. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  1155. // If the class has generic parameters, we don't produce a class type, but
  1156. // a callable whose return value is a class type.
  1157. if (eval_context.classes().Get(class_decl.class_id).has_parameters()) {
  1158. return TransformIfFieldsAreConstant(
  1159. eval_context, class_decl,
  1160. [&](SemIR::ClassDecl result) {
  1161. return SemIR::StructValue{
  1162. .type_id = result.type_id,
  1163. .elements_id = SemIR::InstBlockId::Empty};
  1164. },
  1165. &SemIR::ClassDecl::type_id);
  1166. }
  1167. // A non-generic class declaration evaluates to the class type.
  1168. return MakeConstantResult(
  1169. eval_context.context(),
  1170. SemIR::ClassType{.type_id = SemIR::TypeId::TypeType,
  1171. .class_id = class_decl.class_id,
  1172. .specific_id = SemIR::SpecificId::Invalid},
  1173. Phase::Template);
  1174. }
  1175. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  1176. // If the interface has generic parameters, we don't produce an interface
  1177. // type, but a callable whose return value is an interface type.
  1178. if (eval_context.interfaces()
  1179. .Get(interface_decl.interface_id)
  1180. .has_parameters()) {
  1181. return TransformIfFieldsAreConstant(
  1182. eval_context, interface_decl,
  1183. [&](SemIR::InterfaceDecl result) {
  1184. return SemIR::StructValue{
  1185. .type_id = result.type_id,
  1186. .elements_id = SemIR::InstBlockId::Empty};
  1187. },
  1188. &SemIR::InterfaceDecl::type_id);
  1189. }
  1190. // A non-generic interface declaration evaluates to the interface type.
  1191. return MakeConstantResult(
  1192. eval_context.context(),
  1193. SemIR::InterfaceType{.type_id = SemIR::TypeId::TypeType,
  1194. .interface_id = interface_decl.interface_id,
  1195. .specific_id = SemIR::SpecificId::Invalid},
  1196. Phase::Template);
  1197. }
  1198. case CARBON_KIND(SemIR::SpecificConstant specific): {
  1199. // Pull the constant value out of the specific.
  1200. return SemIR::GetConstantValueInSpecific(
  1201. eval_context.sem_ir(), specific.specific_id, specific.inst_id);
  1202. }
  1203. // These cases are treated as being the unique canonical definition of the
  1204. // corresponding constant value.
  1205. // TODO: This doesn't properly handle redeclarations. Consider adding a
  1206. // corresponding `Value` inst for each of these cases, or returning the
  1207. // first declaration.
  1208. case SemIR::AssociatedConstantDecl::Kind:
  1209. case SemIR::BaseDecl::Kind:
  1210. case SemIR::FieldDecl::Kind:
  1211. case SemIR::ImplDecl::Kind:
  1212. case SemIR::Namespace::Kind:
  1213. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  1214. case SemIR::BoolLiteral::Kind:
  1215. case SemIR::FloatLiteral::Kind:
  1216. case SemIR::IntValue::Kind:
  1217. case SemIR::StringLiteral::Kind:
  1218. // Promote literals to the constant block.
  1219. // TODO: Convert literals into a canonical form. Currently we can form two
  1220. // different `i32` constants with the same value if they are represented
  1221. // by `APInt`s with different bit widths.
  1222. // TODO: Can the type of an IntValue or FloatLiteral be symbolic? If so,
  1223. // we may need to rebuild.
  1224. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1225. // The elements of a constant aggregate can be accessed.
  1226. case SemIR::ClassElementAccess::Kind:
  1227. case SemIR::InterfaceWitnessAccess::Kind:
  1228. case SemIR::StructAccess::Kind:
  1229. case SemIR::TupleAccess::Kind:
  1230. return PerformAggregateAccess(eval_context, inst);
  1231. case CARBON_KIND(SemIR::ArrayIndex index): {
  1232. return PerformArrayIndex(eval_context, index);
  1233. }
  1234. case CARBON_KIND(SemIR::Call call): {
  1235. return MakeConstantForCall(eval_context, inst_id, call);
  1236. }
  1237. // TODO: These need special handling.
  1238. case SemIR::BindValue::Kind:
  1239. case SemIR::Deref::Kind:
  1240. case SemIR::ImportRefLoaded::Kind:
  1241. case SemIR::ReturnSlot::Kind:
  1242. case SemIR::Temporary::Kind:
  1243. case SemIR::TemporaryStorage::Kind:
  1244. case SemIR::ValueAsRef::Kind:
  1245. break;
  1246. case CARBON_KIND(SemIR::SymbolicBindingPattern bind): {
  1247. // TODO: disable constant evaluation of SymbolicBindingPattern once
  1248. // DeduceGenericCallArguments no longer needs implicit params to have
  1249. // constant values.
  1250. const auto& bind_name =
  1251. eval_context.entity_names().Get(bind.entity_name_id);
  1252. // If we know which specific we're evaluating within and this is an
  1253. // argument of that specific, its constant value is the corresponding
  1254. // argument value.
  1255. if (auto value =
  1256. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1257. value.is_valid()) {
  1258. return value;
  1259. }
  1260. // The constant form of a symbolic binding is an idealized form of the
  1261. // original, with no equivalent value.
  1262. bind.entity_name_id =
  1263. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1264. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1265. }
  1266. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  1267. const auto& bind_name =
  1268. eval_context.entity_names().Get(bind.entity_name_id);
  1269. // If we know which specific we're evaluating within and this is an
  1270. // argument of that specific, its constant value is the corresponding
  1271. // argument value.
  1272. if (auto value =
  1273. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1274. value.is_valid()) {
  1275. return value;
  1276. }
  1277. // The constant form of a symbolic binding is an idealized form of the
  1278. // original, with no equivalent value.
  1279. bind.entity_name_id =
  1280. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1281. bind.value_id = SemIR::InstId::Invalid;
  1282. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1283. }
  1284. // These semantic wrappers don't change the constant value.
  1285. case CARBON_KIND(SemIR::AsCompatible inst): {
  1286. return eval_context.GetConstantValue(inst.source_id);
  1287. }
  1288. case CARBON_KIND(SemIR::BindAlias typed_inst): {
  1289. return eval_context.GetConstantValue(typed_inst.value_id);
  1290. }
  1291. case CARBON_KIND(SemIR::ExportDecl typed_inst): {
  1292. return eval_context.GetConstantValue(typed_inst.value_id);
  1293. }
  1294. case CARBON_KIND(SemIR::NameRef typed_inst): {
  1295. return eval_context.GetConstantValue(typed_inst.value_id);
  1296. }
  1297. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  1298. // TODO: treat this as a non-expression (here and in GetExprCategory)
  1299. // once generic deduction doesn't need patterns to have constant values.
  1300. return eval_context.GetConstantValue(param_pattern.subpattern_id);
  1301. }
  1302. case CARBON_KIND(SemIR::Converted typed_inst): {
  1303. return eval_context.GetConstantValue(typed_inst.result_id);
  1304. }
  1305. case CARBON_KIND(SemIR::InitializeFrom typed_inst): {
  1306. return eval_context.GetConstantValue(typed_inst.src_id);
  1307. }
  1308. case CARBON_KIND(SemIR::SpliceBlock typed_inst): {
  1309. return eval_context.GetConstantValue(typed_inst.result_id);
  1310. }
  1311. case CARBON_KIND(SemIR::ValueOfInitializer typed_inst): {
  1312. return eval_context.GetConstantValue(typed_inst.init_id);
  1313. }
  1314. case CARBON_KIND(SemIR::FacetTypeAccess typed_inst): {
  1315. // TODO: Once we start tracking the witness in the facet value, remove it
  1316. // here. For now, we model a facet value as just a type.
  1317. return eval_context.GetConstantValue(typed_inst.facet_id);
  1318. }
  1319. case CARBON_KIND(SemIR::WhereExpr typed_inst): {
  1320. // TODO: This currently ignores the requirements and just produces the
  1321. // left-hand type argument to the `where`.
  1322. return eval_context.GetConstantValue(
  1323. eval_context.insts().Get(typed_inst.period_self_id).type_id());
  1324. }
  1325. // `not true` -> `false`, `not false` -> `true`.
  1326. // All other uses of unary `not` are non-constant.
  1327. case CARBON_KIND(SemIR::UnaryOperatorNot typed_inst): {
  1328. auto const_id = eval_context.GetConstantValue(typed_inst.operand_id);
  1329. auto phase = GetPhase(const_id);
  1330. if (phase == Phase::Template) {
  1331. auto value = eval_context.insts().GetAs<SemIR::BoolLiteral>(
  1332. eval_context.constant_values().GetInstId(const_id));
  1333. return MakeBoolResult(eval_context.context(), value.type_id,
  1334. !value.value.ToBool());
  1335. }
  1336. if (phase == Phase::UnknownDueToError) {
  1337. return SemIR::ConstantId::Error;
  1338. }
  1339. break;
  1340. }
  1341. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  1342. // to itself.
  1343. case CARBON_KIND(SemIR::ConstType typed_inst): {
  1344. auto phase = Phase::Template;
  1345. auto inner_id =
  1346. GetConstantValue(eval_context, typed_inst.inner_id, &phase);
  1347. if (eval_context.context().types().Is<SemIR::ConstType>(inner_id)) {
  1348. return eval_context.context().types().GetConstantId(inner_id);
  1349. }
  1350. typed_inst.inner_id = inner_id;
  1351. return MakeConstantResult(eval_context.context(), typed_inst, phase);
  1352. }
  1353. // These cases are either not expressions or not constant.
  1354. case SemIR::AdaptDecl::Kind:
  1355. case SemIR::AddrPattern::Kind:
  1356. case SemIR::Assign::Kind:
  1357. case SemIR::BindName::Kind:
  1358. case SemIR::BindingPattern::Kind:
  1359. case SemIR::BlockArg::Kind:
  1360. case SemIR::Branch::Kind:
  1361. case SemIR::BranchIf::Kind:
  1362. case SemIR::BranchWithArg::Kind:
  1363. case SemIR::ImportDecl::Kind:
  1364. case SemIR::OutParam::Kind:
  1365. case SemIR::OutParamPattern::Kind:
  1366. case SemIR::RequirementEquivalent::Kind:
  1367. case SemIR::RequirementImpls::Kind:
  1368. case SemIR::RequirementRewrite::Kind:
  1369. case SemIR::Return::Kind:
  1370. case SemIR::ReturnExpr::Kind:
  1371. case SemIR::ReturnSlotPattern::Kind:
  1372. case SemIR::StructLiteral::Kind:
  1373. case SemIR::TupleLiteral::Kind:
  1374. case SemIR::ValueParam::Kind:
  1375. case SemIR::VarStorage::Kind:
  1376. break;
  1377. case SemIR::ImportRefUnloaded::Kind:
  1378. CARBON_FATAL("ImportRefUnloaded should be loaded before TryEvalInst: {0}",
  1379. inst);
  1380. }
  1381. return SemIR::ConstantId::NotConstant;
  1382. }
  1383. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  1384. -> SemIR::ConstantId {
  1385. EvalContext eval_context(context);
  1386. return TryEvalInstInContext(eval_context, inst_id, inst);
  1387. }
  1388. auto TryEvalBlockForSpecific(Context& context, SemIR::SpecificId specific_id,
  1389. SemIR::GenericInstIndex::Region region)
  1390. -> SemIR::InstBlockId {
  1391. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1392. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1393. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1394. llvm::SmallVector<SemIR::InstId> result;
  1395. result.resize(eval_block.size(), SemIR::InstId::Invalid);
  1396. EvalContext eval_context(context, specific_id,
  1397. SpecificEvalInfo{
  1398. .region = region,
  1399. .values = result,
  1400. });
  1401. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1402. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1403. context.insts().Get(inst_id));
  1404. result[i] = context.constant_values().GetInstId(const_id);
  1405. // TODO: If this becomes possible through monomorphization failure, produce
  1406. // a diagnostic and put `SemIR::InstId::BuiltinError` in the table entry.
  1407. CARBON_CHECK(result[i].is_valid());
  1408. }
  1409. return context.inst_blocks().Add(result);
  1410. }
  1411. } // namespace Carbon::Check