thunk.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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/thunk.h"
  5. #include <utility>
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/call.h"
  8. #include "toolchain/check/convert.h"
  9. #include "toolchain/check/cpp/operators.h"
  10. #include "toolchain/check/deferred_definition_worklist.h"
  11. #include "toolchain/check/diagnostic_helpers.h"
  12. #include "toolchain/check/function.h"
  13. #include "toolchain/check/generic.h"
  14. #include "toolchain/check/inst.h"
  15. #include "toolchain/check/member_access.h"
  16. #include "toolchain/check/name_ref.h"
  17. #include "toolchain/check/pattern.h"
  18. #include "toolchain/check/pattern_match.h"
  19. #include "toolchain/check/pointer_dereference.h"
  20. #include "toolchain/check/return.h"
  21. #include "toolchain/check/type.h"
  22. #include "toolchain/diagnostics/diagnostic.h"
  23. #include "toolchain/sem_ir/function.h"
  24. #include "toolchain/sem_ir/generic.h"
  25. #include "toolchain/sem_ir/ids.h"
  26. #include "toolchain/sem_ir/inst.h"
  27. #include "toolchain/sem_ir/pattern.h"
  28. #include "toolchain/sem_ir/typed_insts.h"
  29. namespace Carbon::Check {
  30. // Adds a pattern instruction for a thunk, copying the location from an existing
  31. // instruction.
  32. static auto RebuildPatternInst(Context& context, SemIR::InstId orig_inst_id,
  33. SemIR::Inst new_inst) -> SemIR::InstId {
  34. // Ensure we built the same kind of instruction. In particular, this ensures
  35. // that the location of the old instruction can be reused for the new one.
  36. CARBON_CHECK(context.insts().Get(orig_inst_id).kind() == new_inst.kind(),
  37. "Rebuilt pattern with the wrong kind: {0} -> {1}",
  38. context.insts().Get(orig_inst_id), new_inst);
  39. return AddInst(context,
  40. SemIR::LocIdAndInst::RuntimeVerified(
  41. context.sem_ir(), SemIR::LocId(orig_inst_id), new_inst));
  42. }
  43. // Wrapper to allow the type to be specified as a template argument for API
  44. // consistency with `AddInst`.
  45. template <typename InstT>
  46. static auto RebuildPatternInst(Context& context, SemIR::InstId orig_inst_id,
  47. InstT new_inst) -> SemIR::InstId {
  48. return RebuildPatternInst(context, orig_inst_id, SemIR::Inst(new_inst));
  49. }
  50. // Makes a copy of the given binding pattern, with its type adjusted to be
  51. // `new_pattern_type_id`.
  52. static auto CloneBindingPattern(Context& context, SemIR::InstId pattern_id,
  53. SemIR::AnyBindingPattern pattern,
  54. SemIR::TypeId new_pattern_type_id)
  55. -> SemIR::InstId {
  56. auto entity_name = context.entity_names().Get(pattern.entity_name_id);
  57. CARBON_CHECK((pattern.kind == SemIR::SymbolicBindingPattern::Kind) ==
  58. entity_name.bind_index().has_value());
  59. // Get the transformed type of the binding.
  60. if (new_pattern_type_id == SemIR::ErrorInst::TypeId) {
  61. return SemIR::ErrorInst::InstId;
  62. }
  63. pattern.type_id = new_pattern_type_id;
  64. auto phase = BindingPhase::Runtime;
  65. if (pattern.kind == SemIR::SymbolicBindingPattern::Kind) {
  66. phase = entity_name.is_template ? BindingPhase::Template
  67. : BindingPhase::Symbolic;
  68. }
  69. pattern.entity_name_id = AddBindingEntityName(context, entity_name.name_id,
  70. /*form_id=*/SemIR::InstId::None,
  71. entity_name.is_unused, phase);
  72. if (pattern.kind == SemIR::WrapperBindingPattern::Kind) {
  73. auto subpattern = context.insts().GetAs<SemIR::AnyLeafParamPattern>(
  74. pattern.subpattern_id);
  75. if (subpattern.kind == SemIR::FormParamPatternAction::Kind) {
  76. context.TODO(pattern_id, "Support for cloning generic form bindings");
  77. return SemIR::ErrorInst::InstId;
  78. }
  79. pattern.subpattern_id = RebuildPatternInst<SemIR::AnyLeafParamPattern>(
  80. context, pattern.subpattern_id,
  81. {.kind = subpattern.kind,
  82. .type_id = new_pattern_type_id,
  83. .pretty_name_id = entity_name.name_id});
  84. }
  85. // Rebuild the binding pattern.
  86. return AddBindingPattern(context, SemIR::LocId(pattern_id),
  87. SemIR::ExprRegionId::None, pattern)
  88. .pattern_id;
  89. }
  90. // Makes a copy of the given pattern instruction, substituting values from a
  91. // specific as needed. The resulting pattern behaves like a newly-created
  92. // pattern, so is suitable for running `CalleePatternMatch` against.
  93. static auto ClonePattern(Context& context, SemIR::SpecificId specific_id,
  94. SemIR::InstId pattern_id) -> SemIR::InstId {
  95. if (!pattern_id.has_value()) {
  96. return SemIR::InstId::None;
  97. }
  98. auto get_type = [&](SemIR::InstId inst_id) -> SemIR::TypeId {
  99. return SemIR::GetTypeOfInstInSpecific(context.sem_ir(), specific_id,
  100. inst_id);
  101. };
  102. auto pattern = context.insts().Get(pattern_id);
  103. // Decompose the pattern. The forms we allow for patterns in a function
  104. // parameter list are currently fairly restrictive.
  105. // Optional var parameter pattern.
  106. auto [var_param, var_param_id] = context.insts().TryUnwrap(
  107. pattern, pattern_id, &SemIR::VarParamPattern::subpattern_id);
  108. // Finally, either a binding pattern or a return slot pattern.
  109. auto new_pattern_id = SemIR::InstId::None;
  110. if (auto binding = pattern.TryAs<SemIR::AnyBindingPattern>()) {
  111. new_pattern_id = CloneBindingPattern(context, pattern_id, *binding,
  112. get_type(pattern_id));
  113. } else if (auto return_slot = pattern.TryAs<SemIR::ReturnSlotPattern>()) {
  114. auto new_subpattern_id = SemIR::InstId::None;
  115. auto subpattern = context.insts().Get(return_slot->subpattern_id);
  116. CARBON_KIND_SWITCH(subpattern) {
  117. case SemIR::OutParamPattern::Kind:
  118. case SemIR::RefReturnPattern::Kind:
  119. case SemIR::ValueReturnPattern::Kind:
  120. // These are leaf insts, so we can reuse their contents after updating
  121. // the type.
  122. subpattern.SetType(get_type(return_slot->subpattern_id));
  123. new_subpattern_id =
  124. RebuildPatternInst(context, return_slot->subpattern_id, subpattern);
  125. break;
  126. case SemIR::ErrorInst::Kind:
  127. subpattern.SetType(SemIR::ErrorInst::TypeId);
  128. new_subpattern_id = SemIR::ErrorInst::InstId;
  129. break;
  130. default:
  131. CARBON_FATAL("Unexpected kind for return slot subpattern {0}",
  132. subpattern);
  133. }
  134. new_pattern_id = RebuildPatternInst<SemIR::ReturnSlotPattern>(
  135. context, pattern_id,
  136. {.type_id = get_type(pattern_id),
  137. .subpattern_id = new_subpattern_id,
  138. .type_inst_id = SemIR::TypeInstId::None});
  139. } else {
  140. CARBON_CHECK(pattern.Is<SemIR::ErrorInst>(),
  141. "Unexpected pattern {0} in function signature", pattern);
  142. return SemIR::ErrorInst::InstId;
  143. }
  144. // Rebuild parameter.
  145. if (var_param && new_pattern_id != SemIR::ErrorInst::InstId) {
  146. new_pattern_id = RebuildPatternInst<SemIR::VarParamPattern>(
  147. context, var_param_id,
  148. {.type_id = get_type(var_param_id), .subpattern_id = new_pattern_id});
  149. }
  150. return new_pattern_id;
  151. }
  152. static auto ClonePatternBlock(Context& context, SemIR::SpecificId specific_id,
  153. SemIR::InstBlockId inst_block_id)
  154. -> SemIR::InstBlockId {
  155. if (!inst_block_id.has_value()) {
  156. return SemIR::InstBlockId::None;
  157. }
  158. return context.inst_blocks().Transform(
  159. inst_block_id, [&](SemIR::InstId inst_id) {
  160. return ClonePattern(context, specific_id, inst_id);
  161. });
  162. }
  163. static auto CloneInstId(Context& context, SemIR::SpecificId specific_id,
  164. SemIR::InstId inst_id) -> SemIR::InstId {
  165. if (!inst_id.has_value()) {
  166. return SemIR::InstId::None;
  167. }
  168. return GetOrAddInst<SemIR::SpecificConstant>(
  169. context, SemIR::LocId(inst_id),
  170. {.type_id = SemIR::TypeType::TypeId,
  171. .inst_id = inst_id,
  172. .specific_id = specific_id});
  173. }
  174. static auto CloneTypeInstId(Context& context, SemIR::SpecificId specific_id,
  175. SemIR::TypeInstId inst_id) -> SemIR::TypeInstId {
  176. if (!inst_id.has_value()) {
  177. return SemIR::TypeInstId::None;
  178. }
  179. return context.types().GetAsTypeInstId(
  180. CloneInstId(context, specific_id, inst_id));
  181. }
  182. static auto CloneFunctionDecl(Context& context, SemIR::LocId loc_id,
  183. SemIR::FunctionId signature_id,
  184. SemIR::SpecificId signature_specific_id,
  185. SemIR::FunctionId callee_id)
  186. -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  187. StartGenericDecl(context);
  188. const auto& signature = context.functions().Get(signature_id);
  189. // Clone the signature.
  190. context.pattern_block_stack().Push();
  191. auto implicit_param_patterns_id = ClonePatternBlock(
  192. context, signature_specific_id, signature.implicit_param_patterns_id);
  193. auto param_patterns_id = ClonePatternBlock(context, signature_specific_id,
  194. signature.param_patterns_id);
  195. auto return_pattern_id =
  196. ClonePattern(context, signature_specific_id, signature.return_pattern_id);
  197. auto return_type_inst_id = CloneTypeInstId(context, signature_specific_id,
  198. signature.return_type_inst_id);
  199. auto return_form_inst_id = CloneInstId(context, signature_specific_id,
  200. signature.return_form_inst_id);
  201. auto self_param_id = FindSelfPattern(context, implicit_param_patterns_id);
  202. auto pattern_block_id = context.pattern_block_stack().Pop();
  203. // Perform callee-side pattern matching to rebuild the parameter list.
  204. context.inst_block_stack().Push();
  205. auto match_results = CalleePatternMatch(context, implicit_param_patterns_id,
  206. param_patterns_id, return_pattern_id);
  207. auto decl_block_id = context.inst_block_stack().Pop();
  208. // Create the `FunctionDecl` instruction.
  209. auto& callee = context.functions().Get(callee_id);
  210. auto [decl_id, function_id] = MakeFunctionDecl(
  211. context, loc_id, decl_block_id, /*build_generic=*/true,
  212. /*is_definition=*/true,
  213. SemIR::Function{
  214. {
  215. .name_id = signature.name_id,
  216. .parent_scope_id = callee.parent_scope_id,
  217. // Set by `MakeFunctionDecl`.
  218. .generic_id = SemIR::GenericId::None,
  219. .first_param_node_id = signature.first_param_node_id,
  220. .last_param_node_id = signature.last_param_node_id,
  221. .pattern_block_id = pattern_block_id,
  222. .implicit_param_patterns_id = implicit_param_patterns_id,
  223. .param_patterns_id = param_patterns_id,
  224. .is_extern = false,
  225. .extern_library_id = SemIR::LibraryNameId::None,
  226. .non_owning_decl_id = SemIR::InstId::None,
  227. // Set by `MakeFunctionDecl`.
  228. .first_owning_decl_id = SemIR::InstId::None,
  229. },
  230. {
  231. .call_param_patterns_id = match_results.call_param_patterns_id,
  232. .call_params_id = match_results.call_params_id,
  233. .call_param_ranges = match_results.param_ranges,
  234. .return_type_inst_id = return_type_inst_id,
  235. .return_form_inst_id = return_form_inst_id,
  236. .return_pattern_id = return_pattern_id,
  237. .virtual_modifier = callee.virtual_modifier,
  238. .virtual_index = callee.virtual_index,
  239. .evaluation_mode = signature.evaluation_mode,
  240. .self_param_id = self_param_id,
  241. }});
  242. context.inst_block_stack().AddInstId(decl_id);
  243. return {function_id, decl_id};
  244. }
  245. static auto HasDeclaredReturnType(Context& context,
  246. SemIR::FunctionId function_id) -> bool {
  247. return context.functions().Get(function_id).return_type_inst_id.has_value();
  248. }
  249. auto PerformThunkCall(Context& context, SemIR::LocId loc_id,
  250. SemIR::FunctionId function_id,
  251. llvm::ArrayRef<SemIR::InstId> param_pattern_ids,
  252. llvm::ArrayRef<SemIR::InstId> call_arg_ids,
  253. SemIR::InstId callee_id) -> SemIR::InstId {
  254. auto& function = context.functions().Get(function_id);
  255. auto [args_vec, ignored_call_args] = ThunkPatternMatch(
  256. context, function.self_param_id, param_pattern_ids, call_arg_ids);
  257. llvm::ArrayRef<SemIR::InstId> args = args_vec;
  258. // If we have a self parameter, form `self.<callee_id>` if needed.
  259. // When calling a C++ constructor to implement `Copy`, or calling a C++
  260. // non-method operator to implement a Carbon operator, the interface has a
  261. // `self` parameter but C++ models that parameter as an explicit argument
  262. // instead, so add the `self` to the argument list instead in that case.
  263. if (function.self_param_id.has_value() &&
  264. !IsCppConstructorOrNonMethodOperator(context, callee_id)) {
  265. callee_id = PerformCompoundMemberAccess(context, loc_id,
  266. args.consume_front(), callee_id);
  267. }
  268. return PerformCall(context, loc_id, callee_id, args);
  269. }
  270. // Build a call to a function that forwards the arguments of the enclosing
  271. // function, for use when constructing a thunk.
  272. static auto BuildThunkCall(Context& context, SemIR::FunctionId function_id,
  273. SemIR::InstId callee_id,
  274. llvm::ArrayRef<SemIR::InstId> param_pattern_ids,
  275. llvm::ArrayRef<SemIR::InstId> call_arg_ids)
  276. -> SemIR::InstId {
  277. auto& function = context.functions().Get(function_id);
  278. // Build a `NameRef` naming the callee, and a `SpecificConstant` if needed.
  279. auto loc_id = SemIR::LocId(callee_id);
  280. auto callee_type = context.types().GetAs<SemIR::FunctionType>(
  281. context.insts().Get(callee_id).type_id());
  282. callee_id = BuildNameRef(context, loc_id, function.name_id, callee_id,
  283. callee_type.specific_id);
  284. return PerformThunkCall(context, loc_id, function_id, param_pattern_ids,
  285. call_arg_ids, callee_id);
  286. }
  287. static auto StartThunkFunctionDefinition(Context& context,
  288. SemIR::FunctionId function_id,
  289. SemIR::InstId thunk_id,
  290. SemIR::InstId callee_id) {
  291. // The check below produces diagnostics referring to the signature, so also
  292. // note the callee.
  293. Diagnostics::AnnotationScope annot_scope(
  294. &context.emitter(), [&](DiagnosticBuilder& builder) {
  295. CARBON_DIAGNOSTIC(ThunkCallee, Note,
  296. "while building thunk calling this function");
  297. builder.Note(callee_id, ThunkCallee);
  298. });
  299. StartFunctionDefinition(context, thunk_id, function_id);
  300. }
  301. // Given a declaration of a thunk and the function that it should call, build
  302. // the thunk body.
  303. static auto BuildThunkDefinition(Context& context,
  304. SemIR::FunctionId signature_id,
  305. SemIR::FunctionId function_id,
  306. SemIR::InstId thunk_id,
  307. SemIR::InstId callee_id) -> void {
  308. // TODO: Improve the diagnostics produced here. Specifically, it would likely
  309. // be better for the primary error message to be that we tried to produce a
  310. // thunk because of a type mismatch, but couldn't, with notes explaining
  311. // why, rather than the primary error message being whatever went wrong
  312. // building the thunk.
  313. StartThunkFunctionDefinition(context, function_id, thunk_id, callee_id);
  314. // The checks below produce diagnostics pointing at the callee, so also note
  315. // the signature.
  316. Diagnostics::AnnotationScope annot_scope(
  317. &context.emitter(), [&](DiagnosticBuilder& builder) {
  318. CARBON_DIAGNOSTIC(
  319. ThunkSignature, Note,
  320. "while building thunk to match the signature of this function");
  321. builder.Note(context.functions().Get(signature_id).first_owning_decl_id,
  322. ThunkSignature);
  323. });
  324. const auto& function = context.functions().Get(function_id);
  325. llvm::ArrayRef<SemIR::InstId> param_pattern_ids;
  326. if (function.param_patterns_id.has_value()) {
  327. param_pattern_ids = context.inst_blocks().Get(function.param_patterns_id);
  328. }
  329. auto call_param_ids = context.inst_blocks().Get(function.call_params_id);
  330. auto call_id = BuildThunkCall(context, function_id, callee_id,
  331. param_pattern_ids, call_param_ids);
  332. if (HasDeclaredReturnType(context, function_id)) {
  333. BuildReturnWithExpr(context, SemIR::LocId(callee_id), call_id);
  334. } else {
  335. DiscardExpr(context, call_id);
  336. BuildReturnWithNoExpr(context, SemIR::LocId(callee_id));
  337. }
  338. FinishFunctionDefinition(context, function_id);
  339. }
  340. auto BuildThunkDefinitionForExport(Context& context,
  341. SemIR::FunctionId thunk_function_id,
  342. SemIR::FunctionId callee_function_id,
  343. SemIR::InstId thunk_id,
  344. SemIR::InstId callee_id) -> void {
  345. auto& thunk_function = context.functions().Get(thunk_function_id);
  346. auto& callee_function = context.functions().Get(callee_function_id);
  347. StartThunkFunctionDefinition(context, thunk_function_id, thunk_id, callee_id);
  348. const bool thunk_has_return_param =
  349. callee_function.return_type_inst_id != SemIR::TypeInstId::None;
  350. llvm::ArrayRef<SemIR::InstId> param_pattern_ids;
  351. if (thunk_function.param_patterns_id.has_value()) {
  352. param_pattern_ids =
  353. context.inst_blocks().Get(thunk_function.param_patterns_id);
  354. }
  355. llvm::SmallVector<SemIR::InstId> call_param_ids(
  356. context.inst_blocks().Get(thunk_function.call_params_id));
  357. if (thunk_has_return_param) {
  358. param_pattern_ids = param_pattern_ids.drop_back();
  359. call_param_ids.pop_back();
  360. }
  361. auto callee_param_ids =
  362. context.inst_blocks().Get(callee_function.call_param_patterns_id);
  363. // If any explicit parameters of the callee are `ref` parameters,
  364. // modify the corresponding call arguments to be `ref` tagged.
  365. for (auto index = thunk_function.call_param_ranges.explicit_begin().index;
  366. index < thunk_function.call_param_ranges.explicit_end().index; index++) {
  367. if (context.insts().Is<SemIR::RefParamPattern>(callee_param_ids[index])) {
  368. auto& call_param_id = call_param_ids[index];
  369. auto type = context.insts().Get(call_param_id).type_id();
  370. SemIR::LocId loc_id(thunk_id);
  371. call_param_id =
  372. AddInst(context, SemIR::LocIdAndInst::RuntimeVerified(
  373. context.sem_ir(), SemIR::LocId(call_param_id),
  374. SemIR::RefTagExpr{
  375. .type_id = type,
  376. .expr_id = call_param_id,
  377. }));
  378. }
  379. }
  380. auto call_id = BuildThunkCall(context, thunk_function_id, callee_id,
  381. param_pattern_ids, call_param_ids);
  382. if (thunk_has_return_param) {
  383. auto out_param_id =
  384. context.inst_blocks().Get(thunk_function.call_params_id).back();
  385. SemIR::LocId loc_id(out_param_id);
  386. auto init_id = InitializeExisting(context, loc_id, out_param_id, call_id,
  387. /*for_return=*/true);
  388. AddInst(context, loc_id,
  389. SemIR::Assign{
  390. .lhs_id = out_param_id,
  391. .rhs_id = init_id,
  392. });
  393. } else {
  394. DiscardExpr(context, call_id);
  395. }
  396. BuildReturnWithNoExpr(context, SemIR::LocId(callee_id));
  397. FinishFunctionDefinition(context, thunk_function_id);
  398. }
  399. auto BuildThunkDefinition(Context& context,
  400. DeferredDefinitionWorklist::DefineThunk&& task)
  401. -> void {
  402. context.scope_stack().Restore(std::move(task.scope));
  403. BuildThunkDefinition(context, task.info.signature_id, task.info.function_id,
  404. task.info.decl_id, task.info.callee_id);
  405. context.scope_stack().Pop();
  406. }
  407. auto BuildThunk(Context& context, SemIR::FunctionId signature_id,
  408. SemIR::SpecificId signature_specific_id,
  409. SemIR::InstId callee_id, bool defer_definition)
  410. -> SemIR::InstId {
  411. auto callee = SemIR::GetCalleeAsFunction(context.sem_ir(), callee_id);
  412. // Check whether we can use the given function without a thunk.
  413. // TODO: For virtual functions, we want different rules for checking `self`.
  414. // TODO: This is too strict; for example, we should not compare parameter
  415. // names here.
  416. if (context.functions().Get(callee.function_id).special_function_kind !=
  417. SemIR::Function::SpecialFunctionKind::HasCppThunk &&
  418. CheckFunctionTypeMatches(
  419. context, context.functions().Get(callee.function_id),
  420. context.functions().Get(signature_id), signature_specific_id,
  421. /*check_syntax=*/false, /*check_self=*/true, /*diagnose=*/false)) {
  422. return callee_id;
  423. }
  424. // From P3763:
  425. // If the function in the interface does not have a return type, the
  426. // program is invalid if the function in the impl specifies a return type.
  427. //
  428. // Call into the redeclaration checking logic to produce a suitable error.
  429. //
  430. // TODO: Consider a different rule: always use an explicit return type for the
  431. // thunk, and always convert the result of the wrapped call to the return type
  432. // of the thunk.
  433. if (!HasDeclaredReturnType(context, signature_id) &&
  434. HasDeclaredReturnType(context, callee.function_id) &&
  435. context.functions().Get(callee.function_id).name_id !=
  436. SemIR::NameId::CppOperator) {
  437. bool success = CheckFunctionReturnTypeMatches(
  438. context, context.functions().Get(callee.function_id),
  439. context.functions().Get(signature_id), signature_specific_id);
  440. CARBON_CHECK(!success, "Return type unexpectedly matches");
  441. return SemIR::ErrorInst::InstId;
  442. }
  443. // Create a scope for the function's parameters and generic parameters.
  444. context.scope_stack().PushForDeclName();
  445. // We can't use the function directly. Build a thunk.
  446. // TODO: Check for and diagnose obvious reasons why this will fail, such as
  447. // arity mismatch, before trying to build the thunk.
  448. auto [function_id, thunk_id] =
  449. CloneFunctionDecl(context, SemIR::LocId(callee_id), signature_id,
  450. signature_specific_id, callee.function_id);
  451. // Track that this function is a thunk.
  452. context.functions().Get(function_id).SetThunk(callee_id);
  453. if (defer_definition) {
  454. // Register the thunk to be defined when we reach the end of the enclosing
  455. // deferred definition scope, for example an `impl` or `class` definition,
  456. // as if the thunk's body were written inline in this location.
  457. context.deferred_definition_worklist().SuspendThunkAndPush(
  458. context, {
  459. .signature_id = signature_id,
  460. .function_id = function_id,
  461. .decl_id = thunk_id,
  462. .callee_id = callee_id,
  463. });
  464. } else {
  465. BuildThunkDefinition(context, signature_id, function_id, thunk_id,
  466. callee_id);
  467. context.scope_stack().Pop();
  468. }
  469. return thunk_id;
  470. }
  471. } // namespace Carbon::Check