eval.cpp 91 KB

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