eval.cpp 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  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/action.h"
  7. #include "toolchain/check/diagnostic_helpers.h"
  8. #include "toolchain/check/eval_inst.h"
  9. #include "toolchain/check/facet_type.h"
  10. #include "toolchain/check/generic.h"
  11. #include "toolchain/check/import_ref.h"
  12. #include "toolchain/check/type.h"
  13. #include "toolchain/check/type_completion.h"
  14. #include "toolchain/diagnostics/diagnostic_emitter.h"
  15. #include "toolchain/diagnostics/format_providers.h"
  16. #include "toolchain/sem_ir/builtin_function_kind.h"
  17. #include "toolchain/sem_ir/function.h"
  18. #include "toolchain/sem_ir/generic.h"
  19. #include "toolchain/sem_ir/id_kind.h"
  20. #include "toolchain/sem_ir/ids.h"
  21. #include "toolchain/sem_ir/inst_kind.h"
  22. #include "toolchain/sem_ir/typed_insts.h"
  23. namespace Carbon::Check {
  24. namespace {
  25. // Information about an eval block of a specific that we are currently building.
  26. struct SpecificEvalInfo {
  27. // The region within the specific whose eval block we are building.
  28. SemIR::GenericInstIndex::Region region;
  29. // The work-in-progress contents of the eval block.
  30. llvm::ArrayRef<SemIR::InstId> values;
  31. };
  32. // Information about the context within which we are performing evaluation.
  33. // `context` must not be null.
  34. class EvalContext {
  35. public:
  36. explicit EvalContext(
  37. Context* context, SemIRLoc fallback_loc,
  38. SemIR::SpecificId specific_id = SemIR::SpecificId::None,
  39. std::optional<SpecificEvalInfo> specific_eval_info = std::nullopt)
  40. : context_(context),
  41. fallback_loc_(fallback_loc),
  42. specific_id_(specific_id),
  43. specific_eval_info_(specific_eval_info) {}
  44. // Gets the location to use for diagnostics if a better location is
  45. // unavailable.
  46. // TODO: This is also sometimes unavailable.
  47. auto fallback_loc() const -> SemIRLoc { return fallback_loc_; }
  48. // Returns a location to use to point at an instruction in a diagnostic, given
  49. // a list of instructions that might have an attached location. This is the
  50. // location of the first instruction in the list that has a location if there
  51. // is one, and otherwise the fallback location.
  52. auto GetDiagnosticLoc(llvm::ArrayRef<SemIR::InstId> inst_ids) -> SemIRLoc {
  53. for (auto inst_id : inst_ids) {
  54. if (inst_id.has_value() &&
  55. context_->insts().GetLocId(inst_id).has_value()) {
  56. return inst_id;
  57. }
  58. }
  59. return fallback_loc_;
  60. }
  61. // Gets the value of the specified compile-time binding in this context.
  62. // Returns `None` if the value is not fixed in this context.
  63. auto GetCompileTimeBindValue(SemIR::CompileTimeBindIndex bind_index)
  64. -> SemIR::ConstantId {
  65. if (!bind_index.has_value() || !specific_id_.has_value()) {
  66. return SemIR::ConstantId::None;
  67. }
  68. const auto& specific = specifics().Get(specific_id_);
  69. auto args = inst_blocks().Get(specific.args_id);
  70. // Bindings past the ones with known arguments can appear as local
  71. // bindings of entities declared within this generic.
  72. if (static_cast<size_t>(bind_index.index) >= args.size()) {
  73. return SemIR::ConstantId::None;
  74. }
  75. return constant_values().Get(args[bind_index.index]);
  76. }
  77. // Given a constant value from the SemIR we're evaluating, finds the
  78. // corresponding constant value to use in the context of this evaluation.
  79. // This can be different if the original SemIR is for a generic and we are
  80. // evaluating with specific arguments for the generic parameters.
  81. auto GetInContext(SemIR::ConstantId const_id) -> SemIR::ConstantId {
  82. if (!const_id.is_symbolic()) {
  83. return const_id;
  84. }
  85. // While resolving a specific, map from previous instructions in the eval
  86. // block into their evaluated values. These values won't be present on the
  87. // specific itself yet, so `GetConstantValueInSpecific` won't be able to
  88. // find them.
  89. const auto& symbolic_info = constant_values().GetSymbolicConstant(const_id);
  90. if (specific_eval_info_ && symbolic_info.index.has_value()) {
  91. CARBON_CHECK(
  92. symbolic_info.generic_id == specifics().Get(specific_id_).generic_id,
  93. "Instruction has constant operand in wrong generic");
  94. if (symbolic_info.index.region() == specific_eval_info_->region) {
  95. auto inst_id = specific_eval_info_->values[symbolic_info.index.index()];
  96. CARBON_CHECK(inst_id.has_value(),
  97. "Forward reference in eval block: index {0} referenced "
  98. "before evaluation",
  99. symbolic_info.index.index());
  100. return constant_values().Get(inst_id);
  101. } else {
  102. // TODO: Eliminate this call. This is the only place where we get a
  103. // value from a specific without using an InstId. There are three ways
  104. // we can get here:
  105. // 1) From GetConstantValue(InstId): these can use
  106. // GetConstantValueInSpecific.
  107. // 2) From GetConstantValue(TypeId): for these, we could change
  108. // instructions so they store InstIds instead of TypeIds.
  109. // 3) From GetConstantFacetTypeInfo: for these, we could store an
  110. // InstId instead of a ConstantId in rewrite_constraints.
  111. return GetConstantInSpecific(sem_ir(), specific_id_, const_id);
  112. }
  113. }
  114. // Map from a specific constant value to the canonical value.
  115. return constant_values().Get(symbolic_info.inst_id);
  116. }
  117. // Gets the constant value of the specified instruction in this context.
  118. auto GetConstantValue(SemIR::InstId inst_id) -> SemIR::ConstantId {
  119. return GetInContext(constant_values().Get(inst_id));
  120. }
  121. // Gets the constant value of the specified type in this context.
  122. auto GetConstantValue(SemIR::TypeId type_id) -> SemIR::ConstantId {
  123. return GetInContext(types().GetConstantId(type_id));
  124. }
  125. // Gets the constant value of the specified type in this context.
  126. auto GetConstantValueAsType(SemIR::TypeId id) -> SemIR::TypeId {
  127. return context().types().GetTypeIdForTypeConstantId(GetConstantValue(id));
  128. }
  129. // Gets the instruction describing the constant value of the specified type in
  130. // this context.
  131. auto GetConstantValueAsInst(SemIR::TypeId id) -> SemIR::Inst {
  132. return insts().Get(
  133. context().constant_values().GetInstId(GetConstantValue(id)));
  134. }
  135. auto ints() -> SharedValueStores::IntStore& { return sem_ir().ints(); }
  136. auto floats() -> SharedValueStores::FloatStore& { return sem_ir().floats(); }
  137. auto entity_names() -> SemIR::EntityNameStore& {
  138. return sem_ir().entity_names();
  139. }
  140. auto functions() -> const ValueStore<SemIR::FunctionId>& {
  141. return sem_ir().functions();
  142. }
  143. auto classes() -> const ValueStore<SemIR::ClassId>& {
  144. return sem_ir().classes();
  145. }
  146. auto interfaces() -> const ValueStore<SemIR::InterfaceId>& {
  147. return sem_ir().interfaces();
  148. }
  149. auto specific_interfaces()
  150. -> CanonicalValueStore<SemIR::SpecificInterfaceId>& {
  151. return sem_ir().specific_interfaces();
  152. }
  153. auto facet_types() -> CanonicalValueStore<SemIR::FacetTypeId>& {
  154. return sem_ir().facet_types();
  155. }
  156. auto specifics() -> const SemIR::SpecificStore& {
  157. return sem_ir().specifics();
  158. }
  159. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  160. return sem_ir().type_blocks();
  161. }
  162. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  163. auto inst_blocks() -> SemIR::InstBlockStore& {
  164. return sem_ir().inst_blocks();
  165. }
  166. // Gets the constant value store. Note that this does not provide the constant
  167. // values that should be used from this evaluation context, and so should be
  168. // used with caution.
  169. auto constant_values() -> const SemIR::ConstantValueStore& {
  170. return sem_ir().constant_values();
  171. }
  172. // Gets the types store. Note that this does not provide the type values that
  173. // should be used from this evaluation context, and so should be used with
  174. // caution.
  175. auto types() -> const SemIR::TypeStore& { return sem_ir().types(); }
  176. auto context() -> Context& { return *context_; }
  177. auto sem_ir() -> SemIR::File& { return context().sem_ir(); }
  178. auto emitter() -> DiagnosticEmitterBase& { return context().emitter(); }
  179. private:
  180. // The type-checking context in which we're performing evaluation.
  181. Context* context_;
  182. // The location to use for diagnostics when a better location isn't available.
  183. SemIRLoc fallback_loc_;
  184. // The specific that we are evaluating within.
  185. SemIR::SpecificId specific_id_;
  186. // If we are currently evaluating an eval block for `specific_id_`,
  187. // information about that evaluation.
  188. std::optional<SpecificEvalInfo> specific_eval_info_;
  189. };
  190. } // namespace
  191. namespace {
  192. // The evaluation phase for an expression, computed by evaluation. These are
  193. // ordered so that the phase of an expression is the numerically highest phase
  194. // of its constituent evaluations. Note that an expression with any runtime
  195. // component is known to have Runtime phase even if it involves an evaluation
  196. // with UnknownDueToError phase.
  197. enum class Phase : uint8_t {
  198. // Value could be entirely and concretely computed.
  199. Concrete,
  200. // Evaluation phase is symbolic because the expression involves specifically a
  201. // reference to `.Self`.
  202. PeriodSelfSymbolic,
  203. // Evaluation phase is symbolic because the expression involves a reference to
  204. // a non-template symbolic binding other than `.Self`.
  205. CheckedSymbolic,
  206. // Evaluation phase is symbolic because the expression involves a reference to
  207. // a template parameter, or otherwise depends on something template dependent.
  208. // The expression might also reference non-template symbolic bindings.
  209. TemplateSymbolic,
  210. // The evaluation phase is unknown because evaluation encountered an
  211. // already-diagnosed semantic or syntax error. This is treated as being
  212. // potentially constant, but with an unknown phase.
  213. UnknownDueToError,
  214. // The expression has runtime phase because of a non-constant subexpression.
  215. Runtime,
  216. };
  217. } // namespace
  218. // Returns whether the specified phase is a constant phase.
  219. static auto IsConstant(Phase phase) -> bool {
  220. return phase < Phase::UnknownDueToError;
  221. }
  222. // Gets the phase in which the value of a constant will become available.
  223. static auto GetPhase(const SemIR::ConstantValueStore& constant_values,
  224. SemIR::ConstantId constant_id) -> Phase {
  225. if (!constant_id.is_constant()) {
  226. return Phase::Runtime;
  227. } else if (constant_id == SemIR::ErrorInst::SingletonConstantId) {
  228. return Phase::UnknownDueToError;
  229. }
  230. switch (constant_values.GetDependence(constant_id)) {
  231. case SemIR::ConstantDependence::None:
  232. return Phase::Concrete;
  233. case SemIR::ConstantDependence::PeriodSelf:
  234. return Phase::PeriodSelfSymbolic;
  235. case SemIR::ConstantDependence::Checked:
  236. return Phase::CheckedSymbolic;
  237. case SemIR::ConstantDependence::Template:
  238. return Phase::TemplateSymbolic;
  239. }
  240. }
  241. // Returns the later of two phases.
  242. static auto LatestPhase(Phase a, Phase b) -> Phase {
  243. return static_cast<Phase>(
  244. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  245. }
  246. // `where` expressions using `.Self` should not be considered symbolic
  247. // - `Interface where .Self impls I and .A = bool` -> concrete
  248. // - `T:! type` ... `Interface where .A = T` -> symbolic, since uses `T` which
  249. // is symbolic and not due to `.Self`.
  250. static auto UpdatePhaseIgnorePeriodSelf(EvalContext& eval_context,
  251. SemIR::ConstantId constant_id,
  252. Phase* phase) {
  253. Phase constant_phase = GetPhase(eval_context.constant_values(), constant_id);
  254. // Since LatestPhase(x, Phase::Concrete) == x, this is equivalent to replacing
  255. // Phase::PeriodSelfSymbolic with Phase::Concrete.
  256. if (constant_phase != Phase::PeriodSelfSymbolic) {
  257. *phase = LatestPhase(*phase, constant_phase);
  258. }
  259. }
  260. // Forms a `constant_id` describing a given evaluation result.
  261. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  262. -> SemIR::ConstantId {
  263. switch (phase) {
  264. case Phase::Concrete:
  265. return context.constants().GetOrAdd(inst,
  266. SemIR::ConstantDependence::None);
  267. case Phase::PeriodSelfSymbolic:
  268. return context.constants().GetOrAdd(
  269. inst, SemIR::ConstantDependence::PeriodSelf);
  270. case Phase::CheckedSymbolic:
  271. return context.constants().GetOrAdd(inst,
  272. SemIR::ConstantDependence::Checked);
  273. case Phase::TemplateSymbolic:
  274. return context.constants().GetOrAdd(inst,
  275. SemIR::ConstantDependence::Template);
  276. case Phase::UnknownDueToError:
  277. return SemIR::ErrorInst::SingletonConstantId;
  278. case Phase::Runtime:
  279. return SemIR::ConstantId::NotConstant;
  280. }
  281. }
  282. // Forms a `constant_id` describing why an evaluation was not constant.
  283. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  284. return phase == Phase::UnknownDueToError
  285. ? SemIR::ErrorInst::SingletonConstantId
  286. : SemIR::ConstantId::NotConstant;
  287. }
  288. // Converts a bool value into a ConstantId.
  289. static auto MakeBoolResult(Context& context, SemIR::TypeId bool_type_id,
  290. bool result) -> SemIR::ConstantId {
  291. return MakeConstantResult(
  292. context,
  293. SemIR::BoolLiteral{.type_id = bool_type_id,
  294. .value = SemIR::BoolValue::From(result)},
  295. Phase::Concrete);
  296. }
  297. // Converts an APInt value into a ConstantId.
  298. static auto MakeIntResult(Context& context, SemIR::TypeId type_id,
  299. bool is_signed, llvm::APInt value)
  300. -> SemIR::ConstantId {
  301. CARBON_CHECK(is_signed == context.types().IsSignedInt(type_id));
  302. auto result = is_signed ? context.ints().AddSigned(std::move(value))
  303. : context.ints().AddUnsigned(std::move(value));
  304. return MakeConstantResult(
  305. context, SemIR::IntValue{.type_id = type_id, .int_id = result},
  306. Phase::Concrete);
  307. }
  308. // Converts an APFloat value into a ConstantId.
  309. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  310. llvm::APFloat value) -> SemIR::ConstantId {
  311. auto result = context.floats().Add(std::move(value));
  312. return MakeConstantResult(
  313. context, SemIR::FloatLiteral{.type_id = type_id, .float_id = result},
  314. Phase::Concrete);
  315. }
  316. // Creates a FacetType constant.
  317. static auto MakeFacetTypeResult(Context& context,
  318. const SemIR::FacetTypeInfo& info, Phase phase)
  319. -> SemIR::ConstantId {
  320. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  321. return MakeConstantResult(
  322. context,
  323. SemIR::FacetType{.type_id = SemIR::TypeType::SingletonTypeId,
  324. .facet_type_id = facet_type_id},
  325. phase);
  326. }
  327. // `GetConstantValue` checks to see whether the provided ID describes a value
  328. // with constant phase, and if so, returns the corresponding constant value.
  329. // Overloads are provided for different kinds of ID.
  330. // AbsoluteInstId can not have its values substituted, so this overload is
  331. // deleted. This prevents conversion to InstId.
  332. static auto GetConstantValue(EvalContext& eval_context,
  333. SemIR::AbsoluteInstId inst_id, Phase* phase)
  334. -> SemIR::InstId = delete;
  335. // If the given instruction is constant, returns its constant value.
  336. static auto GetConstantValue(EvalContext& eval_context, SemIR::InstId inst_id,
  337. Phase* phase) -> SemIR::InstId {
  338. if (!inst_id.has_value()) {
  339. return SemIR::InstId::None;
  340. }
  341. auto const_id = eval_context.GetConstantValue(inst_id);
  342. *phase =
  343. LatestPhase(*phase, GetPhase(eval_context.constant_values(), const_id));
  344. return eval_context.constant_values().GetInstId(const_id);
  345. }
  346. // Find the instruction that the given instruction instantiates to, and return
  347. // that.
  348. static auto GetConstantValue(EvalContext& eval_context,
  349. SemIR::MetaInstId inst_id, Phase* phase)
  350. -> SemIR::MetaInstId {
  351. Phase inner_phase = Phase::Concrete;
  352. if (auto const_inst_id =
  353. GetConstantValue(eval_context, SemIR::InstId(inst_id), &inner_phase);
  354. const_inst_id.has_value()) {
  355. // The instruction has a constant value. Use that as the operand of the
  356. // action.
  357. *phase = LatestPhase(*phase, inner_phase);
  358. return const_inst_id;
  359. }
  360. // If this instruction is splicing in an action result, that action result is
  361. // our operand.
  362. if (auto splice = eval_context.insts().TryGetAs<SemIR::SpliceInst>(inst_id)) {
  363. if (auto spliced_inst_id =
  364. GetConstantValue(eval_context, splice->inst_id, phase);
  365. spliced_inst_id.has_value()) {
  366. if (auto inst_value_id = eval_context.insts().TryGetAs<SemIR::InstValue>(
  367. spliced_inst_id)) {
  368. return inst_value_id->inst_id;
  369. }
  370. }
  371. }
  372. // Otherwise, this is a normal instruction.
  373. if (OperandIsDependent(eval_context.context(), inst_id)) {
  374. *phase = LatestPhase(*phase, Phase::TemplateSymbolic);
  375. }
  376. return inst_id;
  377. }
  378. // Explicitly discard a `DestInstId`, because we should not be using the
  379. // destination as part of evaluation.
  380. static auto GetConstantValue(EvalContext& /*eval_context*/,
  381. SemIR::DestInstId /*inst_id*/, Phase* /*phase*/)
  382. -> SemIR::DestInstId {
  383. return SemIR::InstId::None;
  384. }
  385. // Given a type which may refer to a generic parameter, returns the
  386. // corresponding type in the evaluation context.
  387. static auto GetConstantValue(EvalContext& eval_context, SemIR::TypeId type_id,
  388. Phase* phase) -> SemIR::TypeId {
  389. auto const_id = eval_context.GetConstantValue(type_id);
  390. *phase =
  391. LatestPhase(*phase, GetPhase(eval_context.constant_values(), const_id));
  392. return eval_context.context().types().GetTypeIdForTypeConstantId(const_id);
  393. }
  394. // AbsoluteInstBlockId can not have its values substituted, so this overload is
  395. // deleted. This prevents conversion to InstBlockId.
  396. static auto GetConstantValue(EvalContext& eval_context,
  397. SemIR::AbsoluteInstBlockId inst_block_id,
  398. Phase* phase) -> SemIR::InstBlockId = delete;
  399. // If the given instruction block contains only constants, returns a
  400. // corresponding block of those values.
  401. static auto GetConstantValue(EvalContext& eval_context,
  402. SemIR::InstBlockId inst_block_id, Phase* phase)
  403. -> SemIR::InstBlockId {
  404. if (!inst_block_id.has_value()) {
  405. return SemIR::InstBlockId::None;
  406. }
  407. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  408. llvm::SmallVector<SemIR::InstId> const_insts;
  409. for (auto inst_id : insts) {
  410. auto const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  411. if (!const_inst_id.has_value()) {
  412. return SemIR::InstBlockId::None;
  413. }
  414. // Once we leave the small buffer, we know the first few elements are all
  415. // constant, so it's likely that the entire block is constant. Resize to the
  416. // target size given that we're going to allocate memory now anyway.
  417. if (const_insts.size() == const_insts.capacity()) {
  418. const_insts.reserve(insts.size());
  419. }
  420. const_insts.push_back(const_inst_id);
  421. }
  422. // TODO: If the new block is identical to the original block, and we know the
  423. // old ID was canonical, return the original ID.
  424. return eval_context.inst_blocks().AddCanonical(const_insts);
  425. }
  426. // Compute the constant value of a type block. This may be different from the
  427. // input type block if we have known generic arguments.
  428. static auto GetConstantValue(EvalContext& eval_context,
  429. SemIR::StructTypeFieldsId fields_id, Phase* phase)
  430. -> SemIR::StructTypeFieldsId {
  431. if (!fields_id.has_value()) {
  432. return SemIR::StructTypeFieldsId::None;
  433. }
  434. auto fields = eval_context.context().struct_type_fields().Get(fields_id);
  435. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  436. for (auto field : fields) {
  437. auto new_type_id = GetConstantValue(eval_context, field.type_id, phase);
  438. if (!new_type_id.has_value()) {
  439. return SemIR::StructTypeFieldsId::None;
  440. }
  441. // Once we leave the small buffer, we know the first few elements are all
  442. // constant, so it's likely that the entire block is constant. Resize to the
  443. // target size given that we're going to allocate memory now anyway.
  444. if (new_fields.size() == new_fields.capacity()) {
  445. new_fields.reserve(fields.size());
  446. }
  447. new_fields.push_back({.name_id = field.name_id, .type_id = new_type_id});
  448. }
  449. // TODO: If the new block is identical to the original block, and we know the
  450. // old ID was canonical, return the original ID.
  451. return eval_context.context().struct_type_fields().AddCanonical(new_fields);
  452. }
  453. // Compute the constant value of a type block. This may be different from the
  454. // input type block if we have known generic arguments.
  455. static auto GetConstantValue(EvalContext& eval_context,
  456. SemIR::TypeBlockId type_block_id, Phase* phase)
  457. -> SemIR::TypeBlockId {
  458. if (!type_block_id.has_value()) {
  459. return SemIR::TypeBlockId::None;
  460. }
  461. auto types = eval_context.type_blocks().Get(type_block_id);
  462. llvm::SmallVector<SemIR::TypeId> new_types;
  463. for (auto type_id : types) {
  464. auto new_type_id = GetConstantValue(eval_context, type_id, phase);
  465. if (!new_type_id.has_value()) {
  466. return SemIR::TypeBlockId::None;
  467. }
  468. // Once we leave the small buffer, we know the first few elements are all
  469. // constant, so it's likely that the entire block is constant. Resize to the
  470. // target size given that we're going to allocate memory now anyway.
  471. if (new_types.size() == new_types.capacity()) {
  472. new_types.reserve(types.size());
  473. }
  474. new_types.push_back(new_type_id);
  475. }
  476. // TODO: If the new block is identical to the original block, and we know the
  477. // old ID was canonical, return the original ID.
  478. return eval_context.type_blocks().AddCanonical(new_types);
  479. }
  480. // The constant value of a specific is the specific with the corresponding
  481. // constant values for its arguments.
  482. static auto GetConstantValue(EvalContext& eval_context,
  483. SemIR::SpecificId specific_id, Phase* phase)
  484. -> SemIR::SpecificId {
  485. if (!specific_id.has_value()) {
  486. return SemIR::SpecificId::None;
  487. }
  488. const auto& specific = eval_context.specifics().Get(specific_id);
  489. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  490. if (!args_id.has_value()) {
  491. return SemIR::SpecificId::None;
  492. }
  493. if (args_id == specific.args_id) {
  494. const auto& specific = eval_context.specifics().Get(specific_id);
  495. // A constant specific_id should always have a resolved declaration. The
  496. // specific_id from the instruction may coincidentally be canonical, and so
  497. // constant evaluation gives the same value. In that case, we still need to
  498. // ensure its declaration is resolved.
  499. //
  500. // However, don't resolve the declaration if the generic's eval block hasn't
  501. // been set yet. This happens when building the eval block during import.
  502. //
  503. // TODO: Change importing of generic eval blocks to be less fragile and
  504. // remove this `if` so we unconditionally call `ResolveSpecificDeclaration`.
  505. if (!specific.decl_block_id.has_value() && eval_context.context()
  506. .generics()
  507. .Get(specific.generic_id)
  508. .decl_block_id.has_value()) {
  509. ResolveSpecificDeclaration(eval_context.context(),
  510. eval_context.fallback_loc(), specific_id);
  511. }
  512. return specific_id;
  513. }
  514. return MakeSpecific(eval_context.context(), eval_context.fallback_loc(),
  515. specific.generic_id, args_id);
  516. }
  517. static auto GetConstantValue(EvalContext& eval_context,
  518. SemIR::SpecificInterfaceId specific_interface_id,
  519. Phase* phase) -> SemIR::SpecificInterfaceId {
  520. const auto& interface =
  521. eval_context.specific_interfaces().Get(specific_interface_id);
  522. if (!interface.specific_id.has_value()) {
  523. return specific_interface_id;
  524. }
  525. return eval_context.specific_interfaces().Add(
  526. {.interface_id = interface.interface_id,
  527. .specific_id =
  528. GetConstantValue(eval_context, interface.specific_id, phase)});
  529. }
  530. // Like `GetConstantValue` but does a `FacetTypeId` -> `FacetTypeInfo`
  531. // conversion. Does not perform canonicalization.
  532. static auto GetConstantFacetTypeInfo(EvalContext& eval_context,
  533. SemIR::FacetTypeId facet_type_id,
  534. Phase* phase) -> SemIR::FacetTypeInfo {
  535. const auto& orig = eval_context.facet_types().Get(facet_type_id);
  536. SemIR::FacetTypeInfo info;
  537. info.impls_constraints.reserve(orig.impls_constraints.size());
  538. for (const auto& interface : orig.impls_constraints) {
  539. info.impls_constraints.push_back(
  540. {.interface_id = interface.interface_id,
  541. .specific_id =
  542. GetConstantValue(eval_context, interface.specific_id, phase)});
  543. }
  544. info.rewrite_constraints.reserve(orig.rewrite_constraints.size());
  545. for (const auto& rewrite : orig.rewrite_constraints) {
  546. auto lhs_const_id = eval_context.GetInContext(rewrite.lhs_const_id);
  547. auto rhs_const_id = eval_context.GetInContext(rewrite.rhs_const_id);
  548. // `where` requirements using `.Self` should not be considered symbolic
  549. UpdatePhaseIgnorePeriodSelf(eval_context, lhs_const_id, phase);
  550. UpdatePhaseIgnorePeriodSelf(eval_context, rhs_const_id, phase);
  551. info.rewrite_constraints.push_back(
  552. {.lhs_const_id = lhs_const_id, .rhs_const_id = rhs_const_id});
  553. }
  554. // TODO: Process other requirements.
  555. info.other_requirements = orig.other_requirements;
  556. return info;
  557. }
  558. static auto GetConstantValue(EvalContext& eval_context,
  559. SemIR::FacetTypeId facet_type_id, Phase* phase)
  560. -> SemIR::FacetTypeId {
  561. SemIR::FacetTypeInfo info =
  562. GetConstantFacetTypeInfo(eval_context, facet_type_id, phase);
  563. info.Canonicalize();
  564. // TODO: Return `facet_type_id` if we can detect nothing has changed.
  565. return eval_context.facet_types().Add(info);
  566. }
  567. static auto GetConstantValue(EvalContext& eval_context,
  568. SemIR::EntityNameId entity_name_id, Phase* phase)
  569. -> SemIR::EntityNameId {
  570. const auto& bind_name = eval_context.entity_names().Get(entity_name_id);
  571. Phase name_phase;
  572. if (bind_name.name_id == SemIR::NameId::PeriodSelf) {
  573. name_phase = Phase::PeriodSelfSymbolic;
  574. } else if (!bind_name.bind_index().has_value()) {
  575. name_phase = Phase::Concrete;
  576. } else if (bind_name.is_template) {
  577. name_phase = Phase::TemplateSymbolic;
  578. } else {
  579. name_phase = Phase::CheckedSymbolic;
  580. }
  581. *phase = LatestPhase(*phase, name_phase);
  582. return eval_context.entity_names().MakeCanonical(entity_name_id);
  583. }
  584. // Replaces the specified field of the given typed instruction with its constant
  585. // value, if it has constant phase. Returns true on success, false if the value
  586. // has runtime phase.
  587. template <typename InstT, typename FieldIdT>
  588. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  589. InstT* inst, FieldIdT InstT::*field,
  590. Phase* phase) -> bool {
  591. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  592. if (!unwrapped.has_value() && (inst->*field).has_value()) {
  593. return false;
  594. }
  595. inst->*field = unwrapped;
  596. return true;
  597. }
  598. // Function template that can be called with an argument of type `T`. Used below
  599. // to detect which overloads of `GetConstantValue` exist.
  600. template <typename T>
  601. static void Accept(T /*arg*/) {}
  602. // Determines whether a `GetConstantValue` overload exists for a given ID type.
  603. // Note that we do not check whether `GetConstantValue` is *callable* with a
  604. // given ID type, because that would use the `InstId` overload for
  605. // `AbsoluteInstId` and similar wrapper types, which should be left alone.
  606. template <typename IdT>
  607. static constexpr bool HasGetConstantValueOverload = requires {
  608. Accept<auto (*)(EvalContext&, IdT, Phase*)->IdT>(GetConstantValue);
  609. };
  610. using ArgHandlerFnT = auto(EvalContext& context, int32_t arg, Phase* phase)
  611. -> int32_t;
  612. // Returns a lookup table to get constants by Id::Kind. Requires a null IdKind
  613. // as a parameter in order to get the type pack.
  614. template <typename... Types>
  615. static constexpr auto MakeArgHandlerTable(
  616. SemIR::TypeEnum<Types...>* /*id_kind*/)
  617. -> std::array<ArgHandlerFnT*, SemIR::IdKind::NumValues> {
  618. std::array<ArgHandlerFnT*, SemIR::IdKind::NumValues> table = {};
  619. ((table[SemIR::IdKind::template For<Types>.ToIndex()] =
  620. [](EvalContext& eval_context, int32_t arg, Phase* phase) -> int32_t {
  621. auto id = SemIR::Inst::FromRaw<Types>(arg);
  622. if constexpr (HasGetConstantValueOverload<Types>) {
  623. // If we have a custom `GetConstantValue` overload, call it.
  624. return SemIR::Inst::ToRaw(GetConstantValue(eval_context, id, phase));
  625. } else {
  626. // Otherwise, we assume the value is already constant.
  627. return arg;
  628. }
  629. }),
  630. ...);
  631. table[SemIR::IdKind::Invalid.ToIndex()] = [](EvalContext& /*context*/,
  632. int32_t /*arg*/,
  633. Phase* /*phase*/) -> int32_t {
  634. CARBON_FATAL("Instruction has argument with invalid IdKind");
  635. };
  636. table[SemIR::IdKind::None.ToIndex()] =
  637. [](EvalContext& /*context*/, int32_t arg, Phase* /*phase*/) -> int32_t {
  638. return arg;
  639. };
  640. return table;
  641. }
  642. // Given the stored value `arg` of an instruction field and its corresponding
  643. // kind `kind`, returns the constant value to use for that field, if it has a
  644. // constant phase. `*phase` is updated to include the new constant value. If
  645. // the resulting phase is not constant, the returned value is not useful and
  646. // will typically be `NoneIndex`.
  647. static auto GetConstantValueForArg(EvalContext& eval_context,
  648. SemIR::Inst::ArgAndKind arg_and_kind,
  649. Phase* phase) -> int32_t {
  650. static constexpr auto Table =
  651. MakeArgHandlerTable(static_cast<SemIR::IdKind*>(nullptr));
  652. return Table[arg_and_kind.kind().ToIndex()](eval_context,
  653. arg_and_kind.value(), phase);
  654. }
  655. // Given an instruction, replaces its type and operands with their constant
  656. // values from the specified evaluation context. `*phase` is updated to describe
  657. // the constant phase of the result. Returns whether `*phase` is a constant
  658. // phase; if not, `inst` may not be fully updated and should not be used.
  659. static auto ReplaceAllFieldsWithConstantValues(EvalContext& eval_context,
  660. SemIR::Inst* inst, Phase* phase)
  661. -> bool {
  662. auto type_id = SemIR::TypeId(
  663. GetConstantValueForArg(eval_context, inst->type_id_and_kind(), phase));
  664. inst->SetType(type_id);
  665. if (!IsConstant(*phase)) {
  666. return false;
  667. }
  668. auto arg0 =
  669. GetConstantValueForArg(eval_context, inst->arg0_and_kind(), phase);
  670. if (!IsConstant(*phase)) {
  671. return false;
  672. }
  673. auto arg1 =
  674. GetConstantValueForArg(eval_context, inst->arg1_and_kind(), phase);
  675. if (!IsConstant(*phase)) {
  676. return false;
  677. }
  678. inst->SetArgs(arg0, arg1);
  679. return true;
  680. }
  681. auto AddImportedConstant(Context& context, SemIR::Inst inst)
  682. -> SemIR::ConstantId {
  683. EvalContext eval_context(&context, SemIR::InstId::None);
  684. Phase phase = Phase::Concrete;
  685. // TODO: Can we avoid doing this replacement? It may do things that are
  686. // undesirable during importing, such as resolving specifics.
  687. if (!ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  688. return SemIR::ConstantId::NotConstant;
  689. }
  690. return MakeConstantResult(context, inst, phase);
  691. }
  692. // Performs an index into a homogeneous aggregate, retrieving the specified
  693. // element.
  694. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  695. -> SemIR::ConstantId {
  696. Phase phase = Phase::Concrete;
  697. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  698. if (!index_id.has_value()) {
  699. return MakeNonConstantResult(phase);
  700. }
  701. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  702. if (!index) {
  703. CARBON_CHECK(phase != Phase::Concrete,
  704. "Concrete constant integer should be a literal");
  705. return MakeNonConstantResult(phase);
  706. }
  707. // Array indexing is invalid if the index is constant and out of range,
  708. // regardless of whether the array itself is constant.
  709. const auto& index_val = eval_context.ints().Get(index->int_id);
  710. auto aggregate_type_id = eval_context.GetConstantValueAsType(
  711. eval_context.insts().Get(inst.array_id).type_id());
  712. if (auto array_type =
  713. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  714. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  715. array_type->bound_id)) {
  716. // This awkward call to `getZExtValue` is a workaround for APInt not
  717. // supporting comparisons between integers of different bit widths.
  718. if (index_val.getActiveBits() > 64 ||
  719. eval_context.ints()
  720. .Get(bound->int_id)
  721. .ule(index_val.getZExtValue())) {
  722. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  723. "array index `{0}` is past the end of type {1}",
  724. TypedInt, SemIR::TypeId);
  725. eval_context.emitter().Emit(
  726. eval_context.GetDiagnosticLoc(inst.index_id), ArrayIndexOutOfBounds,
  727. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  728. return SemIR::ErrorInst::SingletonConstantId;
  729. }
  730. }
  731. }
  732. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  733. if (!aggregate_id.has_value()) {
  734. return MakeNonConstantResult(phase);
  735. }
  736. auto aggregate =
  737. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  738. if (!aggregate) {
  739. CARBON_CHECK(phase != Phase::Concrete,
  740. "Unexpected representation for template constant aggregate");
  741. return MakeNonConstantResult(phase);
  742. }
  743. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  744. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  745. }
  746. // Forms a constant int type as an evaluation result. Requires that width_id is
  747. // constant.
  748. static auto MakeIntTypeResult(Context& context, SemIRLoc loc,
  749. SemIR::IntKind int_kind, SemIR::InstId width_id,
  750. Phase phase) -> SemIR::ConstantId {
  751. auto result = SemIR::IntType{
  752. .type_id = GetSingletonType(context, SemIR::TypeType::SingletonInstId),
  753. .int_kind = int_kind,
  754. .bit_width_id = width_id};
  755. if (!ValidateIntType(context, loc, result)) {
  756. return SemIR::ErrorInst::SingletonConstantId;
  757. }
  758. return MakeConstantResult(context, result, phase);
  759. }
  760. // Performs a conversion between integer types, truncating if the value doesn't
  761. // fit in the destination type.
  762. static auto PerformIntConvert(Context& context, SemIR::InstId arg_id,
  763. SemIR::TypeId dest_type_id) -> SemIR::ConstantId {
  764. auto arg_val =
  765. context.ints().Get(context.insts().GetAs<SemIR::IntValue>(arg_id).int_id);
  766. auto [dest_is_signed, bit_width_id] =
  767. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  768. if (bit_width_id.has_value()) {
  769. // TODO: If the value fits in the destination type, reuse the existing
  770. // int_id rather than recomputing it. This is probably the most common case.
  771. bool src_is_signed = context.sem_ir().types().IsSignedInt(
  772. context.insts().Get(arg_id).type_id());
  773. unsigned width = context.ints().Get(bit_width_id).getZExtValue();
  774. arg_val =
  775. src_is_signed ? arg_val.sextOrTrunc(width) : arg_val.zextOrTrunc(width);
  776. }
  777. return MakeIntResult(context, dest_type_id, dest_is_signed, arg_val);
  778. }
  779. // Performs a conversion between integer types, diagnosing if the value doesn't
  780. // fit in the destination type.
  781. static auto PerformCheckedIntConvert(Context& context, SemIRLoc loc,
  782. SemIR::InstId arg_id,
  783. SemIR::TypeId dest_type_id)
  784. -> SemIR::ConstantId {
  785. auto arg = context.insts().GetAs<SemIR::IntValue>(arg_id);
  786. auto arg_val = context.ints().Get(arg.int_id);
  787. auto [is_signed, bit_width_id] =
  788. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  789. auto width = bit_width_id.has_value()
  790. ? context.ints().Get(bit_width_id).getZExtValue()
  791. : arg_val.getBitWidth();
  792. if (!is_signed && arg_val.isNegative()) {
  793. CARBON_DIAGNOSTIC(
  794. NegativeIntInUnsignedType, Error,
  795. "negative integer value {0} converted to unsigned type {1}", TypedInt,
  796. SemIR::TypeId);
  797. context.emitter().Emit(loc, NegativeIntInUnsignedType,
  798. {.type = arg.type_id, .value = arg_val},
  799. dest_type_id);
  800. }
  801. unsigned arg_non_sign_bits = arg_val.getSignificantBits() - 1;
  802. if (arg_non_sign_bits + is_signed > width) {
  803. CARBON_DIAGNOSTIC(IntTooLargeForType, Error,
  804. "integer value {0} too large for type {1}", TypedInt,
  805. SemIR::TypeId);
  806. context.emitter().Emit(loc, IntTooLargeForType,
  807. {.type = arg.type_id, .value = arg_val},
  808. dest_type_id);
  809. }
  810. return MakeConstantResult(
  811. context, SemIR::IntValue{.type_id = dest_type_id, .int_id = arg.int_id},
  812. Phase::Concrete);
  813. }
  814. // Issues a diagnostic for a compile-time division by zero.
  815. static auto DiagnoseDivisionByZero(Context& context, SemIRLoc loc) -> void {
  816. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  817. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  818. }
  819. // Get an integer at a suitable bit-width: either `bit_width_id` if it has a
  820. // value, or the canonical width from the value store if not.
  821. static auto GetIntAtSuitableWidth(Context& context, IntId int_id,
  822. IntId bit_width_id) -> llvm::APInt {
  823. return bit_width_id.has_value()
  824. ? context.ints().GetAtWidth(int_id, bit_width_id)
  825. : context.ints().Get(int_id);
  826. }
  827. // Performs a builtin unary integer -> integer operation.
  828. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLoc loc,
  829. SemIR::BuiltinFunctionKind builtin_kind,
  830. SemIR::InstId arg_id)
  831. -> SemIR::ConstantId {
  832. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  833. auto [is_signed, bit_width_id] =
  834. context.sem_ir().types().GetIntTypeInfo(op.type_id);
  835. llvm::APInt op_val = GetIntAtSuitableWidth(context, op.int_id, bit_width_id);
  836. switch (builtin_kind) {
  837. case SemIR::BuiltinFunctionKind::IntSNegate:
  838. if (op_val.isMinSignedValue()) {
  839. if (bit_width_id.has_value()) {
  840. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  841. "integer overflow in negation of {0}", TypedInt);
  842. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  843. {.type = op.type_id, .value = op_val});
  844. } else {
  845. // Widen the integer so we don't overflow into the sign bit.
  846. op_val = op_val.sext(op_val.getBitWidth() +
  847. llvm::APInt::APINT_BITS_PER_WORD);
  848. }
  849. }
  850. op_val.negate();
  851. break;
  852. case SemIR::BuiltinFunctionKind::IntUNegate:
  853. CARBON_CHECK(bit_width_id.has_value(), "Unsigned negate on unsized int");
  854. op_val.negate();
  855. break;
  856. case SemIR::BuiltinFunctionKind::IntComplement:
  857. // TODO: Should we have separate builtins for signed and unsigned
  858. // complement? Like with signed/unsigned negate, these operations do
  859. // different things to the integer value, even though they do the same
  860. // thing to the bits. We treat IntLiteral complement as signed complement,
  861. // given that the result of unsigned complement depends on the bit width.
  862. op_val.flipAllBits();
  863. break;
  864. default:
  865. CARBON_FATAL("Unexpected builtin kind");
  866. }
  867. return MakeIntResult(context, op.type_id, is_signed, std::move(op_val));
  868. }
  869. namespace {
  870. // A pair of APInts that are the operands of a binary operator. We use an
  871. // aggregate rather than `std::pair` to allow RVO of the individual ints.
  872. struct APIntBinaryOperands {
  873. llvm::APInt lhs;
  874. llvm::APInt rhs;
  875. };
  876. } // namespace
  877. // Get a pair of integers at the same suitable bit-width: either their actual
  878. // width if they have a fixed width, or the smallest canonical width in which
  879. // they both fit otherwise.
  880. static auto GetIntsAtSuitableWidth(Context& context, IntId lhs_id, IntId rhs_id,
  881. IntId bit_width_id) -> APIntBinaryOperands {
  882. // Unsized operands: take the wider of the bit widths.
  883. if (!bit_width_id.has_value()) {
  884. APIntBinaryOperands result = {.lhs = context.ints().Get(lhs_id),
  885. .rhs = context.ints().Get(rhs_id)};
  886. if (result.lhs.getBitWidth() != result.rhs.getBitWidth()) {
  887. if (result.lhs.getBitWidth() > result.rhs.getBitWidth()) {
  888. result.rhs = result.rhs.sext(result.lhs.getBitWidth());
  889. } else {
  890. result.lhs = result.lhs.sext(result.rhs.getBitWidth());
  891. }
  892. }
  893. return result;
  894. }
  895. return {.lhs = context.ints().GetAtWidth(lhs_id, bit_width_id),
  896. .rhs = context.ints().GetAtWidth(rhs_id, bit_width_id)};
  897. }
  898. namespace {
  899. // The result of performing a binary int operation.
  900. struct BinaryIntOpResult {
  901. llvm::APInt result_val;
  902. bool overflow;
  903. Lex::TokenKind op_token;
  904. };
  905. } // namespace
  906. // Computes the result of a homogeneous binary (int, int) -> int operation.
  907. static auto ComputeBinaryIntOpResult(SemIR::BuiltinFunctionKind builtin_kind,
  908. const llvm::APInt& lhs_val,
  909. const llvm::APInt& rhs_val)
  910. -> BinaryIntOpResult {
  911. llvm::APInt result_val;
  912. bool overflow = false;
  913. Lex::TokenKind op_token = Lex::TokenKind::Not;
  914. switch (builtin_kind) {
  915. // Arithmetic.
  916. case SemIR::BuiltinFunctionKind::IntSAdd:
  917. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  918. op_token = Lex::TokenKind::Plus;
  919. break;
  920. case SemIR::BuiltinFunctionKind::IntSSub:
  921. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  922. op_token = Lex::TokenKind::Minus;
  923. break;
  924. case SemIR::BuiltinFunctionKind::IntSMul:
  925. result_val = lhs_val.smul_ov(rhs_val, overflow);
  926. op_token = Lex::TokenKind::Star;
  927. break;
  928. case SemIR::BuiltinFunctionKind::IntSDiv:
  929. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  930. op_token = Lex::TokenKind::Slash;
  931. break;
  932. case SemIR::BuiltinFunctionKind::IntSMod:
  933. result_val = lhs_val.srem(rhs_val);
  934. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  935. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  936. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  937. op_token = Lex::TokenKind::Percent;
  938. break;
  939. case SemIR::BuiltinFunctionKind::IntUAdd:
  940. result_val = lhs_val + rhs_val;
  941. op_token = Lex::TokenKind::Plus;
  942. break;
  943. case SemIR::BuiltinFunctionKind::IntUSub:
  944. result_val = lhs_val - rhs_val;
  945. op_token = Lex::TokenKind::Minus;
  946. break;
  947. case SemIR::BuiltinFunctionKind::IntUMul:
  948. result_val = lhs_val * rhs_val;
  949. op_token = Lex::TokenKind::Star;
  950. break;
  951. case SemIR::BuiltinFunctionKind::IntUDiv:
  952. result_val = lhs_val.udiv(rhs_val);
  953. op_token = Lex::TokenKind::Slash;
  954. break;
  955. case SemIR::BuiltinFunctionKind::IntUMod:
  956. result_val = lhs_val.urem(rhs_val);
  957. op_token = Lex::TokenKind::Percent;
  958. break;
  959. // Bitwise.
  960. case SemIR::BuiltinFunctionKind::IntAnd:
  961. result_val = lhs_val & rhs_val;
  962. op_token = Lex::TokenKind::And;
  963. break;
  964. case SemIR::BuiltinFunctionKind::IntOr:
  965. result_val = lhs_val | rhs_val;
  966. op_token = Lex::TokenKind::Pipe;
  967. break;
  968. case SemIR::BuiltinFunctionKind::IntXor:
  969. result_val = lhs_val ^ rhs_val;
  970. op_token = Lex::TokenKind::Caret;
  971. break;
  972. case SemIR::BuiltinFunctionKind::IntLeftShift:
  973. case SemIR::BuiltinFunctionKind::IntRightShift:
  974. CARBON_FATAL("Non-homogeneous operation handled separately.");
  975. default:
  976. CARBON_FATAL("Unexpected operation kind.");
  977. }
  978. return {.result_val = std::move(result_val),
  979. .overflow = overflow,
  980. .op_token = op_token};
  981. }
  982. // Performs a builtin integer bit shift operation.
  983. static auto PerformBuiltinIntShiftOp(Context& context, SemIRLoc loc,
  984. SemIR::BuiltinFunctionKind builtin_kind,
  985. SemIR::InstId lhs_id, SemIR::InstId rhs_id)
  986. -> SemIR::ConstantId {
  987. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  988. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  989. auto [lhs_is_signed, lhs_bit_width_id] =
  990. context.sem_ir().types().GetIntTypeInfo(lhs.type_id);
  991. llvm::APInt lhs_val =
  992. GetIntAtSuitableWidth(context, lhs.int_id, lhs_bit_width_id);
  993. const auto& rhs_orig_val = context.ints().Get(rhs.int_id);
  994. if (lhs_bit_width_id.has_value() && rhs_orig_val.uge(lhs_val.getBitWidth())) {
  995. CARBON_DIAGNOSTIC(
  996. CompileTimeShiftOutOfRange, Error,
  997. "shift distance >= type width of {0} in `{1} {2:<<|>>} {3}`", unsigned,
  998. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  999. context.emitter().Emit(
  1000. loc, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  1001. {.type = lhs.type_id, .value = lhs_val},
  1002. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1003. {.type = rhs.type_id, .value = rhs_orig_val});
  1004. // TODO: Is it useful to recover by returning 0 or -1?
  1005. return SemIR::ErrorInst::SingletonConstantId;
  1006. }
  1007. if (rhs_orig_val.isNegative() &&
  1008. context.sem_ir().types().IsSignedInt(rhs.type_id)) {
  1009. CARBON_DIAGNOSTIC(CompileTimeShiftNegative, Error,
  1010. "shift distance negative in `{0} {1:<<|>>} {2}`",
  1011. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1012. context.emitter().Emit(
  1013. loc, CompileTimeShiftNegative, {.type = lhs.type_id, .value = lhs_val},
  1014. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1015. {.type = rhs.type_id, .value = rhs_orig_val});
  1016. // TODO: Is it useful to recover by returning 0 or -1?
  1017. return SemIR::ErrorInst::SingletonConstantId;
  1018. }
  1019. llvm::APInt result_val;
  1020. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  1021. if (!lhs_bit_width_id.has_value() && !lhs_val.isZero()) {
  1022. // Ensure we don't generate a ridiculously large integer through a bit
  1023. // shift.
  1024. auto width = rhs_orig_val.trySExtValue();
  1025. if (!width ||
  1026. *width > IntStore::MaxIntWidth - lhs_val.getSignificantBits()) {
  1027. CARBON_DIAGNOSTIC(CompileTimeUnsizedShiftOutOfRange, Error,
  1028. "shift distance of {0} would result in an "
  1029. "integer whose width is greater than the "
  1030. "maximum supported width of {1}",
  1031. TypedInt, int);
  1032. context.emitter().Emit(loc, CompileTimeUnsizedShiftOutOfRange,
  1033. {.type = rhs.type_id, .value = rhs_orig_val},
  1034. IntStore::MaxIntWidth);
  1035. return SemIR::ErrorInst::SingletonConstantId;
  1036. }
  1037. lhs_val = lhs_val.sext(
  1038. IntStore::CanonicalBitWidth(lhs_val.getSignificantBits() + *width));
  1039. }
  1040. result_val =
  1041. lhs_val.shl(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1042. } else if (lhs_is_signed) {
  1043. result_val =
  1044. lhs_val.ashr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1045. } else {
  1046. CARBON_CHECK(lhs_bit_width_id.has_value(), "Logical shift on unsized int");
  1047. result_val =
  1048. lhs_val.lshr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1049. }
  1050. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  1051. std::move(result_val));
  1052. }
  1053. // Performs a homogeneous builtin binary integer -> integer operation.
  1054. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLoc loc,
  1055. SemIR::BuiltinFunctionKind builtin_kind,
  1056. SemIR::InstId lhs_id,
  1057. SemIR::InstId rhs_id)
  1058. -> SemIR::ConstantId {
  1059. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1060. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1061. CARBON_CHECK(rhs.type_id == lhs.type_id, "Heterogeneous builtin integer op!");
  1062. auto type_id = lhs.type_id;
  1063. auto [is_signed, bit_width_id] =
  1064. context.sem_ir().types().GetIntTypeInfo(type_id);
  1065. auto [lhs_val, rhs_val] =
  1066. GetIntsAtSuitableWidth(context, lhs.int_id, rhs.int_id, bit_width_id);
  1067. // Check for division by zero.
  1068. switch (builtin_kind) {
  1069. case SemIR::BuiltinFunctionKind::IntSDiv:
  1070. case SemIR::BuiltinFunctionKind::IntSMod:
  1071. case SemIR::BuiltinFunctionKind::IntUDiv:
  1072. case SemIR::BuiltinFunctionKind::IntUMod:
  1073. if (rhs_val.isZero()) {
  1074. DiagnoseDivisionByZero(context, loc);
  1075. return SemIR::ErrorInst::SingletonConstantId;
  1076. }
  1077. break;
  1078. default:
  1079. break;
  1080. }
  1081. BinaryIntOpResult result =
  1082. ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1083. if (result.overflow && !bit_width_id.has_value()) {
  1084. // Retry with a larger bit width. Most operations can only overflow by one
  1085. // bit, but signed n-bit multiplication can overflow to 2n-1 bits. We don't
  1086. // need to handle unsigned multiplication here because it's not permitted
  1087. // for unsized integers.
  1088. //
  1089. // Note that we speculatively first perform the calculation in the width of
  1090. // the wider operand: smaller operations are faster and overflow to a wider
  1091. // integer is unlikely to be needed, especially given that the width will
  1092. // have been rounded up to a multiple of 64 bits by the int store.
  1093. CARBON_CHECK(builtin_kind != SemIR::BuiltinFunctionKind::IntUMul,
  1094. "Unsigned arithmetic requires a fixed bitwidth");
  1095. int new_width =
  1096. builtin_kind == SemIR::BuiltinFunctionKind::IntSMul
  1097. ? lhs_val.getBitWidth() * 2
  1098. : IntStore::CanonicalBitWidth(lhs_val.getBitWidth() + 1);
  1099. new_width = std::min(new_width, IntStore::MaxIntWidth);
  1100. lhs_val = context.ints().GetAtWidth(lhs.int_id, new_width);
  1101. rhs_val = context.ints().GetAtWidth(rhs.int_id, new_width);
  1102. // Note that this can in theory still overflow if we limited `new_width` to
  1103. // `MaxIntWidth`. In that case we fall through to the signed overflow
  1104. // diagnostic below.
  1105. result = ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1106. CARBON_CHECK(!result.overflow || new_width == IntStore::MaxIntWidth);
  1107. }
  1108. if (result.overflow) {
  1109. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  1110. "integer overflow in calculation `{0} {1} {2}`", TypedInt,
  1111. Lex::TokenKind, TypedInt);
  1112. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  1113. {.type = type_id, .value = lhs_val}, result.op_token,
  1114. {.type = type_id, .value = rhs_val});
  1115. }
  1116. return MakeIntResult(context, type_id, is_signed,
  1117. std::move(result.result_val));
  1118. }
  1119. // Performs a builtin integer comparison.
  1120. static auto PerformBuiltinIntComparison(Context& context,
  1121. SemIR::BuiltinFunctionKind builtin_kind,
  1122. SemIR::InstId lhs_id,
  1123. SemIR::InstId rhs_id,
  1124. SemIR::TypeId bool_type_id)
  1125. -> SemIR::ConstantId {
  1126. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1127. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1128. llvm::APInt lhs_val = context.ints().Get(lhs.int_id);
  1129. llvm::APInt rhs_val = context.ints().Get(rhs.int_id);
  1130. bool result;
  1131. switch (builtin_kind) {
  1132. case SemIR::BuiltinFunctionKind::IntEq:
  1133. result = (lhs_val == rhs_val);
  1134. break;
  1135. case SemIR::BuiltinFunctionKind::IntNeq:
  1136. result = (lhs_val != rhs_val);
  1137. break;
  1138. case SemIR::BuiltinFunctionKind::IntLess:
  1139. result = lhs_val.slt(rhs_val);
  1140. break;
  1141. case SemIR::BuiltinFunctionKind::IntLessEq:
  1142. result = lhs_val.sle(rhs_val);
  1143. break;
  1144. case SemIR::BuiltinFunctionKind::IntGreater:
  1145. result = lhs_val.sgt(rhs_val);
  1146. break;
  1147. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  1148. result = lhs_val.sge(rhs_val);
  1149. break;
  1150. default:
  1151. CARBON_FATAL("Unexpected operation kind.");
  1152. }
  1153. return MakeBoolResult(context, bool_type_id, result);
  1154. }
  1155. // Performs a builtin unary float -> float operation.
  1156. static auto PerformBuiltinUnaryFloatOp(Context& context,
  1157. SemIR::BuiltinFunctionKind builtin_kind,
  1158. SemIR::InstId arg_id)
  1159. -> SemIR::ConstantId {
  1160. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  1161. auto op_val = context.floats().Get(op.float_id);
  1162. switch (builtin_kind) {
  1163. case SemIR::BuiltinFunctionKind::FloatNegate:
  1164. op_val.changeSign();
  1165. break;
  1166. default:
  1167. CARBON_FATAL("Unexpected builtin kind");
  1168. }
  1169. return MakeFloatResult(context, op.type_id, std::move(op_val));
  1170. }
  1171. // Performs a builtin binary float -> float operation.
  1172. static auto PerformBuiltinBinaryFloatOp(Context& context,
  1173. SemIR::BuiltinFunctionKind builtin_kind,
  1174. SemIR::InstId lhs_id,
  1175. SemIR::InstId rhs_id)
  1176. -> SemIR::ConstantId {
  1177. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  1178. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  1179. auto lhs_val = context.floats().Get(lhs.float_id);
  1180. auto rhs_val = context.floats().Get(rhs.float_id);
  1181. llvm::APFloat result_val(lhs_val.getSemantics());
  1182. switch (builtin_kind) {
  1183. case SemIR::BuiltinFunctionKind::FloatAdd:
  1184. result_val = lhs_val + rhs_val;
  1185. break;
  1186. case SemIR::BuiltinFunctionKind::FloatSub:
  1187. result_val = lhs_val - rhs_val;
  1188. break;
  1189. case SemIR::BuiltinFunctionKind::FloatMul:
  1190. result_val = lhs_val * rhs_val;
  1191. break;
  1192. case SemIR::BuiltinFunctionKind::FloatDiv:
  1193. result_val = lhs_val / rhs_val;
  1194. break;
  1195. default:
  1196. CARBON_FATAL("Unexpected operation kind.");
  1197. }
  1198. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  1199. }
  1200. // Performs a builtin float comparison.
  1201. static auto PerformBuiltinFloatComparison(
  1202. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1203. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  1204. -> SemIR::ConstantId {
  1205. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  1206. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  1207. const auto& lhs_val = context.floats().Get(lhs.float_id);
  1208. const auto& rhs_val = context.floats().Get(rhs.float_id);
  1209. bool result;
  1210. switch (builtin_kind) {
  1211. case SemIR::BuiltinFunctionKind::FloatEq:
  1212. result = (lhs_val == rhs_val);
  1213. break;
  1214. case SemIR::BuiltinFunctionKind::FloatNeq:
  1215. result = (lhs_val != rhs_val);
  1216. break;
  1217. case SemIR::BuiltinFunctionKind::FloatLess:
  1218. result = lhs_val < rhs_val;
  1219. break;
  1220. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1221. result = lhs_val <= rhs_val;
  1222. break;
  1223. case SemIR::BuiltinFunctionKind::FloatGreater:
  1224. result = lhs_val > rhs_val;
  1225. break;
  1226. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  1227. result = lhs_val >= rhs_val;
  1228. break;
  1229. default:
  1230. CARBON_FATAL("Unexpected operation kind.");
  1231. }
  1232. return MakeBoolResult(context, bool_type_id, result);
  1233. }
  1234. // Performs a builtin boolean comparison.
  1235. static auto PerformBuiltinBoolComparison(
  1236. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1237. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id) {
  1238. bool lhs = context.insts().GetAs<SemIR::BoolLiteral>(lhs_id).value.ToBool();
  1239. bool rhs = context.insts().GetAs<SemIR::BoolLiteral>(rhs_id).value.ToBool();
  1240. return MakeBoolResult(context, bool_type_id,
  1241. builtin_kind == SemIR::BuiltinFunctionKind::BoolEq
  1242. ? lhs == rhs
  1243. : lhs != rhs);
  1244. }
  1245. // Returns a constant for a call to a builtin function.
  1246. static auto MakeConstantForBuiltinCall(EvalContext& eval_context, SemIRLoc loc,
  1247. SemIR::Call call,
  1248. SemIR::BuiltinFunctionKind builtin_kind,
  1249. llvm::ArrayRef<SemIR::InstId> arg_ids,
  1250. Phase phase) -> SemIR::ConstantId {
  1251. auto& context = eval_context.context();
  1252. switch (builtin_kind) {
  1253. case SemIR::BuiltinFunctionKind::None:
  1254. CARBON_FATAL("Not a builtin function.");
  1255. case SemIR::BuiltinFunctionKind::PrintChar:
  1256. case SemIR::BuiltinFunctionKind::PrintInt:
  1257. case SemIR::BuiltinFunctionKind::ReadChar: {
  1258. // These are runtime-only builtins.
  1259. // TODO: Consider tracking this on the `BuiltinFunctionKind`.
  1260. return SemIR::ConstantId::NotConstant;
  1261. }
  1262. case SemIR::BuiltinFunctionKind::TypeAnd: {
  1263. CARBON_CHECK(arg_ids.size() == 2);
  1264. auto lhs_facet_type_id = SemIR::FacetTypeId::None;
  1265. auto rhs_facet_type_id = SemIR::FacetTypeId::None;
  1266. for (auto [facet_type_id, arg_id] :
  1267. llvm::zip(std::to_array({&lhs_facet_type_id, &rhs_facet_type_id}),
  1268. arg_ids)) {
  1269. if (auto facet_type =
  1270. context.insts().TryGetAs<SemIR::FacetType>(arg_id)) {
  1271. *facet_type_id = facet_type->facet_type_id;
  1272. } else {
  1273. CARBON_DIAGNOSTIC(FacetTypeRequiredForTypeAndOperator, Error,
  1274. "non-facet type {0} combined with `&` operator",
  1275. SemIR::TypeId);
  1276. // TODO: Find a location for the lhs or rhs specifically, instead of
  1277. // the whole thing. If that's not possible we can change the text to
  1278. // say if it's referring to the left or the right side for the error.
  1279. // The `arg_id` instruction has no location in it for some reason.
  1280. context.emitter().Emit(
  1281. loc, FacetTypeRequiredForTypeAndOperator,
  1282. context.types().GetTypeIdForTypeInstId(arg_id));
  1283. }
  1284. }
  1285. // Allow errors to be diagnosed for both sides of the operator before
  1286. // returning here if any error occurred on either side.
  1287. if (!lhs_facet_type_id.has_value() || !rhs_facet_type_id.has_value()) {
  1288. return SemIR::ErrorInst::SingletonConstantId;
  1289. }
  1290. // Reuse one of the argument instructions if nothing has changed.
  1291. if (lhs_facet_type_id == rhs_facet_type_id) {
  1292. return context.types().GetConstantId(
  1293. context.types().GetTypeIdForTypeInstId(arg_ids[0]));
  1294. }
  1295. auto info = SemIR::FacetTypeInfo::Combine(
  1296. context.facet_types().Get(lhs_facet_type_id),
  1297. context.facet_types().Get(rhs_facet_type_id));
  1298. info.Canonicalize();
  1299. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1300. }
  1301. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  1302. return context.constant_values().Get(
  1303. SemIR::IntLiteralType::SingletonInstId);
  1304. }
  1305. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  1306. return MakeIntTypeResult(context, loc, SemIR::IntKind::Signed, arg_ids[0],
  1307. phase);
  1308. }
  1309. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  1310. return MakeIntTypeResult(context, loc, SemIR::IntKind::Unsigned,
  1311. arg_ids[0], phase);
  1312. }
  1313. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  1314. // TODO: Support a symbolic constant width.
  1315. if (phase != Phase::Concrete) {
  1316. break;
  1317. }
  1318. if (!ValidateFloatBitWidth(context, loc, arg_ids[0])) {
  1319. return SemIR::ErrorInst::SingletonConstantId;
  1320. }
  1321. return context.constant_values().Get(
  1322. SemIR::LegacyFloatType::SingletonInstId);
  1323. }
  1324. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  1325. return context.constant_values().Get(SemIR::BoolType::SingletonInstId);
  1326. }
  1327. // Integer conversions.
  1328. case SemIR::BuiltinFunctionKind::IntConvert: {
  1329. if (phase != Phase::Concrete) {
  1330. return MakeConstantResult(context, call, phase);
  1331. }
  1332. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1333. }
  1334. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  1335. if (phase != Phase::Concrete) {
  1336. return MakeConstantResult(context, call, phase);
  1337. }
  1338. return PerformCheckedIntConvert(context, loc, arg_ids[0], call.type_id);
  1339. }
  1340. // Unary integer -> integer operations.
  1341. case SemIR::BuiltinFunctionKind::IntSNegate:
  1342. case SemIR::BuiltinFunctionKind::IntUNegate:
  1343. case SemIR::BuiltinFunctionKind::IntComplement: {
  1344. if (phase != Phase::Concrete) {
  1345. break;
  1346. }
  1347. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  1348. }
  1349. // Homogeneous binary integer -> integer operations.
  1350. case SemIR::BuiltinFunctionKind::IntSAdd:
  1351. case SemIR::BuiltinFunctionKind::IntSSub:
  1352. case SemIR::BuiltinFunctionKind::IntSMul:
  1353. case SemIR::BuiltinFunctionKind::IntSDiv:
  1354. case SemIR::BuiltinFunctionKind::IntSMod:
  1355. case SemIR::BuiltinFunctionKind::IntUAdd:
  1356. case SemIR::BuiltinFunctionKind::IntUSub:
  1357. case SemIR::BuiltinFunctionKind::IntUMul:
  1358. case SemIR::BuiltinFunctionKind::IntUDiv:
  1359. case SemIR::BuiltinFunctionKind::IntUMod:
  1360. case SemIR::BuiltinFunctionKind::IntAnd:
  1361. case SemIR::BuiltinFunctionKind::IntOr:
  1362. case SemIR::BuiltinFunctionKind::IntXor: {
  1363. if (phase != Phase::Concrete) {
  1364. break;
  1365. }
  1366. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  1367. arg_ids[1]);
  1368. }
  1369. // Bit shift operations.
  1370. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1371. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1372. if (phase != Phase::Concrete) {
  1373. break;
  1374. }
  1375. return PerformBuiltinIntShiftOp(context, loc, builtin_kind, arg_ids[0],
  1376. arg_ids[1]);
  1377. }
  1378. // Integer comparisons.
  1379. case SemIR::BuiltinFunctionKind::IntEq:
  1380. case SemIR::BuiltinFunctionKind::IntNeq:
  1381. case SemIR::BuiltinFunctionKind::IntLess:
  1382. case SemIR::BuiltinFunctionKind::IntLessEq:
  1383. case SemIR::BuiltinFunctionKind::IntGreater:
  1384. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1385. if (phase != Phase::Concrete) {
  1386. break;
  1387. }
  1388. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1389. arg_ids[1], call.type_id);
  1390. }
  1391. // Unary float -> float operations.
  1392. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1393. if (phase != Phase::Concrete) {
  1394. break;
  1395. }
  1396. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1397. }
  1398. // Binary float -> float operations.
  1399. case SemIR::BuiltinFunctionKind::FloatAdd:
  1400. case SemIR::BuiltinFunctionKind::FloatSub:
  1401. case SemIR::BuiltinFunctionKind::FloatMul:
  1402. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1403. if (phase != Phase::Concrete) {
  1404. break;
  1405. }
  1406. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1407. arg_ids[1]);
  1408. }
  1409. // Float comparisons.
  1410. case SemIR::BuiltinFunctionKind::FloatEq:
  1411. case SemIR::BuiltinFunctionKind::FloatNeq:
  1412. case SemIR::BuiltinFunctionKind::FloatLess:
  1413. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1414. case SemIR::BuiltinFunctionKind::FloatGreater:
  1415. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1416. if (phase != Phase::Concrete) {
  1417. break;
  1418. }
  1419. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1420. arg_ids[1], call.type_id);
  1421. }
  1422. // Bool comparisons.
  1423. case SemIR::BuiltinFunctionKind::BoolEq:
  1424. case SemIR::BuiltinFunctionKind::BoolNeq: {
  1425. if (phase != Phase::Concrete) {
  1426. break;
  1427. }
  1428. return PerformBuiltinBoolComparison(context, builtin_kind, arg_ids[0],
  1429. arg_ids[1], call.type_id);
  1430. }
  1431. }
  1432. return SemIR::ConstantId::NotConstant;
  1433. }
  1434. // Makes a constant for a call instruction.
  1435. static auto MakeConstantForCall(EvalContext& eval_context, SemIRLoc loc,
  1436. SemIR::Call call) -> SemIR::ConstantId {
  1437. Phase phase = Phase::Concrete;
  1438. // A call with an invalid argument list is used to represent an erroneous
  1439. // call.
  1440. //
  1441. // TODO: Use a better representation for this.
  1442. if (call.args_id == SemIR::InstBlockId::None) {
  1443. return SemIR::ErrorInst::SingletonConstantId;
  1444. }
  1445. // Find the constant value of the callee.
  1446. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1447. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1448. auto callee_function =
  1449. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  1450. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1451. if (callee_function.function_id.has_value()) {
  1452. // Calls to builtins might be constant.
  1453. builtin_kind = eval_context.functions()
  1454. .Get(callee_function.function_id)
  1455. .builtin_function_kind;
  1456. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  1457. // TODO: Eventually we'll want to treat some kinds of non-builtin
  1458. // functions as producing constants.
  1459. return SemIR::ConstantId::NotConstant;
  1460. }
  1461. } else {
  1462. // Calls to non-functions, such as calls to generic entity names, might be
  1463. // constant.
  1464. }
  1465. // Find the argument values and the return type.
  1466. bool has_constant_operands =
  1467. has_constant_callee &&
  1468. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::type_id,
  1469. &phase) &&
  1470. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1471. &phase);
  1472. if (phase == Phase::UnknownDueToError) {
  1473. return SemIR::ErrorInst::SingletonConstantId;
  1474. }
  1475. // If any operand of the call is non-constant, the call is non-constant.
  1476. // TODO: Some builtin calls might allow some operands to be non-constant.
  1477. if (!has_constant_operands) {
  1478. if (builtin_kind.IsCompTimeOnly(
  1479. eval_context.sem_ir(), eval_context.inst_blocks().Get(call.args_id),
  1480. call.type_id)) {
  1481. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1482. "non-constant call to compile-time-only function");
  1483. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1484. "compile-time-only function declared here");
  1485. eval_context.emitter()
  1486. .Build(loc, NonConstantCallToCompTimeOnlyFunction)
  1487. .Note(eval_context.functions()
  1488. .Get(callee_function.function_id)
  1489. .latest_decl_id(),
  1490. CompTimeOnlyFunctionHere)
  1491. .Emit();
  1492. }
  1493. return SemIR::ConstantId::NotConstant;
  1494. }
  1495. // Handle calls to builtins.
  1496. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1497. return MakeConstantForBuiltinCall(
  1498. eval_context, loc, call, builtin_kind,
  1499. eval_context.inst_blocks().Get(call.args_id), phase);
  1500. }
  1501. return SemIR::ConstantId::NotConstant;
  1502. }
  1503. // Given an instruction, compute its phase based on its operands.
  1504. static auto ComputeInstPhase(Context& context, SemIR::Inst inst) -> Phase {
  1505. EvalContext eval_context(&context, SemIR::InstId::None);
  1506. auto phase = GetPhase(context.constant_values(),
  1507. context.types().GetConstantId(inst.type_id()));
  1508. GetConstantValueForArg(eval_context, inst.arg0_and_kind(), &phase);
  1509. GetConstantValueForArg(eval_context, inst.arg1_and_kind(), &phase);
  1510. CARBON_CHECK(IsConstant(phase));
  1511. return phase;
  1512. }
  1513. // Convert a ConstantEvalResult to a ConstantId. Factored out of
  1514. // TryEvalTypedInst to avoid repeated instantiation of common code.
  1515. static auto ConvertEvalResultToConstantId(Context& context,
  1516. ConstantEvalResult result,
  1517. Phase orig_phase)
  1518. -> SemIR::ConstantId {
  1519. if (result.is_new()) {
  1520. return MakeConstantResult(
  1521. context, result.new_inst(),
  1522. result.same_phase_as_inst()
  1523. ? orig_phase
  1524. : ComputeInstPhase(context, result.new_inst()));
  1525. }
  1526. return result.existing();
  1527. }
  1528. // Evaluates an instruction of a known type in an evaluation context. The
  1529. // default behavior of this function depends on the constant kind of the
  1530. // instruction:
  1531. //
  1532. // - InstConstantKind::Never: returns ConstantId::NotConstant.
  1533. // - InstConstantKind::Indirect, SymbolicOnly, Conditional: evaluates all the
  1534. // operands of the instruction, and calls `EvalConstantInst` to evaluate the
  1535. // resulting constant instruction.
  1536. // - InstConstantKind::WheneverPossible, Always: evaluates all the operands of
  1537. // the instruction, and produces the resulting constant instruction as the
  1538. // result.
  1539. // - InstConstantKind::Unique: returns the `inst_id` as the resulting
  1540. // constant.
  1541. //
  1542. // Returns an error constant ID if any of the nested evaluations fail, and
  1543. // returns NotConstant if any of the nested evaluations is non-constant.
  1544. //
  1545. // This template is explicitly specialized for instructions that need special
  1546. // handling.
  1547. template <typename InstT>
  1548. static auto TryEvalTypedInst(EvalContext& eval_context, SemIR::InstId inst_id,
  1549. SemIR::Inst inst) -> SemIR::ConstantId {
  1550. constexpr auto ConstantKind = InstT::Kind.constant_kind();
  1551. if constexpr (ConstantKind == SemIR::InstConstantKind::Never) {
  1552. return SemIR::ConstantId::NotConstant;
  1553. } else if constexpr (ConstantKind == SemIR::InstConstantKind::Unique) {
  1554. CARBON_CHECK(inst_id.has_value());
  1555. return SemIR::ConstantId::ForConcreteConstant(inst_id);
  1556. } else {
  1557. // Build a constant instruction by replacing each non-constant operand with
  1558. // its constant value.
  1559. Phase phase = Phase::Concrete;
  1560. if (!ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  1561. if constexpr (ConstantKind == SemIR::InstConstantKind::Always) {
  1562. CARBON_CHECK(phase == Phase::UnknownDueToError,
  1563. "{0} should always be constant", InstT::Kind);
  1564. }
  1565. return MakeNonConstantResult(phase);
  1566. }
  1567. if constexpr (ConstantKind == SemIR::InstConstantKind::Always ||
  1568. ConstantKind == SemIR::InstConstantKind::WheneverPossible) {
  1569. return MakeConstantResult(eval_context.context(), inst, phase);
  1570. } else if constexpr (ConstantKind == SemIR::InstConstantKind::InstAction) {
  1571. auto result_inst_id = PerformDelayedAction(
  1572. eval_context.context(), eval_context.insts().GetLocId(inst_id),
  1573. inst.As<InstT>());
  1574. if (result_inst_id.has_value()) {
  1575. // The result is an instruction.
  1576. return MakeConstantResult(
  1577. eval_context.context(),
  1578. SemIR::InstValue{.type_id = SemIR::InstType::SingletonTypeId,
  1579. .inst_id = result_inst_id},
  1580. Phase::Concrete);
  1581. }
  1582. // Couldn't perform the action because it's still dependent.
  1583. return MakeConstantResult(eval_context.context(), inst,
  1584. Phase::TemplateSymbolic);
  1585. } else {
  1586. return ConvertEvalResultToConstantId(
  1587. eval_context.context(),
  1588. EvalConstantInst(eval_context.context(),
  1589. eval_context.GetDiagnosticLoc({inst_id}),
  1590. inst.As<InstT>()),
  1591. phase);
  1592. }
  1593. }
  1594. }
  1595. // Specialize evaluation for array indexing because we want to check the index
  1596. // expression even if the array expression is non-constant.
  1597. template <>
  1598. auto TryEvalTypedInst<SemIR::ArrayIndex>(EvalContext& eval_context,
  1599. SemIR::InstId /*inst_id*/,
  1600. SemIR::Inst inst)
  1601. -> SemIR::ConstantId {
  1602. return PerformArrayIndex(eval_context, inst.As<SemIR::ArrayIndex>());
  1603. }
  1604. // Specialize evaluation for function calls because we want to check the callee
  1605. // expression even if an argument expression is non-constant, and because we
  1606. // will eventually want to perform control flow handling here.
  1607. template <>
  1608. auto TryEvalTypedInst<SemIR::Call>(EvalContext& eval_context,
  1609. SemIR::InstId inst_id, SemIR::Inst inst)
  1610. -> SemIR::ConstantId {
  1611. return MakeConstantForCall(eval_context,
  1612. eval_context.GetDiagnosticLoc(inst_id),
  1613. inst.As<SemIR::Call>());
  1614. }
  1615. // ImportRefLoaded can have a constant value, but it's owned and maintained by
  1616. // `import_ref.cpp`, not by us.
  1617. // TODO: Rearrange how `ImportRefLoaded` instructions are created so we never
  1618. // call this.
  1619. template <>
  1620. auto TryEvalTypedInst<SemIR::ImportRefLoaded>(EvalContext& /*eval_context*/,
  1621. SemIR::InstId /*inst_id*/,
  1622. SemIR::Inst /*inst*/)
  1623. -> SemIR::ConstantId {
  1624. return SemIR::ConstantId::NotConstant;
  1625. }
  1626. // Symbolic bindings are a special case because they can reach into the eval
  1627. // context and produce a context-specific value.
  1628. template <>
  1629. auto TryEvalTypedInst<SemIR::BindSymbolicName>(EvalContext& eval_context,
  1630. SemIR::InstId /*inst_id*/,
  1631. SemIR::Inst inst)
  1632. -> SemIR::ConstantId {
  1633. auto bind = inst.As<SemIR::BindSymbolicName>();
  1634. // If we know which specific we're evaluating within and this is an argument
  1635. // of that specific, its constant value is the corresponding argument value.
  1636. const auto& bind_name = eval_context.entity_names().Get(bind.entity_name_id);
  1637. if (bind_name.bind_index().has_value()) {
  1638. if (auto value =
  1639. eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  1640. value.has_value()) {
  1641. return value;
  1642. }
  1643. }
  1644. // The constant form of a symbolic binding is an idealized form of the
  1645. // original, with no equivalent value.
  1646. Phase phase = Phase::Concrete;
  1647. bind.value_id = SemIR::InstId::None;
  1648. if (!ReplaceFieldWithConstantValue(
  1649. eval_context, &bind, &SemIR::BindSymbolicName::type_id, &phase) ||
  1650. !ReplaceFieldWithConstantValue(eval_context, &bind,
  1651. &SemIR::BindSymbolicName::entity_name_id,
  1652. &phase)) {
  1653. return MakeNonConstantResult(phase);
  1654. }
  1655. return MakeConstantResult(eval_context.context(), bind, phase);
  1656. }
  1657. // TODO: Convert this to an EvalConstantInst instruction. This will require
  1658. // providing a `GetConstantValue` overload for a requirement block.
  1659. template <>
  1660. auto TryEvalTypedInst<SemIR::WhereExpr>(EvalContext& eval_context,
  1661. SemIR::InstId /*inst_id*/,
  1662. SemIR::Inst inst) -> SemIR::ConstantId {
  1663. auto typed_inst = inst.As<SemIR::WhereExpr>();
  1664. Phase phase = Phase::Concrete;
  1665. SemIR::TypeId base_facet_type_id =
  1666. eval_context.insts().Get(typed_inst.period_self_id).type_id();
  1667. SemIR::Inst base_facet_inst =
  1668. eval_context.GetConstantValueAsInst(base_facet_type_id);
  1669. SemIR::FacetTypeInfo info = {.other_requirements = false};
  1670. // `where` provides that the base facet is an error, `type`, or a facet
  1671. // type.
  1672. if (auto facet_type = base_facet_inst.TryAs<SemIR::FacetType>()) {
  1673. info = GetConstantFacetTypeInfo(eval_context, facet_type->facet_type_id,
  1674. &phase);
  1675. } else if (base_facet_type_id == SemIR::ErrorInst::SingletonTypeId) {
  1676. return SemIR::ErrorInst::SingletonConstantId;
  1677. } else {
  1678. CARBON_CHECK(base_facet_type_id == SemIR::TypeType::SingletonTypeId,
  1679. "Unexpected type_id: {0}, inst: {1}", base_facet_type_id,
  1680. base_facet_inst);
  1681. }
  1682. if (typed_inst.requirements_id.has_value()) {
  1683. auto insts = eval_context.inst_blocks().Get(typed_inst.requirements_id);
  1684. for (auto inst_id : insts) {
  1685. if (auto rewrite =
  1686. eval_context.insts().TryGetAs<SemIR::RequirementRewrite>(
  1687. inst_id)) {
  1688. SemIR::ConstantId lhs = eval_context.GetConstantValue(rewrite->lhs_id);
  1689. SemIR::ConstantId rhs = eval_context.GetConstantValue(rewrite->rhs_id);
  1690. // `where` requirements using `.Self` should not be considered
  1691. // symbolic
  1692. UpdatePhaseIgnorePeriodSelf(eval_context, lhs, &phase);
  1693. UpdatePhaseIgnorePeriodSelf(eval_context, rhs, &phase);
  1694. info.rewrite_constraints.push_back(
  1695. {.lhs_const_id = lhs, .rhs_const_id = rhs});
  1696. } else {
  1697. // TODO: Handle other requirements
  1698. info.other_requirements = true;
  1699. }
  1700. }
  1701. }
  1702. info.Canonicalize();
  1703. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1704. }
  1705. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1706. static auto TryEvalInstInContext(EvalContext& eval_context,
  1707. SemIR::InstId inst_id, SemIR::Inst inst)
  1708. -> SemIR::ConstantId {
  1709. using EvalInstFn =
  1710. auto(EvalContext & eval_context, SemIR::InstId inst_id, SemIR::Inst inst)
  1711. ->SemIR::ConstantId;
  1712. static constexpr EvalInstFn* EvalInstFns[] = {
  1713. #define CARBON_SEM_IR_INST_KIND(Kind) &TryEvalTypedInst<SemIR::Kind>,
  1714. #include "toolchain/sem_ir/inst_kind.def"
  1715. };
  1716. [[clang::musttail]] return EvalInstFns[inst.kind().AsInt()](eval_context,
  1717. inst_id, inst);
  1718. }
  1719. auto TryEvalInst(Context& context, SemIR::LocId loc_id, SemIR::InstId inst_id,
  1720. SemIR::Inst inst) -> SemIR::ConstantId {
  1721. EvalContext eval_context(&context, loc_id);
  1722. return TryEvalInstInContext(eval_context, inst_id, inst);
  1723. }
  1724. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  1725. -> SemIR::ConstantId {
  1726. EvalContext eval_context(&context, inst_id);
  1727. return TryEvalInstInContext(eval_context, inst_id, inst);
  1728. }
  1729. auto TryEvalBlockForSpecific(Context& context, SemIRLoc loc,
  1730. SemIR::SpecificId specific_id,
  1731. SemIR::GenericInstIndex::Region region)
  1732. -> SemIR::InstBlockId {
  1733. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1734. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1735. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1736. llvm::SmallVector<SemIR::InstId> result;
  1737. result.resize(eval_block.size(), SemIR::InstId::None);
  1738. EvalContext eval_context(&context, loc, specific_id,
  1739. SpecificEvalInfo{
  1740. .region = region,
  1741. .values = result,
  1742. });
  1743. Diagnostics::AnnotationScope annotate_diagnostics(
  1744. &context.emitter(), [&](auto& builder) {
  1745. CARBON_DIAGNOSTIC(ResolvingSpecificHere, Note, "in {0} used here",
  1746. SemIR::SpecificId);
  1747. builder.Note(loc, ResolvingSpecificHere, specific_id);
  1748. });
  1749. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1750. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1751. context.insts().Get(inst_id));
  1752. result[i] = context.constant_values().GetInstId(const_id);
  1753. CARBON_CHECK(result[i].has_value(), "Failed to evaluate {0} in eval block",
  1754. context.insts().Get(inst_id));
  1755. }
  1756. return context.inst_blocks().Add(result);
  1757. }
  1758. } // namespace Carbon::Check