pattern_match.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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/pattern_match.h"
  5. #include <functional>
  6. #include <vector>
  7. #include "llvm/ADT/STLExtras.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "toolchain/base/kind_switch.h"
  10. #include "toolchain/check/context.h"
  11. #include "toolchain/check/convert.h"
  12. #include "toolchain/check/subpattern.h"
  13. #include "toolchain/check/type.h"
  14. #include "toolchain/diagnostics/format_providers.h"
  15. namespace Carbon::Check {
  16. // Returns a best-effort name for the given ParamPattern, suitable for use in
  17. // IR pretty-printing.
  18. template <typename ParamPattern>
  19. static auto GetPrettyName(Context& context, ParamPattern param_pattern)
  20. -> SemIR::NameId {
  21. if (context.insts().Is<SemIR::ReturnSlotPattern>(
  22. param_pattern.subpattern_id)) {
  23. return SemIR::NameId::ReturnSlot;
  24. }
  25. if (auto binding_pattern = context.insts().TryGetAs<SemIR::AnyBindingPattern>(
  26. param_pattern.subpattern_id)) {
  27. return context.entity_names().Get(binding_pattern->entity_name_id).name_id;
  28. }
  29. return SemIR::NameId::None;
  30. }
  31. namespace {
  32. // Selects between the different kinds of pattern matching.
  33. enum class MatchKind : uint8_t {
  34. // Caller pattern matching occurs on the caller side of a function call, and
  35. // is responsible for matching the argument expression against the portion
  36. // of the pattern above the ParamPattern insts.
  37. Caller,
  38. // Callee pattern matching occurs in the function decl block, and is
  39. // responsible for matching the function's calling-convention parameters
  40. // against the portion of the pattern below the ParamPattern insts.
  41. Callee,
  42. // Local pattern matching is pattern matching outside of a function call,
  43. // such as in a let/var declaration.
  44. Local,
  45. };
  46. // The collected state of a pattern-matching operation.
  47. class MatchContext {
  48. public:
  49. struct WorkItem {
  50. SemIR::InstId pattern_id;
  51. // `None` when processing the callee side.
  52. SemIR::InstId scrutinee_id;
  53. };
  54. // Constructs a MatchContext. If `callee_specific_id` is not `None`, this
  55. // pattern match operation is part of implementing the signature of the given
  56. // specific.
  57. explicit MatchContext(MatchKind kind, SemIR::SpecificId callee_specific_id =
  58. SemIR::SpecificId::None)
  59. : next_index_(0), kind_(kind), callee_specific_id_(callee_specific_id) {}
  60. // Adds a work item to the stack.
  61. auto AddWork(WorkItem work_item) -> void { stack_.push_back(work_item); }
  62. // Processes all work items on the stack. When performing caller pattern
  63. // matching, returns an inst block with one inst reference for each
  64. // calling-convention argument. When performing callee pattern matching,
  65. // returns an inst block with references to all the emitted BindName insts.
  66. auto DoWork(Context& context) -> SemIR::InstBlockId;
  67. private:
  68. // Allocates the next unallocated RuntimeParamIndex, starting from 0.
  69. auto NextRuntimeIndex() -> SemIR::RuntimeParamIndex {
  70. auto result = next_index_;
  71. ++next_index_.index;
  72. return result;
  73. }
  74. // Emits the pattern-match insts necessary to match the pattern inst
  75. // `entry.pattern_id` against the scrutinee value `entry.scrutinee_id`, and
  76. // adds to `stack_` any work necessary to traverse into its subpatterns. This
  77. // behavior is contingent on the kind of match being performed, as indicated
  78. // by kind_`. For example, when performing a callee pattern match, this does
  79. // not emit insts for patterns on the caller side. However, it still traverses
  80. // into subpatterns if any of their descendants might emit insts.
  81. // TODO: Require that `entry.scrutinee_id` is valid if and only if insts
  82. // should be emitted, once we start emitting `Param` insts in the
  83. // `ParamPattern` case.
  84. auto EmitPatternMatch(Context& context, MatchContext::WorkItem entry) -> void;
  85. // Implementations of `EmitPatternMatch` for particular pattern inst kinds.
  86. // The pattern argument is always equal to
  87. // `context.insts().Get(entry.pattern_id)`, and `pattern_loc_id` is always
  88. // equal to `context.insts().GetLocId(entry.pattern_id)`.
  89. auto DoEmitPatternMatch(Context& context,
  90. SemIR::AnyBindingPattern binding_pattern,
  91. SemIR::LocId pattern_loc_id, WorkItem entry) -> void;
  92. auto DoEmitPatternMatch(Context& context, SemIR::AddrPattern addr_pattern,
  93. SemIR::LocId pattern_loc_id, WorkItem entry) -> void;
  94. auto DoEmitPatternMatch(Context& context,
  95. SemIR::ValueParamPattern param_pattern,
  96. SemIR::LocId pattern_loc_id, WorkItem entry) -> void;
  97. auto DoEmitPatternMatch(Context& context,
  98. SemIR::OutParamPattern param_pattern,
  99. SemIR::LocId pattern_loc_id, WorkItem entry) -> void;
  100. auto DoEmitPatternMatch(Context& context,
  101. SemIR::ReturnSlotPattern return_slot_pattern,
  102. SemIR::LocId pattern_loc_id, WorkItem entry) -> void;
  103. auto DoEmitPatternMatch(Context& context, SemIR::VarPattern var_pattern,
  104. SemIR::LocId pattern_loc_id, WorkItem entry) -> void;
  105. auto DoEmitPatternMatch(Context& context, SemIR::TuplePattern tuple_pattern,
  106. SemIR::LocId pattern_loc_id, WorkItem entry) -> void;
  107. // The stack of work to be processed.
  108. llvm::SmallVector<WorkItem> stack_;
  109. // The next index to be allocated by `NextRuntimeIndex`.
  110. SemIR::RuntimeParamIndex next_index_;
  111. // The pending results that will be returned by the current `DoWork` call.
  112. llvm::SmallVector<SemIR::InstId> results_;
  113. // The kind of pattern match being performed.
  114. MatchKind kind_;
  115. // The SpecificId of the function being called (if any).
  116. SemIR::SpecificId callee_specific_id_;
  117. };
  118. } // namespace
  119. auto MatchContext::DoWork(Context& context) -> SemIR::InstBlockId {
  120. results_.reserve(stack_.size());
  121. while (!stack_.empty()) {
  122. EmitPatternMatch(context, stack_.pop_back_val());
  123. }
  124. auto block_id = context.inst_blocks().Add(results_);
  125. results_.clear();
  126. return block_id;
  127. }
  128. // Inserts the given region into the current code block. If the region
  129. // consists of a single block, this will be implemented as a `splice_block`
  130. // inst. Otherwise, this will end the current block with a branch to the entry
  131. // block of the region, and add future insts to a new block which is the
  132. // immediate successor of the region's exit block. As a result, this cannot be
  133. // called more than once for the same region.
  134. static auto InsertHere(Context& context, SemIR::ExprRegionId region_id)
  135. -> SemIR::InstId {
  136. auto region = context.sem_ir().expr_regions().Get(region_id);
  137. auto loc_id = context.insts().GetLocId(region.result_id);
  138. auto exit_block = context.inst_blocks().Get(region.block_ids.back());
  139. if (region.block_ids.size() == 1) {
  140. // TODO: Is it possible to avoid leaving an "orphan" block in the IR in the
  141. // first two cases?
  142. if (exit_block.empty()) {
  143. return region.result_id;
  144. }
  145. if (exit_block.size() == 1) {
  146. context.inst_block_stack().AddInstId(exit_block.front());
  147. return region.result_id;
  148. }
  149. return AddInst<SemIR::SpliceBlock>(
  150. context, loc_id,
  151. {.type_id = context.insts().Get(region.result_id).type_id(),
  152. .block_id = region.block_ids.front(),
  153. .result_id = region.result_id});
  154. }
  155. if (context.region_stack().empty()) {
  156. context.TODO(loc_id,
  157. "Control flow expressions are currently only supported inside "
  158. "functions.");
  159. return SemIR::ErrorInst::SingletonInstId;
  160. }
  161. AddInst(context, SemIR::LocIdAndInst::NoLoc<SemIR::Branch>(
  162. {.target_id = region.block_ids.front()}));
  163. context.inst_block_stack().Pop();
  164. // TODO: this will cumulatively cost O(MN) running time for M blocks
  165. // at the Nth level of the stack. Figure out how to do better.
  166. context.region_stack().AddToRegion(region.block_ids);
  167. auto resume_with_block_id =
  168. context.insts().GetAs<SemIR::Branch>(exit_block.back()).target_id;
  169. CARBON_CHECK(context.inst_blocks().GetOrEmpty(resume_with_block_id).empty());
  170. context.inst_block_stack().Push(resume_with_block_id);
  171. context.region_stack().AddToRegion(resume_with_block_id, loc_id);
  172. return region.result_id;
  173. }
  174. auto MatchContext::DoEmitPatternMatch(Context& context,
  175. SemIR::AnyBindingPattern binding_pattern,
  176. SemIR::LocId /*pattern_loc_id*/,
  177. MatchContext::WorkItem entry) -> void {
  178. // We're logically consuming this map entry, so we invalidate it in order
  179. // to avoid accidentally consuming it twice.
  180. auto [bind_name_id, type_expr_region_id] =
  181. std::exchange(context.bind_name_map().Lookup(entry.pattern_id).value(),
  182. {.bind_name_id = SemIR::InstId::None,
  183. .type_expr_region_id = SemIR::ExprRegionId::None});
  184. InsertHere(context, type_expr_region_id);
  185. auto value_id = entry.scrutinee_id;
  186. switch (kind_) {
  187. case MatchKind::Local: {
  188. value_id = ConvertToValueOrRefOfType(
  189. context, context.insts().GetLocId(entry.scrutinee_id),
  190. entry.scrutinee_id, binding_pattern.type_id);
  191. break;
  192. }
  193. case MatchKind::Callee: {
  194. if (context.insts()
  195. .GetAs<SemIR::AnyParam>(value_id)
  196. .runtime_index.has_value()) {
  197. results_.push_back(value_id);
  198. }
  199. break;
  200. }
  201. case MatchKind::Caller:
  202. CARBON_FATAL("Found binding pattern during caller pattern match");
  203. }
  204. auto bind_name = context.insts().GetAs<SemIR::AnyBindName>(bind_name_id);
  205. CARBON_CHECK(!bind_name.value_id.has_value());
  206. bind_name.value_id = value_id;
  207. ReplaceInstBeforeConstantUse(context, bind_name_id, bind_name);
  208. context.inst_block_stack().AddInstId(bind_name_id);
  209. }
  210. auto MatchContext::DoEmitPatternMatch(Context& context,
  211. SemIR::AddrPattern addr_pattern,
  212. SemIR::LocId /*pattern_loc_id*/,
  213. WorkItem entry) -> void {
  214. CARBON_CHECK(kind_ != MatchKind::Local);
  215. if (kind_ == MatchKind::Callee) {
  216. // We're emitting pattern-match IR for the callee, but we're still on
  217. // the caller side of the pattern, so we traverse without emitting any
  218. // insts.
  219. AddWork({.pattern_id = addr_pattern.inner_id,
  220. .scrutinee_id = SemIR::InstId::None});
  221. return;
  222. }
  223. CARBON_CHECK(entry.scrutinee_id.has_value());
  224. auto scrutinee_ref_id = ConvertToValueOrRefExpr(context, entry.scrutinee_id);
  225. switch (SemIR::GetExprCategory(context.sem_ir(), scrutinee_ref_id)) {
  226. case SemIR::ExprCategory::Error:
  227. case SemIR::ExprCategory::DurableRef:
  228. case SemIR::ExprCategory::EphemeralRef:
  229. break;
  230. default:
  231. CARBON_DIAGNOSTIC(AddrSelfIsNonRef, Error,
  232. "`addr self` method cannot be invoked on a value");
  233. context.emitter().Emit(
  234. TokenOnly(context.insts().GetLocId(entry.scrutinee_id)),
  235. AddrSelfIsNonRef);
  236. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  237. return;
  238. }
  239. auto scrutinee_ref = context.insts().Get(scrutinee_ref_id);
  240. auto new_scrutinee = AddInst<SemIR::AddrOf>(
  241. context, context.insts().GetLocId(scrutinee_ref_id),
  242. {.type_id = GetPointerType(context, scrutinee_ref.type_id()),
  243. .lvalue_id = scrutinee_ref_id});
  244. AddWork({.pattern_id = addr_pattern.inner_id, .scrutinee_id = new_scrutinee});
  245. }
  246. auto MatchContext::DoEmitPatternMatch(Context& context,
  247. SemIR::ValueParamPattern param_pattern,
  248. SemIR::LocId pattern_loc_id,
  249. WorkItem entry) -> void {
  250. CARBON_CHECK(param_pattern.runtime_index.index < 0 ||
  251. static_cast<size_t>(param_pattern.runtime_index.index) ==
  252. results_.size(),
  253. "Parameters out of order; expecting {0} but got {1}",
  254. results_.size(), param_pattern.runtime_index.index);
  255. switch (kind_) {
  256. case MatchKind::Caller: {
  257. CARBON_CHECK(entry.scrutinee_id.has_value());
  258. if (entry.scrutinee_id == SemIR::ErrorInst::SingletonInstId) {
  259. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  260. } else {
  261. results_.push_back(ConvertToValueOfType(
  262. context, context.insts().GetLocId(entry.scrutinee_id),
  263. entry.scrutinee_id,
  264. SemIR::GetTypeInSpecific(context.sem_ir(), callee_specific_id_,
  265. param_pattern.type_id)));
  266. }
  267. // Do not traverse farther, because the caller side of the pattern
  268. // ends here.
  269. break;
  270. }
  271. case MatchKind::Callee: {
  272. if (param_pattern.runtime_index == SemIR::RuntimeParamIndex::Unknown) {
  273. param_pattern.runtime_index = NextRuntimeIndex();
  274. ReplaceInstBeforeConstantUse(context, entry.pattern_id, param_pattern);
  275. }
  276. AddWork({.pattern_id = param_pattern.subpattern_id,
  277. .scrutinee_id = AddInst<SemIR::ValueParam>(
  278. context, pattern_loc_id,
  279. {.type_id = param_pattern.type_id,
  280. .runtime_index = param_pattern.runtime_index,
  281. .pretty_name_id = GetPrettyName(context, param_pattern)})});
  282. break;
  283. }
  284. case MatchKind::Local: {
  285. CARBON_FATAL("Found ValueParamPattern during local pattern match");
  286. }
  287. }
  288. }
  289. auto MatchContext::DoEmitPatternMatch(Context& context,
  290. SemIR::OutParamPattern param_pattern,
  291. SemIR::LocId pattern_loc_id,
  292. WorkItem entry) -> void {
  293. switch (kind_) {
  294. case MatchKind::Caller: {
  295. CARBON_CHECK(entry.scrutinee_id.has_value());
  296. CARBON_CHECK(context.insts().Get(entry.scrutinee_id).type_id() ==
  297. SemIR::GetTypeInSpecific(context.sem_ir(),
  298. callee_specific_id_,
  299. param_pattern.type_id));
  300. results_.push_back(entry.scrutinee_id);
  301. // Do not traverse farther, because the caller side of the pattern
  302. // ends here.
  303. break;
  304. }
  305. case MatchKind::Callee: {
  306. // TODO: Consider ways to address near-duplication with the
  307. // ValueParamPattern case.
  308. if (param_pattern.runtime_index == SemIR::RuntimeParamIndex::Unknown) {
  309. param_pattern.runtime_index = NextRuntimeIndex();
  310. ReplaceInstBeforeConstantUse(context, entry.pattern_id, param_pattern);
  311. }
  312. AddWork({.pattern_id = param_pattern.subpattern_id,
  313. .scrutinee_id = AddInst<SemIR::OutParam>(
  314. context, pattern_loc_id,
  315. {.type_id = param_pattern.type_id,
  316. .runtime_index = param_pattern.runtime_index,
  317. .pretty_name_id = GetPrettyName(context, param_pattern)})});
  318. break;
  319. }
  320. case MatchKind::Local: {
  321. CARBON_FATAL("Found OutParamPattern during local pattern match");
  322. }
  323. }
  324. }
  325. auto MatchContext::DoEmitPatternMatch(
  326. Context& context, SemIR::ReturnSlotPattern return_slot_pattern,
  327. SemIR::LocId pattern_loc_id, WorkItem entry) -> void {
  328. CARBON_CHECK(kind_ == MatchKind::Callee);
  329. auto return_slot_id = AddInst<SemIR::ReturnSlot>(
  330. context, pattern_loc_id,
  331. {.type_id = return_slot_pattern.type_id,
  332. .type_inst_id = return_slot_pattern.type_inst_id,
  333. .storage_id = entry.scrutinee_id});
  334. bool already_in_lookup =
  335. context.scope_stack()
  336. .LookupOrAddName(SemIR::NameId::ReturnSlot, return_slot_id)
  337. .has_value();
  338. CARBON_CHECK(!already_in_lookup);
  339. results_.push_back(entry.scrutinee_id);
  340. }
  341. auto MatchContext::DoEmitPatternMatch(Context& context,
  342. SemIR::VarPattern var_pattern,
  343. SemIR::LocId pattern_loc_id,
  344. WorkItem entry) -> void {
  345. auto var_id = context.var_storage_map().Lookup(entry.pattern_id).value();
  346. // TODO: Find a more efficient way to put these insts in the global_init
  347. // block (or drop the distinction between the global_init block and the
  348. // file scope?)
  349. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  350. context.global_init().Resume();
  351. }
  352. if (entry.scrutinee_id.has_value()) {
  353. auto init_id =
  354. Initialize(context, pattern_loc_id, var_id, entry.scrutinee_id);
  355. // TODO: Consider using different instruction kinds for assignment
  356. // versus initialization.
  357. AddInst<SemIR::Assign>(context, pattern_loc_id,
  358. {.lhs_id = var_id, .rhs_id = init_id});
  359. }
  360. AddWork({.pattern_id = var_pattern.subpattern_id, .scrutinee_id = var_id});
  361. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  362. context.global_init().Suspend();
  363. }
  364. }
  365. auto MatchContext::DoEmitPatternMatch(Context& context,
  366. SemIR::TuplePattern tuple_pattern,
  367. SemIR::LocId pattern_loc_id,
  368. WorkItem entry) -> void {
  369. if (tuple_pattern.type_id == SemIR::ErrorInst::SingletonTypeId) {
  370. return;
  371. }
  372. auto subpattern_ids = context.inst_blocks().Get(tuple_pattern.elements_id);
  373. auto add_all_subscrutinees =
  374. [&](llvm::ArrayRef<SemIR::InstId> subscrutinee_ids) {
  375. for (auto [subpattern_id, subscrutinee_id] :
  376. llvm::reverse(llvm::zip(subpattern_ids, subscrutinee_ids))) {
  377. AddWork(
  378. {.pattern_id = subpattern_id, .scrutinee_id = subscrutinee_id});
  379. }
  380. };
  381. if (!entry.scrutinee_id.has_value()) {
  382. CARBON_CHECK(kind_ == MatchKind::Callee);
  383. context.TODO(pattern_loc_id,
  384. "Support patterns besides bindings in parameter list");
  385. return;
  386. }
  387. auto scrutinee = context.insts().GetWithLocId(entry.scrutinee_id);
  388. if (auto scrutinee_literal = scrutinee.inst.TryAs<SemIR::TupleLiteral>()) {
  389. auto subscrutinee_ids =
  390. context.inst_blocks().Get(scrutinee_literal->elements_id);
  391. if (subscrutinee_ids.size() != subpattern_ids.size()) {
  392. CARBON_DIAGNOSTIC(TuplePatternSizeDoesntMatchLiteral, Error,
  393. "tuple pattern expects {0} element{0:s}, but tuple "
  394. "literal has {1}",
  395. IntAsSelect, IntAsSelect);
  396. context.emitter().Emit(pattern_loc_id, TuplePatternSizeDoesntMatchLiteral,
  397. subpattern_ids.size(), subscrutinee_ids.size());
  398. return;
  399. }
  400. add_all_subscrutinees(subscrutinee_ids);
  401. return;
  402. }
  403. auto converted_scrutinee = ConvertToValueOrRefOfType(
  404. context, pattern_loc_id, entry.scrutinee_id, tuple_pattern.type_id);
  405. if (auto scrutinee_value =
  406. context.insts().TryGetAs<SemIR::TupleValue>(converted_scrutinee)) {
  407. add_all_subscrutinees(
  408. context.inst_blocks().Get(scrutinee_value->elements_id));
  409. return;
  410. }
  411. auto tuple_type =
  412. context.types().GetAs<SemIR::TupleType>(tuple_pattern.type_id);
  413. auto element_type_ids = context.type_blocks().Get(tuple_type.elements_id);
  414. llvm::SmallVector<SemIR::InstId> subscrutinee_ids;
  415. subscrutinee_ids.reserve(element_type_ids.size());
  416. for (auto [i, element_type_id] : llvm::enumerate(element_type_ids)) {
  417. subscrutinee_ids.push_back(
  418. AddInst<SemIR::TupleAccess>(context, scrutinee.loc_id,
  419. {.type_id = element_type_id,
  420. .tuple_id = entry.scrutinee_id,
  421. .index = SemIR::ElementIndex(i)}));
  422. }
  423. add_all_subscrutinees(subscrutinee_ids);
  424. }
  425. auto MatchContext::EmitPatternMatch(Context& context,
  426. MatchContext::WorkItem entry) -> void {
  427. if (entry.pattern_id == SemIR::ErrorInst::SingletonInstId) {
  428. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  429. return;
  430. }
  431. DiagnosticAnnotationScope annotate_diagnostics(
  432. &context.emitter(), [&](auto& builder) {
  433. if (kind_ == MatchKind::Caller) {
  434. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  435. "initializing function parameter");
  436. builder.Note(entry.pattern_id, InCallToFunctionParam);
  437. }
  438. });
  439. auto pattern = context.insts().GetWithLocId(entry.pattern_id);
  440. CARBON_KIND_SWITCH(pattern.inst) {
  441. case SemIR::BindingPattern::Kind:
  442. case SemIR::SymbolicBindingPattern::Kind: {
  443. DoEmitPatternMatch(context, pattern.inst.As<SemIR::AnyBindingPattern>(),
  444. pattern.loc_id, entry);
  445. break;
  446. }
  447. case CARBON_KIND(SemIR::AddrPattern addr_pattern): {
  448. DoEmitPatternMatch(context, addr_pattern, pattern.loc_id, entry);
  449. break;
  450. }
  451. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  452. DoEmitPatternMatch(context, param_pattern, pattern.loc_id, entry);
  453. break;
  454. }
  455. case CARBON_KIND(SemIR::OutParamPattern param_pattern): {
  456. DoEmitPatternMatch(context, param_pattern, pattern.loc_id, entry);
  457. break;
  458. }
  459. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  460. DoEmitPatternMatch(context, return_slot_pattern, pattern.loc_id, entry);
  461. break;
  462. }
  463. case CARBON_KIND(SemIR::VarPattern var_pattern): {
  464. DoEmitPatternMatch(context, var_pattern, pattern.loc_id, entry);
  465. break;
  466. }
  467. case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
  468. DoEmitPatternMatch(context, tuple_pattern, pattern.loc_id, entry);
  469. break;
  470. }
  471. default: {
  472. CARBON_FATAL("Inst kind not handled: {0}", pattern.inst.kind());
  473. }
  474. }
  475. }
  476. auto CalleePatternMatch(Context& context,
  477. SemIR::InstBlockId implicit_param_patterns_id,
  478. SemIR::InstBlockId param_patterns_id,
  479. SemIR::InstId return_slot_pattern_id)
  480. -> SemIR::InstBlockId {
  481. if (!return_slot_pattern_id.has_value() && !param_patterns_id.has_value() &&
  482. !implicit_param_patterns_id.has_value()) {
  483. return SemIR::InstBlockId::None;
  484. }
  485. MatchContext match(MatchKind::Callee);
  486. // We add work to the stack in reverse so that the results will be produced
  487. // in the original order.
  488. if (return_slot_pattern_id.has_value()) {
  489. match.AddWork({.pattern_id = return_slot_pattern_id,
  490. .scrutinee_id = SemIR::InstId::None});
  491. }
  492. if (param_patterns_id.has_value()) {
  493. for (SemIR::InstId inst_id :
  494. llvm::reverse(context.inst_blocks().Get(param_patterns_id))) {
  495. match.AddWork(
  496. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  497. }
  498. }
  499. if (implicit_param_patterns_id.has_value()) {
  500. for (SemIR::InstId inst_id :
  501. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  502. match.AddWork(
  503. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  504. }
  505. }
  506. return match.DoWork(context);
  507. }
  508. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  509. SemIR::InstId self_pattern_id,
  510. SemIR::InstBlockId param_patterns_id,
  511. SemIR::InstId return_slot_pattern_id,
  512. SemIR::InstId self_arg_id,
  513. llvm::ArrayRef<SemIR::InstId> arg_refs,
  514. SemIR::InstId return_slot_arg_id)
  515. -> SemIR::InstBlockId {
  516. MatchContext match(MatchKind::Caller, specific_id);
  517. // Track the return storage, if present.
  518. if (return_slot_arg_id.has_value()) {
  519. CARBON_CHECK(return_slot_pattern_id.has_value());
  520. match.AddWork({.pattern_id = return_slot_pattern_id,
  521. .scrutinee_id = return_slot_arg_id});
  522. }
  523. // Check type conversions per-element.
  524. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  525. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  526. auto runtime_index = SemIR::Function::GetParamPatternInfoFromPatternId(
  527. context.sem_ir(), param_pattern_id)
  528. .inst.runtime_index;
  529. if (!runtime_index.has_value()) {
  530. // Not a runtime parameter: we don't pass an argument.
  531. continue;
  532. }
  533. match.AddWork({.pattern_id = param_pattern_id, .scrutinee_id = arg_id});
  534. }
  535. if (self_pattern_id.has_value()) {
  536. match.AddWork({.pattern_id = self_pattern_id, .scrutinee_id = self_arg_id});
  537. }
  538. return match.DoWork(context);
  539. }
  540. auto LocalPatternMatch(Context& context, SemIR::InstId pattern_id,
  541. SemIR::InstId scrutinee_id) -> void {
  542. MatchContext match(MatchKind::Local);
  543. match.AddWork({.pattern_id = pattern_id, .scrutinee_id = scrutinee_id});
  544. match.DoWork(context);
  545. }
  546. } // namespace Carbon::Check