cpp_thunk.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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/cpp_thunk.h"
  5. #include "clang/AST/GlobalDecl.h"
  6. #include "clang/AST/Mangle.h"
  7. #include "clang/Sema/Lookup.h"
  8. #include "clang/Sema/Overload.h"
  9. #include "clang/Sema/Sema.h"
  10. #include "toolchain/check/call.h"
  11. #include "toolchain/check/context.h"
  12. #include "toolchain/check/control_flow.h"
  13. #include "toolchain/check/convert.h"
  14. #include "toolchain/check/literal.h"
  15. #include "toolchain/check/type.h"
  16. #include "toolchain/check/type_completion.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Check {
  20. // Returns the GlobalDecl to use to represent the given function declaration.
  21. // TODO: Refactor with `Lower::CreateGlobalDecl`.
  22. static auto GetGlobalDecl(const clang::FunctionDecl* decl)
  23. -> clang::GlobalDecl {
  24. if (const auto* ctor = dyn_cast<clang::CXXConstructorDecl>(decl)) {
  25. return clang::GlobalDecl(ctor, clang::CXXCtorType::Ctor_Complete);
  26. }
  27. return clang::GlobalDecl(decl);
  28. }
  29. // Returns the C++ thunk mangled name given the callee function.
  30. static auto GenerateThunkMangledName(
  31. clang::MangleContext& mangle_context,
  32. const clang::FunctionDecl& callee_function_decl) -> std::string {
  33. RawStringOstream mangled_name_stream;
  34. mangle_context.mangleName(GetGlobalDecl(&callee_function_decl),
  35. mangled_name_stream);
  36. mangled_name_stream << ".carbon_thunk";
  37. return mangled_name_stream.TakeStr();
  38. }
  39. // Returns true if a C++ thunk is required for the given type. A C++ thunk is
  40. // required for any type except for void, pointer types and signed 32-bit and
  41. // 64-bit integers.
  42. static auto IsThunkRequiredForType(Context& context, SemIR::TypeId type_id)
  43. -> bool {
  44. if (!type_id.has_value() || type_id == SemIR::ErrorInst::TypeId) {
  45. return false;
  46. }
  47. type_id = context.types().GetUnqualifiedType(type_id);
  48. switch (context.types().GetAsInst(type_id).kind()) {
  49. case SemIR::PointerType::Kind: {
  50. return false;
  51. }
  52. case SemIR::ClassType::Kind: {
  53. if (!context.types().IsComplete(type_id)) {
  54. // Signed integers of 32 or 64 bits should be completed when imported.
  55. return true;
  56. }
  57. auto int_info = context.types().TryGetIntTypeInfo(type_id);
  58. if (!int_info || !int_info->bit_width.has_value()) {
  59. return true;
  60. }
  61. llvm::APInt bit_width = context.ints().Get(int_info->bit_width);
  62. return bit_width != 32 && bit_width != 64;
  63. }
  64. default:
  65. return true;
  66. }
  67. }
  68. auto IsCppThunkRequired(Context& context, const SemIR::Function& function)
  69. -> bool {
  70. if (!function.clang_decl_id.has_value()) {
  71. return false;
  72. }
  73. // A thunk is required if any parameter or return type requires it. However,
  74. // we don't generate a thunk if any relevant type is erroneous.
  75. bool thunk_required = false;
  76. SemIR::TypeId return_type_id =
  77. function.GetDeclaredReturnType(context.sem_ir());
  78. if (return_type_id.has_value()) {
  79. if (return_type_id == SemIR::ErrorInst::TypeId) {
  80. return false;
  81. }
  82. thunk_required = IsThunkRequiredForType(context, return_type_id);
  83. }
  84. for (auto param_id :
  85. context.inst_blocks().GetOrEmpty(function.call_params_id)) {
  86. if (param_id == SemIR::ErrorInst::InstId) {
  87. return false;
  88. }
  89. if (!thunk_required &&
  90. IsThunkRequiredForType(
  91. context,
  92. context.insts().GetAs<SemIR::AnyParam>(param_id).type_id)) {
  93. thunk_required = true;
  94. }
  95. }
  96. return thunk_required;
  97. }
  98. // Returns whether the type is void, a pointer, or a signed int of 32 or 64
  99. // bits.
  100. static auto IsSimpleAbiType(clang::ASTContext& ast_context,
  101. clang::QualType type) -> bool {
  102. if (type->isVoidType() || type->isPointerType()) {
  103. return true;
  104. }
  105. if (const auto* builtin_type = type->getAs<clang::BuiltinType>()) {
  106. if (builtin_type->isSignedInteger()) {
  107. uint64_t type_size = ast_context.getIntWidth(type);
  108. return type_size == 32 || type_size == 64;
  109. }
  110. }
  111. return false;
  112. }
  113. namespace {
  114. // Information about the callee of a thunk.
  115. struct CalleeFunctionInfo {
  116. explicit CalleeFunctionInfo(clang::FunctionDecl* decl) : decl(decl) {
  117. auto& ast_context = decl->getASTContext();
  118. const auto* method_decl = dyn_cast<clang::CXXMethodDecl>(decl);
  119. bool is_ctor = isa<clang::CXXConstructorDecl>(decl);
  120. has_object_parameter = method_decl && !method_decl->isStatic() && !is_ctor;
  121. if (has_object_parameter && method_decl->isImplicitObjectMemberFunction()) {
  122. implicit_this_type = method_decl->getThisType();
  123. }
  124. effective_return_type =
  125. is_ctor ? ast_context.getRecordType(method_decl->getParent())
  126. : decl->getReturnType();
  127. has_simple_return_type =
  128. IsSimpleAbiType(ast_context, effective_return_type);
  129. }
  130. // Returns whether this callee has an implicit `this` parameter.
  131. auto has_implicit_object_parameter() const -> bool {
  132. return !implicit_this_type.isNull();
  133. }
  134. // Returns whether this callee has an explicit `this` parameter.
  135. auto has_explicit_object_parameter() const -> bool {
  136. return has_object_parameter && !has_implicit_object_parameter();
  137. }
  138. // Returns the number of parameters the thunk should have.
  139. auto num_thunk_params() const -> unsigned {
  140. return has_implicit_object_parameter() + decl->getNumParams() +
  141. !has_simple_return_type;
  142. }
  143. // Returns the thunk parameter index corresponding to a given callee parameter
  144. // index.
  145. auto GetThunkParamIndex(unsigned callee_param_index) const -> unsigned {
  146. return has_implicit_object_parameter() + callee_param_index;
  147. }
  148. // Returns the thunk parameter index corresponding to the parameter that holds
  149. // the address of the return value.
  150. auto GetThunkReturnParamIndex() const -> unsigned {
  151. CARBON_CHECK(!has_simple_return_type);
  152. return has_implicit_object_parameter() + decl->getNumParams();
  153. }
  154. // The callee function.
  155. clang::FunctionDecl* decl;
  156. // Whether the callee has an object parameter, which might be explicit or
  157. // implicit.
  158. bool has_object_parameter;
  159. // If the callee has an implicit object parameter, the corresponding `this`
  160. // type. Otherwise a null type.
  161. clang::QualType implicit_this_type;
  162. // The return type that the callee has when viewed from Carbon. This is the
  163. // C++ return type, except that constructors return the class type in Carbon
  164. // and return void in Clang's AST.
  165. clang::QualType effective_return_type;
  166. // Whether the callee has a simple return type, that we can return directly.
  167. // If not, we'll return through an out parameter instead.
  168. bool has_simple_return_type;
  169. };
  170. } // namespace
  171. // Given a pointer type, returns the corresponding _Nonnull-qualified pointer
  172. // type.
  173. static auto GetNonnullType(clang::ASTContext& ast_context,
  174. clang::QualType pointer_type) -> clang::QualType {
  175. return ast_context.getAttributedType(clang::NullabilityKind::NonNull,
  176. pointer_type, pointer_type);
  177. }
  178. // Given the type of a callee parameter, returns the type to use for the
  179. // corresponding thunk parameter.
  180. static auto GetThunkParameterType(clang::ASTContext& ast_context,
  181. clang::QualType callee_type)
  182. -> clang::QualType {
  183. if (IsSimpleAbiType(ast_context, callee_type)) {
  184. return callee_type;
  185. }
  186. return GetNonnullType(ast_context, ast_context.getPointerType(callee_type));
  187. }
  188. // Creates the thunk parameter types given the callee function.
  189. static auto BuildThunkParameterTypes(clang::ASTContext& ast_context,
  190. CalleeFunctionInfo callee_info)
  191. -> llvm::SmallVector<clang::QualType> {
  192. llvm::SmallVector<clang::QualType> thunk_param_types;
  193. thunk_param_types.reserve(callee_info.num_thunk_params());
  194. if (callee_info.has_implicit_object_parameter()) {
  195. thunk_param_types.push_back(
  196. GetNonnullType(ast_context, callee_info.implicit_this_type));
  197. }
  198. for (const clang::ParmVarDecl* callee_param :
  199. callee_info.decl->parameters()) {
  200. // TODO: We should use the type from the function signature, not the type of
  201. // the parameter here.
  202. thunk_param_types.push_back(
  203. GetThunkParameterType(ast_context, callee_param->getType()));
  204. }
  205. if (!callee_info.has_simple_return_type) {
  206. thunk_param_types.push_back(GetNonnullType(
  207. ast_context,
  208. ast_context.getPointerType(callee_info.effective_return_type)));
  209. }
  210. CARBON_CHECK(thunk_param_types.size() == callee_info.num_thunk_params());
  211. return thunk_param_types;
  212. }
  213. // Returns the thunk parameters using the callee function parameter identifiers.
  214. static auto BuildThunkParameters(clang::ASTContext& ast_context,
  215. CalleeFunctionInfo callee_info,
  216. clang::FunctionDecl* thunk_function_decl)
  217. -> llvm::SmallVector<clang::ParmVarDecl*> {
  218. clang::SourceLocation clang_loc = callee_info.decl->getLocation();
  219. const auto* thunk_function_proto_type =
  220. thunk_function_decl->getFunctionType()->getAs<clang::FunctionProtoType>();
  221. llvm::SmallVector<clang::ParmVarDecl*> thunk_params;
  222. unsigned num_thunk_params = thunk_function_decl->getNumParams();
  223. thunk_params.reserve(num_thunk_params);
  224. if (callee_info.has_implicit_object_parameter()) {
  225. clang::ParmVarDecl* thunk_param =
  226. clang::ParmVarDecl::Create(ast_context, thunk_function_decl, clang_loc,
  227. clang_loc, &ast_context.Idents.get("this"),
  228. thunk_function_proto_type->getParamType(0),
  229. nullptr, clang::SC_None, nullptr);
  230. thunk_params.push_back(thunk_param);
  231. }
  232. for (unsigned i : llvm::seq(callee_info.decl->getNumParams())) {
  233. clang::ParmVarDecl* thunk_param = clang::ParmVarDecl::Create(
  234. ast_context, thunk_function_decl, clang_loc, clang_loc,
  235. callee_info.decl->getParamDecl(i)->getIdentifier(),
  236. thunk_function_proto_type->getParamType(
  237. callee_info.GetThunkParamIndex(i)),
  238. nullptr, clang::SC_None, nullptr);
  239. thunk_params.push_back(thunk_param);
  240. }
  241. if (!callee_info.has_simple_return_type) {
  242. clang::ParmVarDecl* thunk_param =
  243. clang::ParmVarDecl::Create(ast_context, thunk_function_decl, clang_loc,
  244. clang_loc, &ast_context.Idents.get("return"),
  245. thunk_function_proto_type->getParamType(
  246. callee_info.GetThunkReturnParamIndex()),
  247. nullptr, clang::SC_None, nullptr);
  248. thunk_params.push_back(thunk_param);
  249. }
  250. CARBON_CHECK(thunk_params.size() == num_thunk_params);
  251. return thunk_params;
  252. }
  253. // Returns the thunk function declaration given the callee function and the
  254. // thunk parameter types.
  255. static auto CreateThunkFunctionDecl(
  256. Context& context, CalleeFunctionInfo callee_info,
  257. llvm::ArrayRef<clang::QualType> thunk_param_types) -> clang::FunctionDecl* {
  258. clang::ASTContext& ast_context = context.ast_context();
  259. clang::SourceLocation clang_loc = callee_info.decl->getLocation();
  260. clang::IdentifierInfo& identifier_info = ast_context.Idents.get(
  261. callee_info.decl->getNameAsString() + "__carbon_thunk");
  262. auto ext_proto_info = clang::FunctionProtoType::ExtProtoInfo();
  263. clang::QualType thunk_function_type = ast_context.getFunctionType(
  264. callee_info.has_simple_return_type ? callee_info.effective_return_type
  265. : ast_context.VoidTy,
  266. thunk_param_types, ext_proto_info);
  267. clang::DeclContext* decl_context = ast_context.getTranslationUnitDecl();
  268. // TODO: Thunks should not have external linkage, consider using `SC_Static`.
  269. clang::FunctionDecl* thunk_function_decl = clang::FunctionDecl::Create(
  270. ast_context, decl_context, clang_loc, clang_loc,
  271. clang::DeclarationName(&identifier_info), thunk_function_type,
  272. /*TInfo=*/nullptr, clang::SC_Extern);
  273. decl_context->addDecl(thunk_function_decl);
  274. thunk_function_decl->setParams(
  275. BuildThunkParameters(ast_context, callee_info, thunk_function_decl));
  276. // Set always_inline.
  277. thunk_function_decl->addAttr(
  278. clang::AlwaysInlineAttr::CreateImplicit(ast_context));
  279. // Set asm("<callee function mangled name>.carbon_thunk").
  280. thunk_function_decl->addAttr(clang::AsmLabelAttr::CreateImplicit(
  281. ast_context,
  282. GenerateThunkMangledName(*context.sem_ir().clang_mangle_context(),
  283. *callee_info.decl),
  284. clang_loc));
  285. return thunk_function_decl;
  286. }
  287. // Builds a reference to the given parameter thunk. If `type` is specified, that
  288. // is the callee parameter type that's being held by the parameter, and
  289. // conversions will be performed as necessary to recover a value of that type.
  290. static auto BuildThunkParamRef(clang::Sema& sema,
  291. clang::FunctionDecl* thunk_function_decl,
  292. unsigned thunk_index,
  293. clang::QualType type = clang::QualType())
  294. -> clang::Expr* {
  295. clang::ParmVarDecl* thunk_param =
  296. thunk_function_decl->getParamDecl(thunk_index);
  297. clang::SourceLocation clang_loc = thunk_param->getLocation();
  298. clang::Expr* call_arg = sema.BuildDeclRefExpr(
  299. thunk_param, thunk_param->getType().getNonReferenceType(),
  300. clang::VK_LValue, clang_loc);
  301. if (!type.isNull() && thunk_param->getType() != type) {
  302. // TODO: Consider inserting a cast to an rvalue. Note that we currently
  303. // pass pointers to non-temporary objects as the argument when calling a
  304. // thunk, so we'll need to either change that or generate different thunks
  305. // depending on whether we're moving from each parameter.
  306. clang::ExprResult deref_result =
  307. sema.BuildUnaryOp(nullptr, clang_loc, clang::UO_Deref, call_arg);
  308. CARBON_CHECK(deref_result.isUsable());
  309. call_arg = deref_result.get();
  310. }
  311. return call_arg;
  312. }
  313. // Builds a reference to the parameter thunk parameter corresponding to the
  314. // given callee parameter index.
  315. static auto BuildParamRefForCalleeArg(clang::Sema& sema,
  316. clang::FunctionDecl* thunk_function_decl,
  317. CalleeFunctionInfo callee_info,
  318. unsigned callee_index) -> clang::Expr* {
  319. unsigned thunk_index = callee_info.GetThunkParamIndex(callee_index);
  320. return BuildThunkParamRef(
  321. sema, thunk_function_decl, thunk_index,
  322. callee_info.decl->getParamDecl(callee_index)->getType());
  323. }
  324. // Builds an argument list for the callee function by creating suitable uses of
  325. // the corresponding thunk parameters.
  326. static auto BuildCalleeArgs(clang::Sema& sema,
  327. clang::FunctionDecl* thunk_function_decl,
  328. CalleeFunctionInfo callee_info)
  329. -> llvm::SmallVector<clang::Expr*> {
  330. llvm::SmallVector<clang::Expr*> call_args;
  331. // The object parameter is always passed as `self`, not in the callee argument
  332. // list, so the first argument corresponds to the second parameter if there is
  333. // an explicit object parameter and the first parameter otherwise.
  334. unsigned first_param = callee_info.has_explicit_object_parameter();
  335. unsigned num_params = callee_info.decl->getNumParams();
  336. call_args.reserve(num_params - first_param);
  337. for (unsigned callee_index : llvm::seq(first_param, num_params)) {
  338. call_args.push_back(BuildParamRefForCalleeArg(sema, thunk_function_decl,
  339. callee_info, callee_index));
  340. }
  341. return call_args;
  342. }
  343. // Builds the thunk function body which calls the callee function using the call
  344. // args and returns the callee function return value. Returns nullptr on
  345. // failure.
  346. static auto BuildThunkBody(clang::Sema& sema,
  347. clang::FunctionDecl* thunk_function_decl,
  348. CalleeFunctionInfo callee_info)
  349. -> clang::StmtResult {
  350. // TODO: Consider building a CompoundStmt holding our created statement to
  351. // make our result more closely resemble a real C++ function.
  352. clang::SourceLocation clang_loc = callee_info.decl->getLocation();
  353. // If the callee has an object parameter, build a member access expression as
  354. // the callee. Otherwise, build a regular reference to the function.
  355. clang::ExprResult callee;
  356. if (callee_info.has_object_parameter) {
  357. auto* object_param_ref =
  358. BuildThunkParamRef(sema, thunk_function_decl, 0,
  359. callee_info.has_explicit_object_parameter()
  360. ? callee_info.decl->getParamDecl(0)->getType()
  361. : clang::QualType());
  362. bool is_arrow = callee_info.has_implicit_object_parameter();
  363. auto object =
  364. sema.PerformMemberExprBaseConversion(object_param_ref, is_arrow);
  365. if (object.isInvalid()) {
  366. return clang::StmtError();
  367. }
  368. callee = sema.BuildMemberExpr(
  369. object.get(), is_arrow, clang_loc, clang::NestedNameSpecifierLoc(),
  370. clang::SourceLocation(), callee_info.decl,
  371. clang::DeclAccessPair::make(callee_info.decl, clang::AS_public),
  372. /*HadMultipleCandidates=*/false, clang::DeclarationNameInfo(),
  373. sema.getASTContext().BoundMemberTy, clang::VK_PRValue,
  374. clang::OK_Ordinary);
  375. } else if (!isa<clang::CXXConstructorDecl>(callee_info.decl)) {
  376. callee =
  377. sema.BuildDeclRefExpr(callee_info.decl, callee_info.decl->getType(),
  378. clang::VK_PRValue, clang_loc);
  379. }
  380. if (callee.isInvalid()) {
  381. return clang::StmtError();
  382. }
  383. // Build the argument list.
  384. llvm::SmallVector<clang::Expr*> call_args =
  385. BuildCalleeArgs(sema, thunk_function_decl, callee_info);
  386. clang::ExprResult call;
  387. if (auto info = clang::getConstructorInfo(callee_info.decl);
  388. info.Constructor) {
  389. // In C++, there are no direct calls to constructors, only initialization,
  390. // so we need to type-check and build the call ourselves.
  391. auto type = sema.Context.getRecordType(
  392. cast<clang::CXXRecordDecl>(callee_info.decl->getParent()));
  393. llvm::SmallVector<clang::Expr*> converted_args;
  394. converted_args.reserve(call_args.size());
  395. if (sema.CompleteConstructorCall(info.Constructor, type, call_args,
  396. clang_loc, converted_args)) {
  397. return clang::StmtError();
  398. }
  399. call = sema.BuildCXXConstructExpr(
  400. clang_loc, type, callee_info.decl, info.Constructor, converted_args,
  401. false, false, false, false, clang::CXXConstructionKind::Complete,
  402. clang_loc);
  403. } else {
  404. call = sema.BuildCallExpr(nullptr, callee.get(), clang_loc, call_args,
  405. clang_loc);
  406. }
  407. if (!call.isUsable()) {
  408. return clang::StmtError();
  409. }
  410. if (callee_info.has_simple_return_type) {
  411. return sema.BuildReturnStmt(clang_loc, call.get());
  412. }
  413. auto* return_object_addr = BuildThunkParamRef(
  414. sema, thunk_function_decl, callee_info.GetThunkReturnParamIndex());
  415. auto return_type = callee_info.effective_return_type;
  416. auto* return_type_info =
  417. sema.Context.getTrivialTypeSourceInfo(return_type, clang_loc);
  418. auto placement_new = sema.BuildCXXNew(
  419. clang_loc, /*UseGlobal=*/true, clang_loc, {return_object_addr}, clang_loc,
  420. /*TypeIdParens=*/clang::SourceRange(), return_type, return_type_info,
  421. /*ArraySize=*/std::nullopt, clang_loc, call.get());
  422. return sema.ActOnExprStmt(placement_new, /*DiscardedValue=*/true);
  423. }
  424. auto BuildCppThunk(Context& context, const SemIR::Function& callee_function)
  425. -> clang::FunctionDecl* {
  426. clang::FunctionDecl* callee_function_decl =
  427. context.sem_ir()
  428. .clang_decls()
  429. .Get(callee_function.clang_decl_id)
  430. .decl->getAsFunction();
  431. CARBON_CHECK(callee_function_decl);
  432. CalleeFunctionInfo callee_info(callee_function_decl);
  433. // Build the thunk function declaration.
  434. auto thunk_param_types =
  435. BuildThunkParameterTypes(context.ast_context(), callee_info);
  436. clang::FunctionDecl* thunk_function_decl =
  437. CreateThunkFunctionDecl(context, callee_info, thunk_param_types);
  438. // Build the thunk function body.
  439. clang::Sema& sema = context.sem_ir().clang_ast_unit()->getSema();
  440. clang::Sema::ContextRAII context_raii(sema, thunk_function_decl);
  441. sema.ActOnStartOfFunctionDef(nullptr, thunk_function_decl);
  442. clang::StmtResult body =
  443. BuildThunkBody(sema, thunk_function_decl, callee_info);
  444. sema.ActOnFinishFunctionBody(thunk_function_decl, body.get());
  445. if (body.isInvalid()) {
  446. return nullptr;
  447. }
  448. return thunk_function_decl;
  449. }
  450. auto PerformCppThunkCall(Context& context, SemIR::LocId loc_id,
  451. SemIR::FunctionId callee_function_id,
  452. llvm::ArrayRef<SemIR::InstId> callee_arg_ids,
  453. SemIR::InstId thunk_callee_id) -> SemIR::InstId {
  454. auto& callee_function = context.functions().Get(callee_function_id);
  455. auto callee_function_params =
  456. context.inst_blocks().Get(callee_function.call_params_id);
  457. auto thunk_callee = GetCalleeFunction(context.sem_ir(), thunk_callee_id);
  458. auto& thunk_function = context.functions().Get(thunk_callee.function_id);
  459. auto thunk_function_params =
  460. context.inst_blocks().Get(thunk_function.call_params_id);
  461. // Whether we need to pass a return address to the thunk as a final argument.
  462. bool thunk_takes_return_address =
  463. callee_function.return_slot_pattern_id.has_value() &&
  464. !thunk_function.return_slot_pattern_id.has_value();
  465. // The number of arguments we should be acquiring in order to call the thunk.
  466. // This includes the return address parameter, if any.
  467. unsigned num_thunk_args =
  468. context.inst_blocks().Get(thunk_function.param_patterns_id).size();
  469. // The corresponding number of arguments that would be provided in a syntactic
  470. // call to the callee. This excludes the return slot.
  471. unsigned num_callee_args = num_thunk_args - thunk_takes_return_address;
  472. // Grab the return slot argument, if we were given one.
  473. auto return_slot_id = SemIR::InstId::None;
  474. if (callee_arg_ids.size() == num_callee_args + 1) {
  475. return_slot_id = callee_arg_ids.consume_back();
  476. }
  477. // If there's a return slot pattern, drop the corresponding parameter.
  478. // TODO: The parameter should probably only be created if the return pattern
  479. // actually needs a return address to be passed in.
  480. if (thunk_function.return_slot_pattern_id.has_value()) {
  481. thunk_function_params.consume_back();
  482. }
  483. if (callee_function.return_slot_pattern_id.has_value()) {
  484. callee_function_params.consume_back();
  485. }
  486. // We assume that the call parameters exactly match the parameter patterns for
  487. // both the thunk and the callee. This is currently guaranteed because we only
  488. // create trivial *ParamPatterns when importing a C++ function.
  489. CARBON_CHECK(num_callee_args == callee_function_params.size());
  490. CARBON_CHECK(num_callee_args == callee_arg_ids.size());
  491. CARBON_CHECK(num_thunk_args == thunk_function_params.size());
  492. // Build the thunk arguments by converting the callee arguments as needed.
  493. llvm::SmallVector<SemIR::InstId> thunk_arg_ids;
  494. thunk_arg_ids.reserve(num_thunk_args);
  495. for (auto [callee_param_inst_id, thunk_param_inst_id, callee_arg_id] :
  496. llvm::zip(callee_function_params, thunk_function_params,
  497. callee_arg_ids)) {
  498. SemIR::TypeId callee_param_type_id =
  499. context.insts().GetAs<SemIR::AnyParam>(callee_param_inst_id).type_id;
  500. SemIR::TypeId thunk_param_type_id =
  501. context.insts().GetAs<SemIR::AnyParam>(thunk_param_inst_id).type_id;
  502. SemIR::InstId arg_id = callee_arg_id;
  503. if (callee_param_type_id != thunk_param_type_id) {
  504. arg_id = Convert(context, loc_id, arg_id,
  505. {.kind = ConversionTarget::CppThunkRef,
  506. .type_id = callee_param_type_id});
  507. arg_id = AddInst<SemIR::AddrOf>(
  508. context, loc_id,
  509. {.type_id = GetPointerType(
  510. context, context.types().GetInstId(callee_param_type_id)),
  511. .lvalue_id = arg_id});
  512. arg_id =
  513. ConvertToValueOfType(context, loc_id, arg_id, thunk_param_type_id);
  514. }
  515. thunk_arg_ids.push_back(arg_id);
  516. }
  517. // Add an argument to hold the result of the call, if necessary.
  518. auto return_type_id = callee_function.GetDeclaredReturnType(context.sem_ir());
  519. if (thunk_takes_return_address) {
  520. // Create a temporary if the caller didn't provide a return slot.
  521. if (!return_slot_id.has_value()) {
  522. return_slot_id = AddInstWithCleanup<SemIR::TemporaryStorage>(
  523. context, loc_id, {.type_id = return_type_id});
  524. }
  525. auto arg_id = AddInst<SemIR::AddrOf>(
  526. context, loc_id,
  527. {.type_id = GetPointerType(
  528. context, context.types().GetInstId(
  529. context.insts().Get(return_slot_id).type_id())),
  530. .lvalue_id = return_slot_id});
  531. thunk_arg_ids.push_back(arg_id);
  532. }
  533. auto result_id = PerformCall(context, loc_id, thunk_callee_id, thunk_arg_ids);
  534. // Produce the result of the call, taking the value from the return storage.
  535. if (thunk_takes_return_address) {
  536. result_id = AddInst<SemIR::InPlaceInit>(context, loc_id,
  537. {.type_id = return_type_id,
  538. .src_id = result_id,
  539. .dest_id = return_slot_id});
  540. }
  541. return result_id;
  542. }
  543. } // namespace Carbon::Check