export.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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/export.h"
  5. #include "llvm/Support/Casting.h"
  6. #include "toolchain/check/cpp/import.h"
  7. #include "toolchain/check/cpp/location.h"
  8. #include "toolchain/check/cpp/type_mapping.h"
  9. #include "toolchain/check/function.h"
  10. #include "toolchain/check/thunk.h"
  11. #include "toolchain/check/type.h"
  12. #include "toolchain/sem_ir/mangler.h"
  13. namespace Carbon::Check {
  14. // If the given name scope was produced by importing a C++ declaration or has
  15. // already been exported to C++, return the corresponding Clang decl context.
  16. static auto GetClangDeclContextForScope(Context& context,
  17. SemIR::NameScopeId scope_id)
  18. -> clang::DeclContext* {
  19. if (!scope_id.has_value()) {
  20. return nullptr;
  21. }
  22. auto& scope = context.name_scopes().Get(scope_id);
  23. auto clang_decl_context_id = scope.clang_decl_context_id();
  24. if (!clang_decl_context_id.has_value()) {
  25. return nullptr;
  26. }
  27. auto* decl = context.clang_decls().Get(clang_decl_context_id).key.decl;
  28. return cast<clang::DeclContext>(decl);
  29. }
  30. auto ExportNameScopeToCpp(Context& context, SemIR::LocId loc_id,
  31. SemIR::NameScopeId name_scope_id)
  32. -> clang::DeclContext* {
  33. llvm::SmallVector<SemIR::NameScopeId> name_scope_ids_to_create;
  34. // Walk through the parent scopes, looking for one that's already mapped into
  35. // C++. We already mapped the package scope to ::Carbon, so we must find one.
  36. clang::DeclContext* decl_context = nullptr;
  37. while (true) {
  38. // If this name scope was produced by importing a C++ declaration or has
  39. // already been exported to C++, return the corresponding Clang declaration.
  40. if (auto* existing_decl_context =
  41. GetClangDeclContextForScope(context, name_scope_id)) {
  42. decl_context = existing_decl_context;
  43. break;
  44. }
  45. // Otherwise, continue to the parent and create a scope for it first.
  46. name_scope_ids_to_create.push_back(name_scope_id);
  47. name_scope_id = context.name_scopes().Get(name_scope_id).parent_scope_id();
  48. // TODO: What should happen if there's an intervening function scope?
  49. CARBON_CHECK(
  50. name_scope_id.has_value(),
  51. "Reached the top level without finding a scope mapped into C++");
  52. }
  53. // Create the name scopes in order, starting from the outermost one.
  54. while (!name_scope_ids_to_create.empty()) {
  55. name_scope_id = name_scope_ids_to_create.pop_back_val();
  56. auto& name_scope = context.name_scopes().Get(name_scope_id);
  57. auto* identifier_info =
  58. GetClangIdentifierInfo(context, name_scope.name_id());
  59. if (!identifier_info) {
  60. // TODO: Handle keyword package names like `Cpp` and `Core`. These can
  61. // be named from C++ via an alias.
  62. context.TODO(loc_id, "interop with non-identifier package name");
  63. return nullptr;
  64. }
  65. auto inst = context.insts().Get(name_scope.inst_id());
  66. if (inst.Is<SemIR::Namespace>()) {
  67. // TODO: Provide a source location.
  68. auto* namespace_decl = clang::NamespaceDecl::Create(
  69. context.ast_context(), decl_context, false, clang::SourceLocation(),
  70. clang::SourceLocation(), identifier_info, nullptr, false);
  71. decl_context->addHiddenDecl(namespace_decl);
  72. decl_context = namespace_decl;
  73. } else if (inst.Is<SemIR::ClassDecl>()) {
  74. // TODO: Provide a source location.
  75. auto* record_decl = clang::CXXRecordDecl::Create(
  76. context.ast_context(), clang::TagTypeKind::Class, decl_context,
  77. clang::SourceLocation(), clang::SourceLocation(), identifier_info);
  78. // If this is a member class, set its access.
  79. if (isa<clang::CXXRecordDecl>(decl_context)) {
  80. // TODO: Map Carbon access to C++ access.
  81. record_decl->setAccess(clang::AS_public);
  82. }
  83. decl_context->addHiddenDecl(record_decl);
  84. decl_context = record_decl;
  85. decl_context->setHasExternalLexicalStorage();
  86. } else {
  87. context.TODO(loc_id, "non-class non-namespace name scope");
  88. return nullptr;
  89. }
  90. decl_context->setHasExternalVisibleStorage();
  91. auto key = SemIR::ClangDeclKey::ForNonFunctionDecl(
  92. cast<clang::Decl>(decl_context));
  93. auto clang_decl_id = context.clang_decls().Add(
  94. {.key = key, .inst_id = name_scope.inst_id()});
  95. name_scope.set_clang_decl_context_id(clang_decl_id, /*is_cpp_scope=*/false);
  96. }
  97. return decl_context;
  98. }
  99. auto ExportClassToCpp(Context& context, SemIR::LocId loc_id,
  100. SemIR::InstId class_inst_id, SemIR::ClassType class_type)
  101. -> clang::TagDecl* {
  102. // TODO: A lot of logic in this function is shared with ExportNameScopeToCpp.
  103. // This should be refactored.
  104. if (class_type.specific_id.has_value()) {
  105. context.TODO(loc_id, "interop with specific class");
  106. return nullptr;
  107. }
  108. const auto& class_info = context.classes().Get(class_type.class_id);
  109. // If this class was produced by importing a C++ declaration or has
  110. // already been exported to C++, return the corresponding Clang declaration.
  111. // That could either be a CXXRecordDecl or an EnumDecl.
  112. if (auto* decl_context =
  113. GetClangDeclContextForScope(context, class_info.scope_id)) {
  114. return cast<clang::TagDecl>(decl_context);
  115. }
  116. auto* identifier_info = GetClangIdentifierInfo(context, class_info.name_id);
  117. CARBON_CHECK(identifier_info, "non-identifier class name {0}",
  118. class_info.name_id);
  119. auto* decl_context =
  120. ExportNameScopeToCpp(context, loc_id, class_info.parent_scope_id);
  121. // TODO: Provide a source location.
  122. auto* record_decl = clang::CXXRecordDecl::Create(
  123. context.ast_context(), clang::TagTypeKind::Class, decl_context,
  124. clang::SourceLocation(), clang::SourceLocation(), identifier_info);
  125. // If this is a member class, set its access.
  126. if (isa<clang::CXXRecordDecl>(decl_context)) {
  127. // TODO: Map Carbon access to C++ access.
  128. record_decl->setAccess(clang::AS_public);
  129. }
  130. record_decl->setHasExternalLexicalStorage();
  131. record_decl->setHasExternalVisibleStorage();
  132. auto key =
  133. SemIR::ClangDeclKey::ForNonFunctionDecl(cast<clang::Decl>(record_decl));
  134. auto clang_decl_id =
  135. context.clang_decls().Add({.key = key, .inst_id = class_inst_id});
  136. if (class_info.scope_id.has_value()) {
  137. // TODO: Record the Carbon class -> clang declaration mapping for incomplete
  138. // classes too.
  139. context.name_scopes()
  140. .Get(class_info.scope_id)
  141. .set_clang_decl_context_id(clang_decl_id, /*is_cpp_scope=*/false);
  142. }
  143. return record_decl;
  144. }
  145. namespace {
  146. struct FunctionInfo {
  147. explicit FunctionInfo(Context& context, SemIR::FunctionId function_id,
  148. const SemIR::Function& function,
  149. clang::DeclContext* decl_context)
  150. : function_id(function_id),
  151. function(function),
  152. decl_context(decl_context) {
  153. auto function_params =
  154. context.inst_blocks().Get(function.call_param_patterns_id);
  155. // Get the function's `self` parameter type, if present.
  156. if (function.call_param_ranges.implicit_size() > 0) {
  157. CARBON_CHECK(function.call_param_ranges.implicit_size() == 1);
  158. auto param_inst_id =
  159. function_params[function.call_param_ranges.implicit_begin().index];
  160. auto scrutinee_type_id = ExtractScrutineeType(
  161. context.sem_ir(), context.insts().Get(param_inst_id).type_id());
  162. self_type_id = scrutinee_type_id;
  163. }
  164. // Get the function's explicit parameter types.
  165. function_params =
  166. function_params.drop_front(function.call_param_ranges.implicit_size());
  167. function_params =
  168. function_params.drop_back(function.call_param_ranges.return_size());
  169. for (auto param_inst_id : function_params) {
  170. auto scrutinee_type_id = ExtractScrutineeType(
  171. context.sem_ir(), context.insts().Get(param_inst_id).type_id());
  172. param_type_ids.push_back(scrutinee_type_id);
  173. }
  174. }
  175. // Get the `StorageClass` to use for `CXXMethodDecl`s.
  176. auto GetStorageClass() const -> clang::StorageClass {
  177. if (has_self()) {
  178. return clang::SC_None;
  179. } else {
  180. return clang::SC_Static;
  181. }
  182. }
  183. // Whether the function has a `self` parameter.
  184. auto has_self() const -> bool { return self_type_id != SemIR::TypeId::None; }
  185. SemIR::FunctionId function_id;
  186. const SemIR::Function& function;
  187. // Parent scope in the C++ AST where a C++ thunk for this function can
  188. // be created. If the function is a method, this will be a
  189. // `CXXRecordDecl`.
  190. clang::DeclContext* decl_context;
  191. // Types of the function's explicit parameters (excludes implicit
  192. // parameters and return parameters).
  193. llvm::SmallVector<SemIR::TypeId> param_type_ids;
  194. // Type of the function's `self` parameter, or `None` if the function
  195. // is not a method.
  196. SemIR::TypeId self_type_id = SemIR::TypeId::None;
  197. };
  198. } // namespace
  199. // Create a `clang::FunctionDecl` for the given Carbon function. This
  200. // can be used to call the Carbon function from C++. The Carbon
  201. // function's ABI must be compatible with C++.
  202. //
  203. // The resulting decl is used to allow a generated C++ function to call
  204. // a generated Carbon function.
  205. static auto BuildCppFunctionDeclForCarbonFn(Context& context,
  206. SemIR::LocId loc_id,
  207. SemIR::FunctionId function_id)
  208. -> clang::FunctionDecl* {
  209. auto clang_loc = GetCppLocation(context, loc_id);
  210. const SemIR::Function& function = context.functions().Get(function_id);
  211. FunctionInfo callee(context, function_id, function, nullptr);
  212. // Get parameters types.
  213. llvm::SmallVector<clang::QualType> cpp_param_types;
  214. if (callee.has_self()) {
  215. auto cpp_type = MapToCppType(context, callee.self_type_id);
  216. if (cpp_type.isNull()) {
  217. context.TODO(loc_id, "failed to map Carbon self type to C++");
  218. return nullptr;
  219. }
  220. cpp_type = context.ast_context().getLValueReferenceType(cpp_type);
  221. cpp_param_types.push_back(cpp_type);
  222. }
  223. for (auto param_type_id : callee.param_type_ids) {
  224. auto cpp_type = MapToCppType(context, param_type_id);
  225. if (cpp_type.isNull()) {
  226. context.TODO(loc_id, "failed to map Carbon type to C++");
  227. return nullptr;
  228. }
  229. auto ref_type = context.ast_context().getLValueReferenceType(cpp_type);
  230. cpp_param_types.push_back(ref_type);
  231. }
  232. CARBON_CHECK(function.return_type_inst_id == SemIR::TypeInstId::None);
  233. auto cpp_return_type = context.ast_context().VoidTy;
  234. auto cpp_function_type = context.ast_context().getFunctionType(
  235. cpp_return_type, cpp_param_types,
  236. clang::FunctionProtoType::ExtProtoInfo());
  237. auto* identifier_info = GetClangIdentifierInfo(context, function.name_id);
  238. CARBON_CHECK(identifier_info, "function with non-identifier name {0}",
  239. function.name_id);
  240. clang::FunctionDecl* function_decl = clang::FunctionDecl::Create(
  241. context.ast_context(), context.ast_context().getTranslationUnitDecl(),
  242. /*StartLoc=*/clang_loc, /*NLoc=*/clang_loc, identifier_info,
  243. cpp_function_type, /*TInfo=*/nullptr, clang::SC_Extern);
  244. // Build parameter decls.
  245. llvm::SmallVector<clang::ParmVarDecl*> param_var_decls;
  246. for (auto [i, type] : llvm::enumerate(cpp_param_types)) {
  247. clang::ParmVarDecl* param = clang::ParmVarDecl::Create(
  248. context.ast_context(), function_decl, /*StartLoc=*/clang_loc,
  249. /*IdLoc=*/clang_loc, /*Id=*/nullptr, type, /*TInfo=*/nullptr,
  250. clang::SC_None, /*DefArg=*/nullptr);
  251. param_var_decls.push_back(param);
  252. }
  253. function_decl->setParams(param_var_decls);
  254. // Mangle the function name and attach it to the `FunctionDecl`.
  255. SemIR::Mangler m(context.sem_ir(), context.total_ir_count());
  256. std::string mangled_name = m.Mangle(function_id, SemIR::SpecificId::None);
  257. function_decl->addAttr(
  258. clang::AsmLabelAttr::Create(context.ast_context(), mangled_name));
  259. return function_decl;
  260. }
  261. // Create the declaration of the C++ thunk.
  262. static auto BuildCppToCarbonThunkDecl(
  263. Context& context, SemIR::LocId loc_id, const FunctionInfo& target,
  264. clang::DeclarationName thunk_name,
  265. llvm::ArrayRef<clang::QualType> thunk_param_types) -> clang::FunctionDecl* {
  266. clang::ASTContext& ast_context = context.ast_context();
  267. auto clang_loc = GetCppLocation(context, loc_id);
  268. // Get the C++ return type (this corresponds to the return type of the
  269. // target Carbon function).
  270. clang::QualType cpp_return_type = context.ast_context().VoidTy;
  271. auto return_type_id = target.function.GetDeclaredReturnType(context.sem_ir());
  272. if (return_type_id != SemIR::TypeId::None) {
  273. cpp_return_type = MapToCppType(context, return_type_id);
  274. if (cpp_return_type.isNull()) {
  275. context.TODO(loc_id, "failed to map Carbon return type to C++ type");
  276. return nullptr;
  277. }
  278. }
  279. clang::DeclarationNameInfo name_info(thunk_name, clang_loc);
  280. auto ext_proto_info = clang::FunctionProtoType::ExtProtoInfo();
  281. clang::QualType thunk_function_type = ast_context.getFunctionType(
  282. cpp_return_type, thunk_param_types, ext_proto_info);
  283. auto* tinfo =
  284. ast_context.getTrivialTypeSourceInfo(thunk_function_type, clang_loc);
  285. bool uses_fp_intrin = false;
  286. bool inline_specified = true;
  287. auto constexpr_kind = clang::ConstexprSpecKind::Unspecified;
  288. auto trailing_requires_clause = clang::AssociatedConstraint();
  289. clang::FunctionDecl* thunk_function_decl = nullptr;
  290. if (auto* parent_class =
  291. dyn_cast<clang::CXXRecordDecl>(target.decl_context)) {
  292. thunk_function_decl = clang::CXXMethodDecl::Create(
  293. ast_context, parent_class, clang_loc, name_info, thunk_function_type,
  294. tinfo, target.GetStorageClass(), uses_fp_intrin, inline_specified,
  295. constexpr_kind, clang_loc, trailing_requires_clause);
  296. // TODO: Map Carbon access to C++ access.
  297. thunk_function_decl->setAccess(clang::AS_public);
  298. } else {
  299. thunk_function_decl = clang::FunctionDecl::Create(
  300. ast_context, target.decl_context, clang_loc, name_info,
  301. thunk_function_type, tinfo, clang::SC_None, uses_fp_intrin,
  302. inline_specified,
  303. /*hasWrittenPrototype=*/true, constexpr_kind, trailing_requires_clause);
  304. }
  305. target.decl_context->addHiddenDecl(thunk_function_decl);
  306. llvm::SmallVector<clang::ParmVarDecl*> param_var_decls;
  307. for (auto [i, type] : llvm::enumerate(thunk_param_types)) {
  308. clang::ParmVarDecl* thunk_param = clang::ParmVarDecl::Create(
  309. ast_context, thunk_function_decl, /*StartLoc=*/clang_loc,
  310. /*IdLoc=*/clang_loc, /*Id=*/nullptr, type,
  311. /*TInfo=*/nullptr, clang::SC_None, /*DefArg=*/nullptr);
  312. param_var_decls.push_back(thunk_param);
  313. }
  314. thunk_function_decl->setParams(param_var_decls);
  315. // Force the thunk to be inlined and discarded.
  316. thunk_function_decl->addAttr(
  317. clang::AlwaysInlineAttr::CreateImplicit(ast_context));
  318. thunk_function_decl->addAttr(
  319. clang::InternalLinkageAttr::CreateImplicit(ast_context));
  320. return thunk_function_decl;
  321. }
  322. // Create the body of a C++ thunk that calls a Carbon thunk. The
  323. // arguments are passed by reference to the callee.
  324. static auto BuildCppToCarbonThunkBody(clang::Sema& sema,
  325. const FunctionInfo& target,
  326. clang::FunctionDecl* function_decl,
  327. clang::FunctionDecl* callee_function_decl)
  328. -> clang::StmtResult {
  329. clang::SourceLocation clang_loc = function_decl->getLocation();
  330. llvm::SmallVector<clang::Stmt*> stmts;
  331. // Create return storage if the target function returns non-void.
  332. const bool has_return_value = !function_decl->getReturnType()->isVoidType();
  333. clang::VarDecl* return_storage_var_decl = nullptr;
  334. clang::ExprResult return_storage_expr;
  335. if (has_return_value) {
  336. auto& return_storage_ident =
  337. sema.getASTContext().Idents.get("return_storage");
  338. return_storage_var_decl =
  339. clang::VarDecl::Create(sema.getASTContext(), function_decl,
  340. /*StartLoc=*/clang_loc,
  341. /*IdLoc=*/clang_loc, &return_storage_ident,
  342. function_decl->getReturnType(),
  343. /*TInfo=*/nullptr, clang::SC_None);
  344. return_storage_var_decl->setNRVOVariable(true);
  345. return_storage_expr = sema.BuildDeclRefExpr(
  346. return_storage_var_decl, return_storage_var_decl->getType(),
  347. clang::VK_LValue, clang_loc);
  348. auto decl_group_ref = clang::DeclGroupRef(return_storage_var_decl);
  349. auto decl_stmt =
  350. sema.ActOnDeclStmt(clang::Sema::DeclGroupPtrTy::make(decl_group_ref),
  351. clang_loc, clang_loc);
  352. stmts.push_back(decl_stmt.get());
  353. }
  354. clang::ExprResult callee = sema.BuildDeclRefExpr(
  355. callee_function_decl, callee_function_decl->getType(), clang::VK_PRValue,
  356. clang_loc);
  357. llvm::SmallVector<clang::Expr*> call_args;
  358. // For methods, pass the `this` pointer as the first argument to the callee.
  359. if (target.has_self()) {
  360. auto* parent_class = cast<clang::CXXRecordDecl>(target.decl_context);
  361. clang::QualType class_type =
  362. sema.getASTContext().getCanonicalTagType(parent_class);
  363. auto class_ptr_type = sema.getASTContext().getPointerType(class_type);
  364. auto* this_expr = sema.BuildCXXThisExpr(clang_loc, class_ptr_type,
  365. /*IsImplicit=*/true);
  366. this_expr = clang::UnaryOperator::Create(
  367. sema.getASTContext(), this_expr, clang::UO_Deref, class_type,
  368. clang::ExprValueKind::VK_LValue, clang::ExprObjectKind::OK_Ordinary,
  369. clang_loc, /*CanOverflow=*/false, clang::FPOptionsOverride());
  370. call_args.push_back(this_expr);
  371. }
  372. for (auto* param : function_decl->parameters()) {
  373. clang::Expr* call_arg =
  374. sema.BuildDeclRefExpr(param, param->getType().getNonReferenceType(),
  375. clang::VK_LValue, clang_loc);
  376. call_args.push_back(call_arg);
  377. }
  378. // If the target function returns non-void, the Carbon thunk takes an
  379. // extra output parameter referencing the return storage.
  380. if (has_return_value) {
  381. call_args.push_back(return_storage_expr.get());
  382. }
  383. clang::ExprResult call = sema.BuildCallExpr(nullptr, callee.get(), clang_loc,
  384. call_args, clang_loc);
  385. CARBON_CHECK(call.isUsable());
  386. stmts.push_back(call.get());
  387. if (has_return_value) {
  388. auto* return_stmt = clang::ReturnStmt::Create(
  389. sema.getASTContext(), clang_loc, return_storage_expr.get(),
  390. return_storage_var_decl);
  391. stmts.push_back(return_stmt);
  392. }
  393. return clang::CompoundStmt::Create(sema.getASTContext(), stmts,
  394. clang::FPOptionsOverride(), clang_loc,
  395. clang_loc);
  396. }
  397. // Create a C++ thunk that calls the Carbon thunk. The C++ thunk's
  398. // parameter types are mapped from the parameters of the target function
  399. // with `MapToCppType`. (Note that the target function here is the
  400. // callee of the Carbon thunk.)
  401. static auto BuildCppToCarbonThunk(Context& context, SemIR::LocId loc_id,
  402. const FunctionInfo& target,
  403. llvm::StringRef thunk_name,
  404. clang::FunctionDecl* carbon_function_decl)
  405. -> clang::FunctionDecl* {
  406. auto& thunk_ident = context.ast_context().Idents.get(thunk_name);
  407. llvm::SmallVector<clang::QualType> param_types;
  408. for (auto type_id : target.param_type_ids) {
  409. auto cpp_type = MapToCppType(context, type_id);
  410. if (cpp_type.isNull()) {
  411. context.TODO(loc_id, "failed to map C++ type to Carbon");
  412. return nullptr;
  413. }
  414. param_types.push_back(cpp_type);
  415. }
  416. auto* thunk_function_decl = BuildCppToCarbonThunkDecl(
  417. context, loc_id, target, &thunk_ident, param_types);
  418. // Build the thunk function body.
  419. clang::Sema& sema = context.clang_sema();
  420. clang::Sema::ContextRAII context_raii(sema, thunk_function_decl);
  421. sema.ActOnStartOfFunctionDef(nullptr, thunk_function_decl);
  422. clang::StmtResult body = BuildCppToCarbonThunkBody(
  423. sema, target, thunk_function_decl, carbon_function_decl);
  424. sema.ActOnFinishFunctionBody(thunk_function_decl, body.get());
  425. CARBON_CHECK(!body.isInvalid());
  426. context.clang_sema().getASTConsumer().HandleTopLevelDecl(
  427. clang::DeclGroupRef(thunk_function_decl));
  428. return thunk_function_decl;
  429. }
  430. // Create a Carbon thunk that calls `callee`. The thunk's parameters are
  431. // all references to the callee parameter type.
  432. static auto BuildCarbonToCarbonThunk(Context& context, SemIR::LocId loc_id,
  433. const FunctionInfo& target)
  434. -> SemIR::FunctionId {
  435. // Create the thunk's name.
  436. llvm::SmallString<64> thunk_name =
  437. context.names().GetFormatted(target.function.name_id);
  438. thunk_name += "__carbon_thunk";
  439. auto& ident = context.ast_context().Idents.get(thunk_name);
  440. auto thunk_name_id =
  441. SemIR::NameId::ForIdentifier(context.identifiers().Add(ident.getName()));
  442. // Get the thunk's parameters. These match the callee parameters, with
  443. // the addition of an output parameter for the callee's return value
  444. // (if it has one).
  445. llvm::SmallVector<SemIR::TypeId> thunk_param_type_ids(target.param_type_ids);
  446. auto callee_return_type_id =
  447. target.function.GetDeclaredReturnType(context.sem_ir());
  448. if (callee_return_type_id != SemIR::TypeId::None) {
  449. thunk_param_type_ids.push_back(callee_return_type_id);
  450. }
  451. auto carbon_thunk_function_id =
  452. MakeGeneratedFunctionDecl(
  453. context, loc_id,
  454. {.parent_scope_id = target.function.parent_scope_id,
  455. .name_id = thunk_name_id,
  456. .self_type_id = target.self_type_id,
  457. .param_type_ids = thunk_param_type_ids,
  458. .params_are_refs = true})
  459. .second;
  460. BuildThunkDefinitionForExport(
  461. context, carbon_thunk_function_id, target.function_id,
  462. context.functions().Get(carbon_thunk_function_id).first_decl_id(),
  463. target.function.first_decl_id());
  464. return carbon_thunk_function_id;
  465. }
  466. auto ExportFunctionToCpp(Context& context, SemIR::LocId loc_id,
  467. SemIR::FunctionId callee_function_id)
  468. -> clang::FunctionDecl* {
  469. const SemIR::Function& callee = context.functions().Get(callee_function_id);
  470. if (callee.generic_id.has_value()) {
  471. context.TODO(loc_id,
  472. "unsupported: C++ calling a Carbon function with "
  473. "generic parameters");
  474. return nullptr;
  475. }
  476. // Map the parent scope into the C++ AST.
  477. auto* decl_context =
  478. ExportNameScopeToCpp(context, loc_id, callee.parent_scope_id);
  479. if (!decl_context) {
  480. return nullptr;
  481. }
  482. FunctionInfo target_function_info(context, callee_function_id, callee,
  483. decl_context);
  484. // Create a Carbon thunk that calls the callee. The thunk's parameters
  485. // are all references so that the ABI is compatible with C++ callers.
  486. auto carbon_thunk_function_id =
  487. BuildCarbonToCarbonThunk(context, loc_id, target_function_info);
  488. // Create a `clang::FunctionDecl` that can be used to call the Carbon thunk.
  489. auto* carbon_function_decl = BuildCppFunctionDeclForCarbonFn(
  490. context, loc_id, carbon_thunk_function_id);
  491. if (!carbon_function_decl) {
  492. return nullptr;
  493. }
  494. // Create a C++ thunk that calls the Carbon thunk.
  495. return BuildCppToCarbonThunk(context, loc_id, target_function_info,
  496. context.names().GetFormatted(callee.name_id),
  497. carbon_function_decl);
  498. }
  499. } // namespace Carbon::Check