eval.cpp 60 KB

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