eval.cpp 60 KB

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