eval.cpp 74 KB

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