export.cpp 24 KB

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