eval.cpp 60 KB

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