facet_type.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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/facet_type.h"
  5. #include <compare>
  6. #include "llvm/ADT/ArrayRef.h"
  7. #include "llvm/ADT/STLExtras.h"
  8. #include "toolchain/check/convert.h"
  9. #include "toolchain/check/diagnostic_helpers.h"
  10. #include "toolchain/check/generic.h"
  11. #include "toolchain/check/import_ref.h"
  12. #include "toolchain/check/inst.h"
  13. #include "toolchain/check/interface.h"
  14. #include "toolchain/check/subst.h"
  15. #include "toolchain/check/type.h"
  16. #include "toolchain/check/type_completion.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Check {
  20. auto FacetTypeFromInterface(Context& context, SemIR::InterfaceId interface_id,
  21. SemIR::SpecificId specific_id) -> SemIR::FacetType {
  22. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(
  23. SemIR::FacetTypeInfo{.extend_constraints = {{interface_id, specific_id}},
  24. .other_requirements = false});
  25. return {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id};
  26. }
  27. // Returns whether the `LookupImplWitness` of `witness_id` matches `interface`.
  28. static auto WitnessQueryMatchesInterface(
  29. Context& context, SemIR::InstId witness_id,
  30. const SemIR::SpecificInterface& interface) -> bool {
  31. auto lookup = context.insts().GetAs<SemIR::LookupImplWitness>(witness_id);
  32. return interface ==
  33. context.specific_interfaces().Get(lookup.query_specific_interface_id);
  34. }
  35. static auto IncompleteFacetTypeDiagnosticBuilder(
  36. Context& context, SemIR::LocId loc_id, SemIR::TypeInstId facet_type_inst_id,
  37. bool is_definition) -> DiagnosticBuilder {
  38. if (is_definition) {
  39. CARBON_DIAGNOSTIC(ImplAsIncompleteFacetTypeDefinition, Error,
  40. "definition of impl as incomplete facet type {0}",
  41. InstIdAsType);
  42. return context.emitter().Build(loc_id, ImplAsIncompleteFacetTypeDefinition,
  43. facet_type_inst_id);
  44. } else {
  45. CARBON_DIAGNOSTIC(
  46. ImplAsIncompleteFacetTypeRewrites, Error,
  47. "declaration of impl as incomplete facet type {0} with rewrites",
  48. InstIdAsType);
  49. return context.emitter().Build(loc_id, ImplAsIncompleteFacetTypeRewrites,
  50. facet_type_inst_id);
  51. }
  52. }
  53. auto InitialFacetTypeImplWitness(
  54. Context& context, SemIR::LocId witness_loc_id,
  55. SemIR::TypeInstId facet_type_inst_id, SemIR::TypeInstId self_type_inst_id,
  56. const SemIR::SpecificInterface& interface_to_witness,
  57. SemIR::SpecificId self_specific_id, bool is_definition) -> SemIR::InstId {
  58. // TODO: Finish facet type resolution. This code currently only handles
  59. // rewrite constraints that set associated constants to a concrete value.
  60. // Need logic to topologically sort rewrites to respect dependencies, and
  61. // afterwards reject duplicates that are not identical.
  62. auto facet_type_id =
  63. context.types().GetTypeIdForTypeInstId(facet_type_inst_id);
  64. CARBON_CHECK(facet_type_id != SemIR::ErrorInst::TypeId);
  65. auto facet_type = context.types().GetAs<SemIR::FacetType>(facet_type_id);
  66. // TODO: This is currently a copy because I'm not sure whether anything could
  67. // cause the facet type store to resize before we are done with it.
  68. auto facet_type_info = context.facet_types().Get(facet_type.facet_type_id);
  69. if (!is_definition && facet_type_info.rewrite_constraints.empty()) {
  70. auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
  71. context, witness_loc_id,
  72. {.elements_id = context.inst_blocks().AddPlaceholder(),
  73. .impl_id = SemIR::ImplId::None});
  74. return AddInst<SemIR::ImplWitness>(
  75. context, witness_loc_id,
  76. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  77. .witness_table_id = witness_table_inst_id,
  78. .specific_id = self_specific_id});
  79. }
  80. if (!RequireCompleteType(
  81. context, facet_type_id, SemIR::LocId(facet_type_inst_id), [&] {
  82. return IncompleteFacetTypeDiagnosticBuilder(
  83. context, witness_loc_id, facet_type_inst_id, is_definition);
  84. })) {
  85. return SemIR::ErrorInst::InstId;
  86. }
  87. const auto& interface =
  88. context.interfaces().Get(interface_to_witness.interface_id);
  89. auto assoc_entities =
  90. context.inst_blocks().Get(interface.associated_entities_id);
  91. // TODO: When this function is used for things other than just impls, may want
  92. // to only load the specific associated entities that are mentioned in rewrite
  93. // rules.
  94. for (auto decl_id : assoc_entities) {
  95. LoadImportRef(context, decl_id);
  96. }
  97. SemIR::InstId witness_inst_id = SemIR::InstId::None;
  98. llvm::MutableArrayRef<SemIR::InstId> table;
  99. {
  100. auto elements_id =
  101. context.inst_blocks().AddUninitialized(assoc_entities.size());
  102. table = context.inst_blocks().GetMutable(elements_id);
  103. for (auto& uninit : table) {
  104. uninit = SemIR::ImplWitnessTablePlaceholder::TypeInstId;
  105. }
  106. auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
  107. context, witness_loc_id,
  108. {.elements_id = elements_id, .impl_id = SemIR::ImplId::None});
  109. witness_inst_id = AddInst<SemIR::ImplWitness>(
  110. context, witness_loc_id,
  111. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  112. .witness_table_id = witness_table_inst_id,
  113. .specific_id = self_specific_id});
  114. }
  115. for (auto rewrite : facet_type_info.rewrite_constraints) {
  116. auto access =
  117. context.insts().GetAs<SemIR::ImplWitnessAccess>(rewrite.lhs_id);
  118. if (!WitnessQueryMatchesInterface(context, access.witness_id,
  119. interface_to_witness)) {
  120. continue;
  121. }
  122. auto& table_entry = table[access.index.index];
  123. if (table_entry == SemIR::ErrorInst::InstId) {
  124. // Don't overwrite an error value. This prioritizes not generating
  125. // multiple errors for one associated constant over picking a value
  126. // for it to use to attempt recovery.
  127. continue;
  128. }
  129. auto rewrite_inst_id = rewrite.rhs_id;
  130. if (rewrite_inst_id == SemIR::ErrorInst::InstId) {
  131. table_entry = SemIR::ErrorInst::InstId;
  132. continue;
  133. }
  134. auto decl_id = context.constant_values().GetConstantInstId(
  135. assoc_entities[access.index.index]);
  136. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  137. if (decl_id == SemIR::ErrorInst::InstId) {
  138. table_entry = SemIR::ErrorInst::InstId;
  139. continue;
  140. }
  141. auto assoc_constant_decl =
  142. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id);
  143. if (!assoc_constant_decl) {
  144. auto type_id = context.insts().Get(decl_id).type_id();
  145. auto type_inst = context.types().GetAsInst(type_id);
  146. auto fn_type = type_inst.As<SemIR::FunctionType>();
  147. const auto& fn = context.functions().Get(fn_type.function_id);
  148. CARBON_DIAGNOSTIC(RewriteForAssociatedFunction, Error,
  149. "rewrite specified for associated function {0}",
  150. SemIR::NameId);
  151. context.emitter().Emit(facet_type_inst_id, RewriteForAssociatedFunction,
  152. fn.name_id);
  153. table_entry = SemIR::ErrorInst::InstId;
  154. continue;
  155. }
  156. // FacetTypes resolution disallows two rewrites to the same associated
  157. // constant, so we won't ever have a facet write twice to the same position
  158. // in the witness table.
  159. CARBON_CHECK(table_entry == SemIR::ImplWitnessTablePlaceholder::TypeInstId);
  160. // If the associated constant has a symbolic type, convert the rewrite
  161. // value to that type now we know the value of `Self`.
  162. SemIR::TypeId assoc_const_type_id = assoc_constant_decl->type_id;
  163. if (assoc_const_type_id.is_symbolic()) {
  164. // Get the type of the associated constant in this interface with this
  165. // value for `Self`.
  166. assoc_const_type_id = GetTypeForSpecificAssociatedEntity(
  167. context, SemIR::LocId(facet_type_inst_id),
  168. interface_to_witness.specific_id, decl_id,
  169. context.types().GetTypeIdForTypeInstId(self_type_inst_id),
  170. witness_inst_id);
  171. // Perform the conversion of the value to the type. We skipped this when
  172. // forming the facet type because the type of the associated constant
  173. // was symbolic.
  174. auto converted_inst_id =
  175. ConvertToValueOfType(context, SemIR::LocId(facet_type_inst_id),
  176. rewrite_inst_id, assoc_const_type_id);
  177. // Canonicalize the converted constant value.
  178. converted_inst_id =
  179. context.constant_values().GetConstantInstId(converted_inst_id);
  180. // The result of conversion can be non-constant even if the original
  181. // value was constant.
  182. if (converted_inst_id.has_value()) {
  183. rewrite_inst_id = converted_inst_id;
  184. } else {
  185. const auto& assoc_const = context.associated_constants().Get(
  186. assoc_constant_decl->assoc_const_id);
  187. CARBON_DIAGNOSTIC(
  188. AssociatedConstantNotConstantAfterConversion, Error,
  189. "associated constant {0} given value {1} that is not constant "
  190. "after conversion to {2}",
  191. SemIR::NameId, InstIdAsConstant, SemIR::TypeId);
  192. context.emitter().Emit(
  193. facet_type_inst_id, AssociatedConstantNotConstantAfterConversion,
  194. assoc_const.name_id, rewrite_inst_id, assoc_const_type_id);
  195. rewrite_inst_id = SemIR::ErrorInst::InstId;
  196. }
  197. }
  198. CARBON_CHECK(rewrite_inst_id == context.constant_values().GetConstantInstId(
  199. rewrite_inst_id),
  200. "Rewritten value for associated constant is not canonical.");
  201. table_entry = AddInst<SemIR::ImplWitnessAssociatedConstant>(
  202. context, witness_loc_id,
  203. {.type_id = context.insts().Get(rewrite_inst_id).type_id(),
  204. .inst_id = rewrite_inst_id});
  205. }
  206. return witness_inst_id;
  207. }
  208. auto RequireCompleteFacetTypeForImplDefinition(
  209. Context& context, SemIR::LocId loc_id, SemIR::TypeInstId facet_type_inst_id)
  210. -> bool {
  211. auto facet_type_id =
  212. context.types().GetTypeIdForTypeInstId(facet_type_inst_id);
  213. return RequireCompleteType(
  214. context, facet_type_id, SemIR::LocId(facet_type_inst_id), [&] {
  215. return IncompleteFacetTypeDiagnosticBuilder(context, loc_id,
  216. facet_type_inst_id,
  217. /*is_definition=*/true);
  218. });
  219. }
  220. auto AllocateFacetTypeImplWitness(Context& context,
  221. SemIR::InterfaceId interface_id,
  222. SemIR::InstBlockId witness_id) -> void {
  223. const auto& interface = context.interfaces().Get(interface_id);
  224. CARBON_CHECK(interface.is_complete());
  225. auto assoc_entities =
  226. context.inst_blocks().Get(interface.associated_entities_id);
  227. for (auto decl_id : assoc_entities) {
  228. LoadImportRef(context, decl_id);
  229. }
  230. llvm::SmallVector<SemIR::InstId> empty_table(
  231. assoc_entities.size(), SemIR::ImplWitnessTablePlaceholder::TypeInstId);
  232. context.inst_blocks().ReplacePlaceholder(witness_id, empty_table);
  233. }
  234. namespace {
  235. struct FacetTypeConstraintValue {
  236. SemIR::EntityNameId entity_name_id;
  237. SemIR::ElementIndex access_index;
  238. SemIR::SpecificInterfaceId specific_interface_id;
  239. friend auto operator==(const FacetTypeConstraintValue& lhs,
  240. const FacetTypeConstraintValue& rhs) -> bool = default;
  241. };
  242. } // namespace
  243. static auto GetFacetTypeConstraintValue(Context& context,
  244. SemIR::ImplWitnessAccess access)
  245. -> std::optional<FacetTypeConstraintValue> {
  246. auto lookup =
  247. context.insts().TryGetAs<SemIR::LookupImplWitness>(access.witness_id);
  248. if (lookup) {
  249. auto self = context.insts().TryGetAs<SemIR::BindSymbolicName>(
  250. context.constant_values().GetConstantInstId(
  251. lookup->query_self_inst_id));
  252. if (self) {
  253. return {{.entity_name_id = self->entity_name_id,
  254. .access_index = access.index,
  255. .specific_interface_id = lookup->query_specific_interface_id}};
  256. }
  257. }
  258. return std::nullopt;
  259. }
  260. // Returns true if two values in a rewrite constraint are equivalent. Two
  261. // `ImplWitnessAccess` instructions that refer to the same associated constant
  262. // through the same facet value are treated as equivalent.
  263. static auto CompareFacetTypeConstraintValues(Context& context,
  264. SemIR::InstId lhs_id,
  265. SemIR::InstId rhs_id) -> bool {
  266. if (lhs_id == rhs_id) {
  267. return true;
  268. }
  269. auto lhs_access = context.insts().TryGetAs<SemIR::ImplWitnessAccess>(lhs_id);
  270. auto rhs_access = context.insts().TryGetAs<SemIR::ImplWitnessAccess>(rhs_id);
  271. if (lhs_access && rhs_access) {
  272. auto lhs_access_value = GetFacetTypeConstraintValue(context, *lhs_access);
  273. auto rhs_access_value = GetFacetTypeConstraintValue(context, *rhs_access);
  274. // We do *not* want to get the evaluated result of `ImplWitnessAccess` here,
  275. // we want to keep them as a reference to an associated constant for the
  276. // resolution phase.
  277. return lhs_access_value && rhs_access_value &&
  278. *lhs_access_value == *rhs_access_value;
  279. }
  280. return context.constant_values().GetConstantInstId(lhs_id) ==
  281. context.constant_values().GetConstantInstId(rhs_id);
  282. }
  283. // A mapping of each associated constant (represented as `ImplWitnessAccess`) to
  284. // its value (represented as an `InstId`). Used to track rewrite constraints,
  285. // with the LHS mapping to the resolved value of the RHS.
  286. class AccessRewriteValues {
  287. public:
  288. enum State {
  289. NotRewritten,
  290. BeingRewritten,
  291. FullyRewritten,
  292. };
  293. struct Value {
  294. State state;
  295. SemIR::InstId inst_id;
  296. };
  297. auto InsertNotRewritten(Context& context, SemIR::ImplWitnessAccess access,
  298. SemIR::InstId inst_id) -> void {
  299. map_.insert({*GetKey(context, access), {NotRewritten, inst_id}});
  300. }
  301. // Finds and returns a pointer into the cache for a given ImplWitnessAccess.
  302. // The pointer will be invalidated by mutating the cache. Returns `nullptr`
  303. // if `access` is not found.
  304. auto FindRef(Context& context, SemIR::ImplWitnessAccess access) -> Value* {
  305. auto key = GetKey(context, access);
  306. if (!key) {
  307. return nullptr;
  308. }
  309. auto it = map_.find(*key);
  310. if (it == map_.end()) {
  311. return nullptr;
  312. }
  313. return &it->second;
  314. }
  315. auto SetBeingRewritten(Value& value) -> void {
  316. if (value.state == NotRewritten) {
  317. value.state = BeingRewritten;
  318. }
  319. }
  320. auto SetFullyRewritten(Context& context, Value& value, SemIR::InstId inst_id)
  321. -> void {
  322. CARBON_CHECK(
  323. value.state == BeingRewritten ||
  324. CompareFacetTypeConstraintValues(context, value.inst_id, inst_id));
  325. value = {FullyRewritten, inst_id};
  326. }
  327. private:
  328. using Key = FacetTypeConstraintValue;
  329. struct KeyInfo {
  330. static auto getEmptyKey() -> Key {
  331. return {
  332. .entity_name_id = SemIR::EntityNameId::None,
  333. .access_index = SemIR::ElementIndex(-1),
  334. .specific_interface_id = SemIR::SpecificInterfaceId::None,
  335. };
  336. }
  337. static auto getTombstoneKey() -> Key {
  338. return {
  339. .entity_name_id = SemIR::EntityNameId::None,
  340. .access_index = SemIR::ElementIndex(-2),
  341. .specific_interface_id = SemIR::SpecificInterfaceId::None,
  342. };
  343. }
  344. static auto getHashValue(Key key) -> unsigned {
  345. // This hash produces the same value if two ImplWitnessAccess are
  346. // pointing to the same associated constant, even if they are different
  347. // instruction ids.
  348. //
  349. // TODO: This truncates the high bits of the hash code which does not
  350. // make for a good hash function.
  351. return static_cast<unsigned>(static_cast<uint64_t>(HashValue(key)));
  352. }
  353. static auto isEqual(Key lhs, Key rhs) -> bool {
  354. // This comparison is true if the two ImplWitnessAccess are pointing to
  355. // the same associated constant, even if they are different instruction
  356. // ids.
  357. return lhs == rhs;
  358. }
  359. };
  360. // Returns a key for the `access` to an associated context if the access is
  361. // through a facet value. If the access it through another `ImplWitnessAccess`
  362. // then no key is able to be made.
  363. auto GetKey(Context& context, SemIR::ImplWitnessAccess access)
  364. -> std::optional<Key> {
  365. return GetFacetTypeConstraintValue(context, access);
  366. }
  367. // Try avoid heap allocations in the common case where there are a small
  368. // number of rewrite rules referring to each other by keeping up to 16 on
  369. // the stack.
  370. //
  371. // TODO: Revisit if 16 is an appropriate number when we can measure how deep
  372. // rewrite constraint chains go in practice.
  373. llvm::SmallDenseMap<Key, Value, 16, KeyInfo> map_;
  374. };
  375. // To be used for substituting into the RHS of a rewrite constraint.
  376. //
  377. // It will substitute any `ImplWitnessAccess` into `.Self` (a reference to an
  378. // associated constant) with the RHS of another rewrite constraint that writes
  379. // to the same associated constant. For example:
  380. // ```
  381. // Z where .X = () and .Y = .X
  382. // ```
  383. // Here the second `.X` is an `ImplWitnessAccess` which would be substituted by
  384. // finding the first rewrite constraint, where the LHS is for the same
  385. // associated constant and using its RHS. So the substitution would produce:
  386. // ```
  387. // Z where .X = () and .Y = ()
  388. // ```
  389. //
  390. // This additionally diagnoses cycles when the `ImplWitnessAccess` is reading
  391. // from the same rewrite constraint, and is thus assigning to the associated
  392. // constant a value that refers to the same associated constant, such as with `Z
  393. // where .X = C(.X)`. In the event of a cycle, the `ImplWitnessAccess` is
  394. // replaced with `ErrorInst` so that further evaluation of the
  395. // `ImplWitnessAccess` will not loop infinitely.
  396. //
  397. // The `rewrite_values` given to the constructor must be set up initially with
  398. // each rewrite rule of an associated constant inserted with its unresolved
  399. // value via `InsertNotRewritten`. Then for each rewrite rule of an associated
  400. // constant, the LHS access should be set as being rewritten with its state
  401. // changed to `BeingRewritten` in order to detect cycles before performing
  402. // SubstInst. The result of SubstInst should be preserved afterward by changing
  403. // the state and value for the LHS to `FullyRewritten` and the subst output
  404. // instruction, respectively, to avoid duplicating work.
  405. class SubstImplWitnessAccessCallbacks : public SubstInstCallbacks {
  406. public:
  407. explicit SubstImplWitnessAccessCallbacks(Context* context,
  408. SemIR::LocId loc_id,
  409. AccessRewriteValues* rewrite_values)
  410. : SubstInstCallbacks(context),
  411. loc_id_(loc_id),
  412. rewrite_values_(rewrite_values) {}
  413. auto Subst(SemIR::InstId& rhs_inst_id) -> SubstResult override {
  414. auto rhs_access =
  415. context().insts().TryGetAs<SemIR::ImplWitnessAccess>(rhs_inst_id);
  416. if (!rhs_access) {
  417. // We only want to substitute ImplWitnessAccesses written directly on the
  418. // RHS of the rewrite constraint, not when they are nested inside facet
  419. // types that are part of the RHS, like `.X = C as (I where .Y = {})`.
  420. if (context().insts().Is<SemIR::FacetType>(rhs_inst_id)) {
  421. return SubstResult::FullySubstituted;
  422. }
  423. if (context().constant_values().Get(rhs_inst_id).is_concrete()) {
  424. // There's no ImplWitnessAccess that we care about inside this
  425. // instruction.
  426. return SubstResult::FullySubstituted;
  427. } else {
  428. // SubstOperands will result in a Rebuild or ReuseUnchanged callback, so
  429. // push the non-ImplWitnessAccess to get proper bracketing, allowing us
  430. // to pop it in the paired callback.
  431. substs_in_progress_.push_back(rhs_inst_id);
  432. return SubstResult::SubstOperands;
  433. }
  434. }
  435. // If the access is going through a nested `ImplWitnessAccess`, that
  436. // access needs to be resolved to a facet value first. If it can't be
  437. // resolved then the outer one can not be either.
  438. if (auto lookup = context().insts().TryGetAs<SemIR::LookupImplWitness>(
  439. rhs_access->witness_id)) {
  440. if (context().insts().Is<SemIR::ImplWitnessAccess>(
  441. lookup->query_self_inst_id)) {
  442. substs_in_progress_.push_back(rhs_inst_id);
  443. return SubstResult::SubstOperandsAndRetry;
  444. }
  445. }
  446. auto* rewrite_value = rewrite_values_->FindRef(context(), *rhs_access);
  447. if (!rewrite_value) {
  448. // The RHS refers to an associated constant for which there is no rewrite
  449. // rule.
  450. return SubstResult::FullySubstituted;
  451. }
  452. // Diagnose a cycle if the RHS refers to something that depends on the value
  453. // of the RHS.
  454. if (rewrite_value->state == AccessRewriteValues::BeingRewritten) {
  455. CARBON_DIAGNOSTIC(FacetTypeConstraintCycle, Error,
  456. "found cycle in facet type constraint for {0}",
  457. InstIdAsConstant);
  458. // TODO: It would be nice to note the places where the values are
  459. // assigned but rewrite constraint instructions are from canonical
  460. // constant values, and have no locations. We'd need to store a location
  461. // along with them in the rewrite constraints, and track propagation of
  462. // locations here, which may imply heap allocations.
  463. context().emitter().Emit(loc_id_, FacetTypeConstraintCycle, rhs_inst_id);
  464. rhs_inst_id = SemIR::ErrorInst::InstId;
  465. return SubstResult::FullySubstituted;
  466. } else if (rewrite_value->state == AccessRewriteValues::FullyRewritten) {
  467. rhs_inst_id = rewrite_value->inst_id;
  468. return SubstResult::FullySubstituted;
  469. }
  470. // We have a non-rewritten RHS. We need to recurse on rewriting it. Reuse
  471. // the previous lookup by mutating it in place.
  472. rewrite_values_->SetBeingRewritten(*rewrite_value);
  473. // The ImplWitnessAccess was replaced with some other instruction, which may
  474. // contain or be another ImplWitnessAccess. Keep track of the associated
  475. // constant we are now computing the value of.
  476. substs_in_progress_.push_back(rhs_inst_id);
  477. rhs_inst_id = rewrite_value->inst_id;
  478. return SubstResult::SubstAgain;
  479. }
  480. auto Rebuild(SemIR::InstId /*orig_inst_id*/, SemIR::Inst new_inst)
  481. -> SemIR::InstId override {
  482. auto inst_id = RebuildNewInst(loc_id_, new_inst);
  483. auto subst_inst_id = substs_in_progress_.pop_back_val();
  484. if (auto access = context().insts().TryGetAs<SemIR::ImplWitnessAccess>(
  485. subst_inst_id)) {
  486. if (auto* rewrite_value = rewrite_values_->FindRef(context(), *access)) {
  487. rewrite_values_->SetFullyRewritten(context(), *rewrite_value, inst_id);
  488. }
  489. }
  490. return inst_id;
  491. }
  492. auto ReuseUnchanged(SemIR::InstId orig_inst_id) -> SemIR::InstId override {
  493. auto subst_inst_id = substs_in_progress_.pop_back_val();
  494. if (auto access = context().insts().TryGetAs<SemIR::ImplWitnessAccess>(
  495. subst_inst_id)) {
  496. if (auto* rewrite_value = rewrite_values_->FindRef(context(), *access)) {
  497. rewrite_values_->SetFullyRewritten(context(), *rewrite_value,
  498. orig_inst_id);
  499. }
  500. }
  501. return orig_inst_id;
  502. }
  503. private:
  504. struct SubstInProgress {
  505. // The associated constant whose value is being determined, represented as
  506. // an ImplWitnessAccess. Or another instruction that we are recursing
  507. // through.
  508. SemIR::InstId inst_id;
  509. };
  510. // The location of the rewrite constraints as a whole.
  511. SemIR::LocId loc_id_;
  512. // Tracks the resolved value of each rewrite constraint, keyed by the
  513. // `ImplWitnessAccess` of the associated constant on the LHS of the
  514. // constraint. The value of each associated constant may be changed during
  515. // substitution, replaced with a fully resolved value for the RHS. This allows
  516. // us to cache work; when a value for an associated constant is found once it
  517. // can be reused cheaply, avoiding exponential runtime when rewrite rules
  518. // refer to each other in ways that create exponential references.
  519. AccessRewriteValues* rewrite_values_;
  520. // A stack of instructions being replaced in Subst(). When it's an associated
  521. // constant, then it represents the constant value is being determined,
  522. // represented as an ImplWitnessAccess.
  523. //
  524. // Avoid heap allocations in common cases, if there are chains of instructions
  525. // in associated constants with a depth at most 16.
  526. llvm::SmallVector<SemIR::InstId, 16> substs_in_progress_;
  527. };
  528. auto ResolveFacetTypeRewriteConstraints(
  529. Context& context, SemIR::LocId loc_id,
  530. llvm::SmallVector<SemIR::FacetTypeInfo::RewriteConstraint>& rewrites)
  531. -> bool {
  532. if (rewrites.empty()) {
  533. return true;
  534. }
  535. AccessRewriteValues rewrite_values;
  536. for (auto& constraint : rewrites) {
  537. auto lhs_access =
  538. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(constraint.lhs_id);
  539. if (!lhs_access) {
  540. continue;
  541. }
  542. rewrite_values.InsertNotRewritten(context, *lhs_access, constraint.rhs_id);
  543. }
  544. for (auto& constraint : rewrites) {
  545. auto lhs_access =
  546. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(constraint.lhs_id);
  547. if (!lhs_access) {
  548. continue;
  549. }
  550. auto* lhs_rewrite_value = rewrite_values.FindRef(context, *lhs_access);
  551. // Every LHS was added with InsertNotRewritten above.
  552. CARBON_CHECK(lhs_rewrite_value);
  553. rewrite_values.SetBeingRewritten(*lhs_rewrite_value);
  554. auto replace_witness_callbacks =
  555. SubstImplWitnessAccessCallbacks(&context, loc_id, &rewrite_values);
  556. auto rhs_subst_inst_id =
  557. SubstInst(context, constraint.rhs_id, replace_witness_callbacks);
  558. if (rhs_subst_inst_id == SemIR::ErrorInst::InstId) {
  559. return false;
  560. }
  561. if (lhs_rewrite_value->state == AccessRewriteValues::FullyRewritten &&
  562. !CompareFacetTypeConstraintValues(context, lhs_rewrite_value->inst_id,
  563. rhs_subst_inst_id)) {
  564. if (lhs_rewrite_value->inst_id != SemIR::ErrorInst::InstId) {
  565. CARBON_DIAGNOSTIC(AssociatedConstantWithDifferentValues, Error,
  566. "associated constant {0} given two different "
  567. "values {1} and {2}",
  568. InstIdAsConstant, InstIdAsConstant, InstIdAsConstant);
  569. // Use inst id ordering as a simple proxy for source ordering, to
  570. // try to name the values in the same order they appear in the facet
  571. // type.
  572. auto source_order1 =
  573. lhs_rewrite_value->inst_id.index < rhs_subst_inst_id.index
  574. ? lhs_rewrite_value->inst_id
  575. : rhs_subst_inst_id;
  576. auto source_order2 =
  577. lhs_rewrite_value->inst_id.index >= rhs_subst_inst_id.index
  578. ? lhs_rewrite_value->inst_id
  579. : rhs_subst_inst_id;
  580. // TODO: It would be nice to note the places where the values are
  581. // assigned but rewrite constraint instructions are from canonical
  582. // constant values, and have no locations. We'd need to store a
  583. // location along with them in the rewrite constraints.
  584. context.emitter().Emit(loc_id, AssociatedConstantWithDifferentValues,
  585. constraint.lhs_id, source_order1, source_order2);
  586. }
  587. return false;
  588. }
  589. rewrite_values.SetFullyRewritten(context, *lhs_rewrite_value,
  590. rhs_subst_inst_id);
  591. }
  592. // Rebuild the `rewrites` vector with resolved values for the RHS. Drop any
  593. // duplicate rewrites in the `rewrites` vector by walking through the
  594. // `rewrite_values` map and dropping the computed RHS value for each LHS the
  595. // first time we see it, and erasing the constraint from the vector if we see
  596. // the same LHS again.
  597. size_t keep_size = rewrites.size();
  598. for (size_t i = 0; i < keep_size;) {
  599. auto& constraint = rewrites[i];
  600. auto lhs_access =
  601. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(constraint.lhs_id);
  602. if (!lhs_access) {
  603. ++i;
  604. continue;
  605. }
  606. auto& rewrite_value = *rewrite_values.FindRef(context, *lhs_access);
  607. auto rhs_id = std::exchange(rewrite_value.inst_id, SemIR::InstId::None);
  608. if (rhs_id == SemIR::InstId::None) {
  609. std::swap(rewrites[i], rewrites[keep_size - 1]);
  610. --keep_size;
  611. } else {
  612. rewrites[i].rhs_id = rhs_id;
  613. ++i;
  614. }
  615. }
  616. rewrites.erase(rewrites.begin() + keep_size, rewrites.end());
  617. return true;
  618. }
  619. } // namespace Carbon::Check