eval.cpp 77 KB

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