eval.cpp 59 KB

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