eval.cpp 57 KB

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