eval.cpp 59 KB

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