subst.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. .builtin_constraint_mask =
  221. old_facet_type_info.builtin_constraint_mask,
  222. .other_requirements = old_facet_type_info.other_requirements};
  223. // Since these were added to a stack, we get them back in reverse order.
  224. new_facet_type_info.rewrite_constraints.resize(
  225. old_facet_type_info.rewrite_constraints.size(),
  226. SemIR::FacetTypeInfo::RewriteConstraint::None);
  227. for (auto& new_constraint :
  228. llvm::reverse(new_facet_type_info.rewrite_constraints)) {
  229. auto rhs_id = worklist.Pop();
  230. auto lhs_id = worklist.Pop();
  231. new_constraint = {.lhs_id = lhs_id, .rhs_id = rhs_id};
  232. }
  233. new_facet_type_info.self_impls_named_constraints.resize(
  234. old_facet_type_info.self_impls_named_constraints.size(),
  235. SemIR::SpecificNamedConstraint::None);
  236. for (auto [old_constraint, new_constraint] :
  237. llvm::reverse(llvm::zip_equal(
  238. old_facet_type_info.self_impls_named_constraints,
  239. new_facet_type_info.self_impls_named_constraints))) {
  240. new_constraint = {
  241. .named_constraint_id = old_constraint.named_constraint_id,
  242. .specific_id = pop_specific(old_constraint.specific_id)};
  243. }
  244. new_facet_type_info.extend_named_constraints.resize(
  245. old_facet_type_info.extend_named_constraints.size(),
  246. SemIR::SpecificNamedConstraint::None);
  247. for (auto [old_constraint, new_constraint] : llvm::reverse(
  248. llvm::zip_equal(old_facet_type_info.extend_named_constraints,
  249. new_facet_type_info.extend_named_constraints))) {
  250. new_constraint = {
  251. .named_constraint_id = old_constraint.named_constraint_id,
  252. .specific_id = pop_specific(old_constraint.specific_id)};
  253. }
  254. new_facet_type_info.self_impls_constraints.resize(
  255. old_facet_type_info.self_impls_constraints.size(),
  256. SemIR::SpecificInterface::None);
  257. for (auto [old_constraint, new_constraint] : llvm::reverse(
  258. llvm::zip_equal(old_facet_type_info.self_impls_constraints,
  259. new_facet_type_info.self_impls_constraints))) {
  260. new_constraint = {
  261. .interface_id = old_constraint.interface_id,
  262. .specific_id = pop_specific(old_constraint.specific_id)};
  263. }
  264. new_facet_type_info.extend_constraints.resize(
  265. old_facet_type_info.extend_constraints.size(),
  266. SemIR::SpecificInterface::None);
  267. for (auto [old_constraint, new_constraint] : llvm::reverse(
  268. llvm::zip_equal(old_facet_type_info.extend_constraints,
  269. new_facet_type_info.extend_constraints))) {
  270. new_constraint = {
  271. .interface_id = old_constraint.interface_id,
  272. .specific_id = pop_specific(old_constraint.specific_id)};
  273. }
  274. new_facet_type_info.Canonicalize();
  275. return context.facet_types().Add(new_facet_type_info).index;
  276. }
  277. default:
  278. return arg.value();
  279. }
  280. }
  281. // Pops the operands of the specified instruction off the worklist and rebuilds
  282. // the instruction with the updated operands if it has changed.
  283. static auto Rebuild(Context& context, Worklist& worklist, SemIR::InstId inst_id,
  284. SubstInstCallbacks& callbacks) -> SemIR::InstId {
  285. auto inst = context.insts().Get(inst_id);
  286. // Note that we pop in reverse order because we pushed them in forwards order.
  287. int32_t arg1 = PopOperand(context, worklist, inst.arg1_and_kind());
  288. int32_t arg0 = PopOperand(context, worklist, inst.arg0_and_kind());
  289. auto type_id = inst.type_id().has_value()
  290. ? callbacks.RebuildType(
  291. context.types().GetAsTypeInstId(worklist.Pop()))
  292. : SemIR::TypeId::None;
  293. if (type_id == inst.type_id() && arg0 == inst.arg0() && arg1 == inst.arg1()) {
  294. return callbacks.ReuseUnchanged(inst_id);
  295. }
  296. // TODO: Do we need to require this type to be complete?
  297. inst.SetType(type_id);
  298. inst.SetArgs(arg0, arg1);
  299. return callbacks.Rebuild(inst_id, inst);
  300. }
  301. auto SubstInst(Context& context, SemIR::InstId inst_id,
  302. SubstInstCallbacks& callbacks) -> SemIR::InstId {
  303. Worklist worklist(inst_id);
  304. // For each instruction that forms part of the constant, we will visit it
  305. // twice:
  306. //
  307. // - First, we visit it with `is_expanded == false`, we add all of its
  308. // operands onto the worklist, and process them by following this same
  309. // process.
  310. // - Then, once all operands are processed, we visit the instruction with
  311. // `is_expanded == true`, pop the operands back off the worklist, and if any
  312. // of them changed, rebuild this instruction.
  313. //
  314. // The second step is skipped if we can detect in the first step that the
  315. // instruction will not need to be rebuilt.
  316. int index = 0;
  317. while (index != -1) {
  318. auto& item = worklist[index];
  319. if (item.is_expanded) {
  320. // Rebuild this item if necessary. Note that this might pop items from the
  321. // worklist but does not reallocate, so does not invalidate `item`.
  322. auto old_inst_id = std::exchange(
  323. item.inst_id, Rebuild(context, worklist, item.inst_id, callbacks));
  324. if (item.is_repeated && old_inst_id != item.inst_id) {
  325. // SubstOperandsAndRetry was returned for the item, and the instruction
  326. // was rebuilt from new operands, so go through Subst() again. Note that
  327. // we've already called Rebuild so we don't want to leave this item as
  328. // repeated, and call back to ReuseUnchanged for it again later unless
  329. // the next call to Subst() asks for that.
  330. item.is_expanded = false;
  331. item.is_repeated = false;
  332. } else {
  333. index = item.next_index;
  334. continue;
  335. }
  336. }
  337. if (item.is_repeated) {
  338. // SubstAgain was returned for the item, and the result of that Subst() is
  339. // at the back of the worklist, which we pop. Note that popping from the
  340. // worklist does not reallocate, so does not invalidate `item`.
  341. //
  342. // When Subst returns SubstAgain, we must call back to Rebuild or
  343. // ReuseUnchanged for that work item.
  344. item.inst_id = callbacks.ReuseUnchanged(worklist.Pop());
  345. index = item.next_index;
  346. continue;
  347. }
  348. switch (callbacks.Subst(item.inst_id)) {
  349. case SubstInstCallbacks::SubstResult::FullySubstituted:
  350. // If any instruction is an ErrorInst, combining it into another
  351. // instruction will also produce an ErrorInst, so shortcut out here to
  352. // save wasted work.
  353. if (item.inst_id == SemIR::ErrorInst::InstId) {
  354. return SemIR::ErrorInst::InstId;
  355. }
  356. index = item.next_index;
  357. continue;
  358. case SubstInstCallbacks::SubstResult::SubstAgain: {
  359. item.is_repeated = true;
  360. // This modifies `worklist` which invalidates `item`.
  361. worklist.Push(item.inst_id);
  362. worklist.back().next_index = index;
  363. index = worklist.size() - 1;
  364. continue;
  365. }
  366. case SubstInstCallbacks::SubstResult::SubstOperands:
  367. break;
  368. case SubstInstCallbacks::SubstResult::SubstOperandsAndRetry:
  369. item.is_repeated = true;
  370. break;
  371. }
  372. // Extract the operands of this item into the worklist. Note that this
  373. // modifies the worklist, so it's not safe to use `item` after
  374. // `ExpandOperands` returns.
  375. item.is_expanded = true;
  376. int first_operand = worklist.size();
  377. int next_index = item.next_index;
  378. ExpandOperands(context, worklist, item.inst_id);
  379. // If there are any operands, go and update them before rebuilding this
  380. // item.
  381. if (worklist.size() > first_operand) {
  382. worklist.back().next_index = index;
  383. index = first_operand;
  384. } else {
  385. // No need to rebuild this instruction: its operands can't be changed by
  386. // substitution because it has none.
  387. item.inst_id = callbacks.ReuseUnchanged(item.inst_id);
  388. index = next_index;
  389. }
  390. }
  391. CARBON_CHECK(worklist.size() == 1,
  392. "Unexpected data left behind in work list");
  393. return worklist.back().inst_id;
  394. }
  395. auto SubstInst(Context& context, SemIR::TypeInstId inst_id,
  396. SubstInstCallbacks& callbacks) -> SemIR::TypeInstId {
  397. return context.types().GetAsTypeInstId(
  398. SubstInst(context, static_cast<SemIR::InstId>(inst_id), callbacks));
  399. }
  400. namespace {
  401. // Callbacks for performing substitution of a set of Substitutions into a
  402. // symbolic constant.
  403. class SubstConstantCallbacks final : public SubstInstCallbacks {
  404. public:
  405. // `context` must not be null.
  406. SubstConstantCallbacks(Context* context, SemIR::LocId loc_id,
  407. Substitutions substitutions)
  408. : SubstInstCallbacks(context),
  409. loc_id_(loc_id),
  410. substitutions_(substitutions) {}
  411. // Applies the given Substitutions to an instruction, in order to replace
  412. // SymbolicBinding instructions with the value of the binding.
  413. auto Subst(SemIR::InstId& inst_id) -> SubstResult override {
  414. if (context().constant_values().Get(inst_id).is_concrete()) {
  415. // This instruction is a concrete constant, so can't contain any
  416. // bindings that need to be substituted.
  417. return SubstResult::FullySubstituted;
  418. }
  419. // A symbolic binding `as type` contains the EntityNameId of that symbolic
  420. // binding. If it matches a substitution, then we want to point the
  421. // EntityNameId to the substitution facet value.
  422. if (auto bind =
  423. context().insts().TryGetAs<SemIR::SymbolicBindingType>(inst_id)) {
  424. auto& entity_name = context().entity_names().Get(bind->entity_name_id);
  425. for (auto [bind_index, replacement_id] : substitutions_) {
  426. if (entity_name.bind_index() == bind_index) {
  427. auto replacement_inst_id =
  428. context().constant_values().GetInstId(replacement_id);
  429. inst_id = RebuildNewInst<SemIR::FacetAccessType>(
  430. loc_id_, {
  431. .type_id = SemIR::TypeType::TypeId,
  432. .facet_value_inst_id = replacement_inst_id,
  433. });
  434. return SubstResult::FullySubstituted;
  435. }
  436. }
  437. }
  438. auto entity_name_id = SemIR::EntityNameId::None;
  439. if (auto bind =
  440. context().insts().TryGetAs<SemIR::SymbolicBinding>(inst_id)) {
  441. entity_name_id = bind->entity_name_id;
  442. } else if (auto bind =
  443. context().insts().TryGetAs<SemIR::SymbolicBindingPattern>(
  444. inst_id)) {
  445. entity_name_id = bind->entity_name_id;
  446. } else {
  447. return SubstResult::SubstOperands;
  448. }
  449. auto& entity_name = context().entity_names().Get(entity_name_id);
  450. // This is a symbolic binding. Check if we're substituting it.
  451. // TODO: Consider building a hash map for substitutions. We might have a
  452. // lot of them.
  453. for (auto [bind_index, replacement_id] : substitutions_) {
  454. if (entity_name.bind_index() == bind_index) {
  455. // This is the binding we're replacing. Perform substitution.
  456. inst_id = context().constant_values().GetInstId(replacement_id);
  457. return SubstResult::FullySubstituted;
  458. }
  459. }
  460. // If it's not being substituted, we still need to look through it, as we
  461. // may need to substitute into its type (a `FacetType`, with one or more
  462. // `SpecificInterfaces` within).
  463. return SubstResult::SubstOperands;
  464. }
  465. // Rebuilds an instruction by building a new constant.
  466. auto Rebuild(SemIR::InstId /*old_inst_id*/, SemIR::Inst new_inst)
  467. -> SemIR::InstId override {
  468. return RebuildNewInst(loc_id_, new_inst);
  469. }
  470. private:
  471. SemIR::LocId loc_id_;
  472. Substitutions substitutions_;
  473. };
  474. } // namespace
  475. auto SubstConstant(Context& context, SemIR::LocId loc_id,
  476. SemIR::ConstantId const_id, Substitutions substitutions)
  477. -> SemIR::ConstantId {
  478. CARBON_CHECK(const_id.is_constant(), "Substituting into non-constant");
  479. if (substitutions.empty()) {
  480. // Nothing to substitute.
  481. return const_id;
  482. }
  483. if (!const_id.is_symbolic()) {
  484. // A concrete constant can't contain a reference to a symbolic binding.
  485. return const_id;
  486. }
  487. auto callbacks = SubstConstantCallbacks(&context, loc_id, substitutions);
  488. auto subst_inst_id = SubstInst(
  489. context, context.constant_values().GetInstId(const_id), callbacks);
  490. return context.constant_values().Get(subst_inst_id);
  491. }
  492. } // namespace Carbon::Check