subst.cpp 21 KB

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