subst.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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/subst.h"
  5. #include "toolchain/base/kind_switch.h"
  6. #include "toolchain/check/eval.h"
  7. #include "toolchain/check/generic.h"
  8. #include "toolchain/check/inst.h"
  9. #include "toolchain/sem_ir/copy_on_write_block.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. #include "toolchain/sem_ir/inst.h"
  12. #include "toolchain/sem_ir/typed_insts.h"
  13. namespace Carbon::Check {
  14. auto SubstInstCallbacks::RebuildType(SemIR::TypeInstId type_inst_id) const
  15. -> SemIR::TypeId {
  16. return context().types().GetTypeIdForTypeInstId(type_inst_id);
  17. }
  18. auto SubstInstCallbacks::RebuildNewInst(SemIR::LocId loc_id,
  19. SemIR::Inst new_inst) const
  20. -> SemIR::InstId {
  21. auto const_id = EvalOrAddInst(
  22. context(), SemIR::LocIdAndInst::UncheckedLoc(loc_id, new_inst));
  23. CARBON_CHECK(const_id.has_value(),
  24. "Substitution into constant produced non-constant");
  25. CARBON_CHECK(const_id.is_constant(),
  26. "Substitution into constant produced runtime value");
  27. return context().constant_values().GetInstId(const_id);
  28. }
  29. namespace {
  30. // Information about an instruction that we are substituting into.
  31. struct WorklistItem {
  32. // The instruction that we are substituting into.
  33. SemIR::InstId inst_id;
  34. // Whether the operands of this instruction have been added to the worklist.
  35. bool is_expanded : 1;
  36. // Whether the instruction was subst'd and re-added to the worklist.
  37. bool is_repeated : 1;
  38. // The index of the worklist item to process after we finish updating this
  39. // one. For the final child of an instruction, this is the parent. For any
  40. // other child, this is the index of the next child of the parent. For the
  41. // root, this is -1.
  42. int next_index : 31;
  43. };
  44. // A list of instructions that we're currently in the process of substituting
  45. // into. For details of the algorithm used here, see `SubstConstant`.
  46. class Worklist {
  47. public:
  48. explicit Worklist(SemIR::InstId root_id) {
  49. worklist_.push_back({.inst_id = root_id,
  50. .is_expanded = false,
  51. .is_repeated = false,
  52. .next_index = -1});
  53. }
  54. auto operator[](int index) -> WorklistItem& { return worklist_[index]; }
  55. auto size() -> int { return worklist_.size(); }
  56. auto back() -> WorklistItem& { return worklist_.back(); }
  57. auto Push(SemIR::InstId inst_id) -> void {
  58. CARBON_CHECK(inst_id.has_value());
  59. worklist_.push_back({.inst_id = inst_id,
  60. .is_expanded = false,
  61. .is_repeated = false,
  62. .next_index = static_cast<int>(worklist_.size() + 1)});
  63. CARBON_CHECK(worklist_.back().next_index > 0, "Constant too large.");
  64. }
  65. auto Pop() -> SemIR::InstId { return worklist_.pop_back_val().inst_id; }
  66. private:
  67. // Constants can get pretty large, so use a large worklist. This should be
  68. // about 4KiB, which should be small enough to comfortably fit on the stack,
  69. // but large enough that it's unlikely that we'll need a heap allocation.
  70. llvm::SmallVector<WorklistItem, 512> worklist_;
  71. };
  72. } // namespace
  73. // Pushes the specified operand onto the worklist.
  74. static auto PushOperand(Context& context, Worklist& worklist,
  75. SemIR::Inst::ArgAndKind arg) -> void {
  76. auto push_block = [&](SemIR::InstBlockId block_id) {
  77. for (auto inst_id :
  78. context.inst_blocks().Get(SemIR::InstBlockId(block_id))) {
  79. worklist.Push(inst_id);
  80. }
  81. };
  82. auto push_specific = [&](SemIR::SpecificId specific_id) {
  83. if (specific_id.has_value()) {
  84. push_block(context.specifics().Get(specific_id).args_id);
  85. }
  86. };
  87. CARBON_KIND_SWITCH(arg) {
  88. case CARBON_KIND(SemIR::InstId inst_id): {
  89. if (inst_id.has_value()) {
  90. worklist.Push(inst_id);
  91. }
  92. break;
  93. }
  94. case CARBON_KIND(SemIR::TypeInstId inst_id): {
  95. if (inst_id.has_value()) {
  96. worklist.Push(inst_id);
  97. }
  98. break;
  99. }
  100. case CARBON_KIND(SemIR::InstBlockId inst_block_id): {
  101. push_block(inst_block_id);
  102. break;
  103. }
  104. case CARBON_KIND(SemIR::StructTypeFieldsId fields_id): {
  105. for (auto field : context.struct_type_fields().Get(fields_id)) {
  106. worklist.Push(field.type_inst_id);
  107. }
  108. break;
  109. }
  110. case CARBON_KIND(SemIR::SpecificId specific_id): {
  111. push_specific(specific_id);
  112. break;
  113. }
  114. case CARBON_KIND(SemIR::SpecificInterfaceId interface_id): {
  115. auto interface = context.specific_interfaces().Get(interface_id);
  116. push_specific(interface.specific_id);
  117. break;
  118. }
  119. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  120. const auto& facet_type_info = context.facet_types().Get(facet_type_id);
  121. for (auto interface : facet_type_info.extend_constraints) {
  122. push_specific(interface.specific_id);
  123. }
  124. for (auto interface : facet_type_info.self_impls_constraints) {
  125. push_specific(interface.specific_id);
  126. }
  127. for (auto interface : facet_type_info.extend_named_constraints) {
  128. push_specific(interface.specific_id);
  129. }
  130. for (auto interface : facet_type_info.self_impls_named_constraints) {
  131. push_specific(interface.specific_id);
  132. }
  133. for (auto rewrite : facet_type_info.rewrite_constraints) {
  134. worklist.Push(rewrite.lhs_id);
  135. worklist.Push(rewrite.rhs_id);
  136. }
  137. // TODO: Process other requirements as well.
  138. break;
  139. }
  140. default:
  141. break;
  142. }
  143. }
  144. // Converts the operands of this instruction into `InstId`s and pushes them onto
  145. // the worklist.
  146. static auto ExpandOperands(Context& context, Worklist& worklist,
  147. SemIR::InstId inst_id) -> void {
  148. auto inst = context.insts().Get(inst_id);
  149. if (inst.type_id().has_value()) {
  150. worklist.Push(context.types().GetInstId(inst.type_id()));
  151. }
  152. PushOperand(context, worklist, inst.arg0_and_kind());
  153. PushOperand(context, worklist, inst.arg1_and_kind());
  154. }
  155. // Pops the specified operand from the worklist and returns it.
  156. static auto PopOperand(Context& context, Worklist& worklist,
  157. SemIR::Inst::ArgAndKind arg) -> int32_t {
  158. auto pop_block_id = [&](SemIR::InstBlockId old_inst_block_id) {
  159. auto size = context.inst_blocks().Get(old_inst_block_id).size();
  160. SemIR::CopyOnWriteInstBlock new_inst_block(&context.sem_ir(),
  161. old_inst_block_id);
  162. for (auto i : llvm::reverse(llvm::seq(size))) {
  163. new_inst_block.Set(i, worklist.Pop());
  164. }
  165. return new_inst_block.GetCanonical();
  166. };
  167. auto pop_specific = [&](SemIR::SpecificId specific_id) {
  168. if (!specific_id.has_value()) {
  169. return specific_id;
  170. }
  171. auto& specific = context.specifics().Get(specific_id);
  172. auto args_id = pop_block_id(specific.args_id);
  173. return context.specifics().GetOrAdd(specific.generic_id, args_id);
  174. };
  175. CARBON_KIND_SWITCH(arg) {
  176. case CARBON_KIND(SemIR::InstId inst_id): {
  177. if (!inst_id.has_value()) {
  178. return arg.value();
  179. }
  180. return worklist.Pop().index;
  181. }
  182. case CARBON_KIND(SemIR::TypeInstId inst_id): {
  183. if (!inst_id.has_value()) {
  184. return arg.value();
  185. }
  186. return worklist.Pop().index;
  187. }
  188. case CARBON_KIND(SemIR::InstBlockId inst_block_id): {
  189. return pop_block_id(inst_block_id).index;
  190. }
  191. case CARBON_KIND(SemIR::StructTypeFieldsId old_fields_id): {
  192. auto old_fields = context.struct_type_fields().Get(old_fields_id);
  193. SemIR::CopyOnWriteStructTypeFieldsBlock new_fields(&context.sem_ir(),
  194. old_fields_id);
  195. for (auto i : llvm::reverse(llvm::seq(old_fields.size()))) {
  196. new_fields.Set(
  197. i,
  198. {.name_id = old_fields[i].name_id,
  199. .type_inst_id = context.types().GetAsTypeInstId(worklist.Pop())});
  200. }
  201. return new_fields.GetCanonical().index;
  202. }
  203. case CARBON_KIND(SemIR::SpecificId specific_id): {
  204. return pop_specific(specific_id).index;
  205. }
  206. case CARBON_KIND(SemIR::SpecificInterfaceId interface_id): {
  207. auto interface = context.specific_interfaces().Get(interface_id);
  208. auto specific_id = pop_specific(interface.specific_id);
  209. return context.specific_interfaces()
  210. .Add({
  211. .interface_id = interface.interface_id,
  212. .specific_id = specific_id,
  213. })
  214. .index;
  215. }
  216. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  217. const auto& old_facet_type_info =
  218. context.facet_types().Get(facet_type_id);
  219. SemIR::FacetTypeInfo new_facet_type_info = {
  220. .other_requirements = old_facet_type_info.other_requirements};
  221. // Since these were added to a stack, we get them back in reverse order.
  222. new_facet_type_info.rewrite_constraints.resize(
  223. old_facet_type_info.rewrite_constraints.size(),
  224. SemIR::FacetTypeInfo::RewriteConstraint::None);
  225. for (auto& new_constraint :
  226. llvm::reverse(new_facet_type_info.rewrite_constraints)) {
  227. auto rhs_id = worklist.Pop();
  228. auto lhs_id = worklist.Pop();
  229. new_constraint = {.lhs_id = lhs_id, .rhs_id = rhs_id};
  230. }
  231. new_facet_type_info.self_impls_named_constraints.resize(
  232. old_facet_type_info.self_impls_named_constraints.size(),
  233. SemIR::SpecificNamedConstraint::None);
  234. for (auto [old_constraint, new_constraint] :
  235. llvm::reverse(llvm::zip_equal(
  236. old_facet_type_info.self_impls_named_constraints,
  237. new_facet_type_info.self_impls_named_constraints))) {
  238. new_constraint = {
  239. .named_constraint_id = old_constraint.named_constraint_id,
  240. .specific_id = pop_specific(old_constraint.specific_id)};
  241. }
  242. new_facet_type_info.extend_named_constraints.resize(
  243. old_facet_type_info.extend_named_constraints.size(),
  244. SemIR::SpecificNamedConstraint::None);
  245. for (auto [old_constraint, new_constraint] : llvm::reverse(
  246. llvm::zip_equal(old_facet_type_info.extend_named_constraints,
  247. new_facet_type_info.extend_named_constraints))) {
  248. new_constraint = {
  249. .named_constraint_id = old_constraint.named_constraint_id,
  250. .specific_id = pop_specific(old_constraint.specific_id)};
  251. }
  252. new_facet_type_info.self_impls_constraints.resize(
  253. old_facet_type_info.self_impls_constraints.size(),
  254. SemIR::SpecificInterface::None);
  255. for (auto [old_constraint, new_constraint] : llvm::reverse(
  256. llvm::zip_equal(old_facet_type_info.self_impls_constraints,
  257. new_facet_type_info.self_impls_constraints))) {
  258. new_constraint = {
  259. .interface_id = old_constraint.interface_id,
  260. .specific_id = pop_specific(old_constraint.specific_id)};
  261. }
  262. new_facet_type_info.extend_constraints.resize(
  263. old_facet_type_info.extend_constraints.size(),
  264. SemIR::SpecificInterface::None);
  265. for (auto [old_constraint, new_constraint] : llvm::reverse(
  266. llvm::zip_equal(old_facet_type_info.extend_constraints,
  267. new_facet_type_info.extend_constraints))) {
  268. new_constraint = {
  269. .interface_id = old_constraint.interface_id,
  270. .specific_id = pop_specific(old_constraint.specific_id)};
  271. }
  272. new_facet_type_info.Canonicalize();
  273. return context.facet_types().Add(new_facet_type_info).index;
  274. }
  275. default:
  276. return arg.value();
  277. }
  278. }
  279. // Pops the operands of the specified instruction off the worklist and rebuilds
  280. // the instruction with the updated operands if it has changed.
  281. static auto Rebuild(Context& context, Worklist& worklist, SemIR::InstId inst_id,
  282. SubstInstCallbacks& callbacks) -> SemIR::InstId {
  283. auto inst = context.insts().Get(inst_id);
  284. // Note that we pop in reverse order because we pushed them in forwards order.
  285. int32_t arg1 = PopOperand(context, worklist, inst.arg1_and_kind());
  286. int32_t arg0 = PopOperand(context, worklist, inst.arg0_and_kind());
  287. auto type_id = inst.type_id().has_value()
  288. ? callbacks.RebuildType(
  289. context.types().GetAsTypeInstId(worklist.Pop()))
  290. : SemIR::TypeId::None;
  291. if (type_id == inst.type_id() && arg0 == inst.arg0() && arg1 == inst.arg1()) {
  292. return callbacks.ReuseUnchanged(inst_id);
  293. }
  294. // TODO: Do we need to require this type to be complete?
  295. inst.SetType(type_id);
  296. inst.SetArgs(arg0, arg1);
  297. return callbacks.Rebuild(inst_id, inst);
  298. }
  299. auto SubstInst(Context& context, SemIR::InstId inst_id,
  300. SubstInstCallbacks& callbacks) -> SemIR::InstId {
  301. Worklist worklist(inst_id);
  302. // For each instruction that forms part of the constant, we will visit it
  303. // twice:
  304. //
  305. // - First, we visit it with `is_expanded == false`, we add all of its
  306. // operands onto the worklist, and process them by following this same
  307. // process.
  308. // - Then, once all operands are processed, we visit the instruction with
  309. // `is_expanded == true`, pop the operands back off the worklist, and if any
  310. // of them changed, rebuild this instruction.
  311. //
  312. // The second step is skipped if we can detect in the first step that the
  313. // instruction will not need to be rebuilt.
  314. int index = 0;
  315. while (index != -1) {
  316. auto& item = worklist[index];
  317. if (item.is_expanded) {
  318. // Rebuild this item if necessary. Note that this might pop items from the
  319. // worklist but does not reallocate, so does not invalidate `item`.
  320. auto old_inst_id = std::exchange(
  321. item.inst_id, Rebuild(context, worklist, item.inst_id, callbacks));
  322. if (item.is_repeated && old_inst_id != item.inst_id) {
  323. // SubstOperandsAndRetry was returned for the item, and the instruction
  324. // was rebuilt from new operands, so go through Subst() again. Note that
  325. // we've already called Rebuild so we don't want to leave this item as
  326. // repeated, and call back to ReuseUnchanged for it again later unless
  327. // the next call to Subst() asks for that.
  328. item.is_expanded = false;
  329. item.is_repeated = false;
  330. } else {
  331. index = item.next_index;
  332. continue;
  333. }
  334. }
  335. if (item.is_repeated) {
  336. // SubstAgain was returned for the item, and the result of that Subst() is
  337. // at the back of the worklist, which we pop. Note that popping from the
  338. // worklist does not reallocate, so does not invalidate `item`.
  339. //
  340. // When Subst returns SubstAgain, we must call back to Rebuild or
  341. // ReuseUnchanged for that work item.
  342. item.inst_id = callbacks.ReuseUnchanged(worklist.Pop());
  343. index = item.next_index;
  344. continue;
  345. }
  346. switch (callbacks.Subst(item.inst_id)) {
  347. case SubstInstCallbacks::SubstResult::FullySubstituted:
  348. // If any instruction is an ErrorInst, combining it into another
  349. // instruction will also produce an ErrorInst, so shortcut out here to
  350. // save wasted work.
  351. if (item.inst_id == SemIR::ErrorInst::InstId) {
  352. return SemIR::ErrorInst::InstId;
  353. }
  354. index = item.next_index;
  355. continue;
  356. case SubstInstCallbacks::SubstResult::SubstAgain: {
  357. item.is_repeated = true;
  358. // This modifies `worklist` which invalidates `item`.
  359. worklist.Push(item.inst_id);
  360. worklist.back().next_index = index;
  361. index = worklist.size() - 1;
  362. continue;
  363. }
  364. case SubstInstCallbacks::SubstResult::SubstOperands:
  365. break;
  366. case SubstInstCallbacks::SubstResult::SubstOperandsAndRetry:
  367. item.is_repeated = true;
  368. break;
  369. }
  370. // Extract the operands of this item into the worklist. Note that this
  371. // modifies the worklist, so it's not safe to use `item` after
  372. // `ExpandOperands` returns.
  373. item.is_expanded = true;
  374. int first_operand = worklist.size();
  375. int next_index = item.next_index;
  376. ExpandOperands(context, worklist, item.inst_id);
  377. // If there are any operands, go and update them before rebuilding this
  378. // item.
  379. if (worklist.size() > first_operand) {
  380. worklist.back().next_index = index;
  381. index = first_operand;
  382. } else {
  383. // No need to rebuild this instruction: its operands can't be changed by
  384. // substitution because it has none.
  385. item.inst_id = callbacks.ReuseUnchanged(item.inst_id);
  386. index = next_index;
  387. }
  388. }
  389. CARBON_CHECK(worklist.size() == 1,
  390. "Unexpected data left behind in work list");
  391. return worklist.back().inst_id;
  392. }
  393. auto SubstInst(Context& context, SemIR::TypeInstId inst_id,
  394. SubstInstCallbacks& callbacks) -> SemIR::TypeInstId {
  395. return context.types().GetAsTypeInstId(
  396. SubstInst(context, static_cast<SemIR::InstId>(inst_id), callbacks));
  397. }
  398. namespace {
  399. // Callbacks for performing substitution of a set of Substitutions into a
  400. // symbolic constant.
  401. class SubstConstantCallbacks final : public SubstInstCallbacks {
  402. public:
  403. // `context` must not be null.
  404. SubstConstantCallbacks(Context* context, SemIR::LocId loc_id,
  405. Substitutions substitutions)
  406. : SubstInstCallbacks(context),
  407. loc_id_(loc_id),
  408. substitutions_(substitutions) {}
  409. // Applies the given Substitutions to an instruction, in order to replace
  410. // SymbolicBinding instructions with the value of the binding.
  411. auto Subst(SemIR::InstId& inst_id) -> SubstResult override {
  412. if (context().constant_values().Get(inst_id).is_concrete()) {
  413. // This instruction is a concrete constant, so can't contain any
  414. // bindings that need to be substituted.
  415. return SubstResult::FullySubstituted;
  416. }
  417. // A symbolic binding `as type` contains the EntityNameId of that symbolic
  418. // binding. If it matches a substitution, then we want to point the
  419. // EntityNameId to the substitution facet value.
  420. if (auto bind =
  421. context().insts().TryGetAs<SemIR::SymbolicBindingType>(inst_id)) {
  422. auto& entity_name = context().entity_names().Get(bind->entity_name_id);
  423. for (auto [bind_index, replacement_id] : substitutions_) {
  424. if (entity_name.bind_index() == bind_index) {
  425. auto replacement_inst_id =
  426. context().constant_values().GetInstId(replacement_id);
  427. inst_id = RebuildNewInst<SemIR::FacetAccessType>(
  428. loc_id_, {
  429. .type_id = SemIR::TypeType::TypeId,
  430. .facet_value_inst_id = replacement_inst_id,
  431. });
  432. return SubstResult::FullySubstituted;
  433. }
  434. }
  435. }
  436. auto entity_name_id = SemIR::EntityNameId::None;
  437. if (auto bind =
  438. context().insts().TryGetAs<SemIR::SymbolicBinding>(inst_id)) {
  439. entity_name_id = bind->entity_name_id;
  440. } else if (auto bind =
  441. context().insts().TryGetAs<SemIR::SymbolicBindingPattern>(
  442. inst_id)) {
  443. entity_name_id = bind->entity_name_id;
  444. } else {
  445. return SubstResult::SubstOperands;
  446. }
  447. auto& entity_name = context().entity_names().Get(entity_name_id);
  448. // This is a symbolic binding. Check if we're substituting it.
  449. // TODO: Consider building a hash map for substitutions. We might have a
  450. // lot of them.
  451. for (auto [bind_index, replacement_id] : substitutions_) {
  452. if (entity_name.bind_index() == bind_index) {
  453. // This is the binding we're replacing. Perform substitution.
  454. inst_id = context().constant_values().GetInstId(replacement_id);
  455. return SubstResult::FullySubstituted;
  456. }
  457. }
  458. // If it's not being substituted, we still need to look through it, as we
  459. // may need to substitute into its type (a `FacetType`, with one or more
  460. // `SpecificInterfaces` within).
  461. return SubstResult::SubstOperands;
  462. }
  463. // Rebuilds an instruction by building a new constant.
  464. auto Rebuild(SemIR::InstId /*old_inst_id*/, SemIR::Inst new_inst)
  465. -> SemIR::InstId override {
  466. return RebuildNewInst(loc_id_, new_inst);
  467. }
  468. private:
  469. SemIR::LocId loc_id_;
  470. Substitutions substitutions_;
  471. };
  472. } // namespace
  473. auto SubstConstant(Context& context, SemIR::LocId loc_id,
  474. SemIR::ConstantId const_id, Substitutions substitutions)
  475. -> SemIR::ConstantId {
  476. CARBON_CHECK(const_id.is_constant(), "Substituting into non-constant");
  477. if (substitutions.empty()) {
  478. // Nothing to substitute.
  479. return const_id;
  480. }
  481. if (!const_id.is_symbolic()) {
  482. // A concrete constant can't contain a reference to a symbolic binding.
  483. return const_id;
  484. }
  485. auto callbacks = SubstConstantCallbacks(&context, loc_id, substitutions);
  486. auto subst_inst_id = SubstInst(
  487. context, context.constant_values().GetInstId(const_id), callbacks);
  488. return context.constant_values().Get(subst_inst_id);
  489. }
  490. } // namespace Carbon::Check