export.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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. // Get the `StructTypeField`s from a class's object repr.
  147. static auto GetStructTypeFields(Context& context,
  148. const SemIR::Class& class_info)
  149. -> llvm::ArrayRef<SemIR::StructTypeField> {
  150. if (class_info.adapt_id.has_value()) {
  151. // The representation of an adapter won't necessarily be a
  152. // struct. Return an empty array since adapters can't declare
  153. // fields.
  154. return {};
  155. }
  156. auto object_repr_type_id =
  157. class_info.GetObjectRepr(context.sem_ir(), SemIR::SpecificId::None);
  158. auto struct_type =
  159. context.types().GetAs<SemIR::StructType>(object_repr_type_id);
  160. return context.struct_type_fields().Get(struct_type.fields_id);
  161. }
  162. static auto LookupClassFieldByStructField(
  163. const Context& context, const SemIR::NameScope& class_scope,
  164. const SemIR::StructTypeField& struct_field)
  165. -> std::optional<SemIR::InstStore::GetAsWithIdResult<SemIR::FieldDecl>> {
  166. if (auto entry_id = class_scope.Lookup(struct_field.name_id)) {
  167. auto field_inst_id =
  168. class_scope.GetEntry(*entry_id).result.target_inst_id();
  169. return context.insts().TryGetAsWithId<SemIR::FieldDecl>(field_inst_id);
  170. }
  171. return std::nullopt;
  172. }
  173. // Creates a `clang::FieldDecl` for a Carbon class field. Returns
  174. // nullptr if an error occurs.
  175. static auto CreateCppFieldDecl(Context& context,
  176. clang::CXXRecordDecl* record_decl,
  177. SemIR::InstId field_inst_id,
  178. const SemIR::FieldDecl& field_decl)
  179. -> clang::FieldDecl* {
  180. // Get the field's C++ type.
  181. auto unbound_element_type =
  182. context.types().GetAs<SemIR::UnboundElementType>(field_decl.type_id);
  183. auto cpp_type =
  184. MapToCppType(context, context.types().GetTypeIdForTypeInstId(
  185. unbound_element_type.element_type_inst_id));
  186. if (cpp_type.isNull()) {
  187. context.TODO(field_inst_id, "failed to map Carbon type to C++");
  188. return nullptr;
  189. }
  190. // Get the field's C++ identifier.
  191. auto* identifier_info = GetClangIdentifierInfo(context, field_decl.name_id);
  192. CARBON_CHECK(identifier_info, "field with non-identifier name {0}",
  193. field_decl.name_id);
  194. // Create the `clang::FieldDecl`.
  195. auto clang_loc = GetCppLocation(context, SemIR::LocId(field_inst_id));
  196. auto* cpp_field_decl = clang::FieldDecl::Create(
  197. context.ast_context(), record_decl, /*StartLoc=*/clang_loc,
  198. /*IdLoc=*/clang_loc, identifier_info, cpp_type, /*TInfo=*/nullptr,
  199. /*BW=*/nullptr,
  200. /*Mutable=*/true, clang::ICIS_NoInit);
  201. cpp_field_decl->setAccess(clang::AS_public);
  202. record_decl->addHiddenDecl(cpp_field_decl);
  203. return cpp_field_decl;
  204. }
  205. auto ExportAllFieldsToCpp(Context& context, SemIR::Class& class_info) -> void {
  206. if (class_info.fields_exported) {
  207. return;
  208. }
  209. const auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  210. for (const auto& struct_field : GetStructTypeFields(context, class_info)) {
  211. auto class_field =
  212. LookupClassFieldByStructField(context, class_scope, struct_field);
  213. if (!class_field) {
  214. continue;
  215. }
  216. // Map the parent scope into the C++ AST.
  217. auto* decl_context = ExportNameScopeToCpp(
  218. context, SemIR::LocId(class_field->inst_id), class_info.scope_id);
  219. if (!decl_context) {
  220. continue;
  221. }
  222. auto* cpp_field_decl =
  223. CreateCppFieldDecl(context, cast<clang::CXXRecordDecl>(decl_context),
  224. class_field->inst_id, class_field->inst);
  225. if (!cpp_field_decl) {
  226. continue;
  227. }
  228. // Create and store the `ClangDeclId`.
  229. auto key = SemIR::ClangDeclKey::ForNonFunctionDecl(cpp_field_decl);
  230. context.clang_decls().Add({.key = key, .inst_id = class_field->inst_id});
  231. }
  232. class_info.fields_exported = true;
  233. }
  234. auto ExportFieldToCpp(Context& context, SemIR::InstId field_inst_id,
  235. SemIR::FieldDecl field_decl) -> clang::FieldDecl* {
  236. // Get the `SemIR::Class` that contains the `field_decl`.
  237. auto unbound_element_type =
  238. context.types().GetAs<SemIR::UnboundElementType>(field_decl.type_id);
  239. SemIR::TypeId class_type_id = context.types().GetTypeIdForTypeInstId(
  240. unbound_element_type.class_type_inst_id);
  241. auto class_type = context.types().GetAs<SemIR::ClassType>(class_type_id);
  242. auto& class_info = context.classes().Get(class_type.class_id);
  243. // If the class's fields haven't already been exported, do so now.
  244. ExportAllFieldsToCpp(context, class_info);
  245. // Get the exported `clang::FieldDecl`.
  246. auto clang_decl_id = context.clang_decls().Lookup(field_inst_id);
  247. if (clang_decl_id == SemIR::ClangDeclId::None) {
  248. return nullptr;
  249. }
  250. return cast<clang::FieldDecl>(
  251. context.clang_decls().Get(clang_decl_id).key.decl);
  252. }
  253. auto CalculateCppFieldOffsets(
  254. Context& context, SemIR::ClassId class_id,
  255. llvm::DenseMap<const clang::FieldDecl*, uint64_t>& field_offsets) -> bool {
  256. auto class_info = context.classes().Get(class_id);
  257. const auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  258. auto class_layout = SemIR::ObjectLayout::Empty();
  259. for (const auto& struct_field : GetStructTypeFields(context, class_info)) {
  260. auto field_type_id = context.sem_ir().types().GetTypeIdForTypeInstId(
  261. struct_field.type_inst_id);
  262. auto field_layout = context.sem_ir()
  263. .types()
  264. .GetCompleteTypeInfo(field_type_id)
  265. .object_layout;
  266. // Use the field's name to look up the corresponding entry in the
  267. // class. If it's a `FieldDecl`, write out the offset of the
  268. // corresponding `clang::FieldDecl`.
  269. auto class_field =
  270. LookupClassFieldByStructField(context, class_scope, struct_field);
  271. if (class_field) {
  272. auto* cpp_field_decl =
  273. ExportFieldToCpp(context, class_field->inst_id, class_field->inst);
  274. if (!cpp_field_decl) {
  275. return false;
  276. }
  277. field_offsets.insert(
  278. {cpp_field_decl, class_layout.FieldOffset(field_layout).bits()});
  279. }
  280. class_layout.AppendField(field_layout);
  281. }
  282. return true;
  283. }
  284. namespace {
  285. struct FunctionInfo {
  286. struct Param {
  287. // Type of the parameter's scrutinee.
  288. SemIR::TypeId type_id;
  289. // Whether this is a `ref` param.
  290. bool is_ref;
  291. };
  292. explicit FunctionInfo(Context& context, SemIR::FunctionId function_id,
  293. const SemIR::Function& function,
  294. clang::DeclContext* decl_context)
  295. : function_id(function_id),
  296. function(function),
  297. decl_context(decl_context) {
  298. auto function_params =
  299. context.inst_blocks().Get(function.call_param_patterns_id);
  300. // Get the function's `self` parameter type, if present.
  301. if (function.call_param_ranges.implicit_size() > 0) {
  302. CARBON_CHECK(function.call_param_ranges.implicit_size() == 1);
  303. auto param_inst_id =
  304. function_params[function.call_param_ranges.implicit_begin().index];
  305. auto scrutinee_type_id = ExtractScrutineeType(
  306. context.sem_ir(), context.insts().Get(param_inst_id).type_id());
  307. self_type_id = scrutinee_type_id;
  308. }
  309. // Get the function's explicit parameters.
  310. function_params =
  311. function_params.drop_front(function.call_param_ranges.implicit_size());
  312. function_params =
  313. function_params.drop_back(function.call_param_ranges.return_size());
  314. for (auto param_inst_id : function_params) {
  315. explicit_params.push_back(
  316. {.type_id = ExtractScrutineeType(
  317. context.sem_ir(), context.insts().Get(param_inst_id).type_id()),
  318. .is_ref =
  319. context.insts().Is<SemIR::RefParamPattern>(param_inst_id)});
  320. }
  321. }
  322. // Get the `StorageClass` to use for `CXXMethodDecl`s.
  323. auto GetStorageClass() const -> clang::StorageClass {
  324. if (has_self()) {
  325. return clang::SC_None;
  326. } else {
  327. return clang::SC_Static;
  328. }
  329. }
  330. // Whether the function has a `self` parameter.
  331. auto has_self() const -> bool { return self_type_id != SemIR::TypeId::None; }
  332. SemIR::FunctionId function_id;
  333. const SemIR::Function& function;
  334. // Parent scope in the C++ AST where a C++ thunk for this function can
  335. // be created. If the function is a method, this will be a
  336. // `CXXRecordDecl`.
  337. clang::DeclContext* decl_context;
  338. // For each of the function's explicit parameters, the scrutinee type
  339. // and whether the parameter is a reference.
  340. llvm::SmallVector<Param> explicit_params;
  341. // Type of the function's `self` parameter, or `None` if the function
  342. // is not a method.
  343. SemIR::TypeId self_type_id = SemIR::TypeId::None;
  344. };
  345. } // namespace
  346. // Create a `clang::FunctionDecl` for the given Carbon function. This
  347. // can be used to call the Carbon function from C++. The Carbon
  348. // function's ABI must be compatible with C++.
  349. //
  350. // The resulting decl is used to allow a generated C++ function to call
  351. // a generated Carbon function.
  352. static auto BuildCppFunctionDeclForCarbonFn(Context& context,
  353. SemIR::LocId loc_id,
  354. SemIR::FunctionId function_id)
  355. -> clang::FunctionDecl* {
  356. auto clang_loc = GetCppLocation(context, loc_id);
  357. const SemIR::Function& function = context.functions().Get(function_id);
  358. FunctionInfo callee(context, function_id, function, nullptr);
  359. // Get parameters types.
  360. llvm::SmallVector<clang::QualType> cpp_param_types;
  361. if (callee.has_self()) {
  362. auto cpp_type = MapToCppType(context, callee.self_type_id);
  363. if (cpp_type.isNull()) {
  364. context.TODO(loc_id, "failed to map Carbon self type to C++");
  365. return nullptr;
  366. }
  367. cpp_type = context.ast_context().getLValueReferenceType(cpp_type);
  368. cpp_param_types.push_back(cpp_type);
  369. }
  370. for (auto param : callee.explicit_params) {
  371. auto cpp_type = MapToCppType(context, param.type_id);
  372. if (cpp_type.isNull()) {
  373. context.TODO(loc_id, "failed to map Carbon type to C++");
  374. return nullptr;
  375. }
  376. auto ref_type = context.ast_context().getLValueReferenceType(cpp_type);
  377. cpp_param_types.push_back(ref_type);
  378. }
  379. CARBON_CHECK(function.return_type_inst_id == SemIR::TypeInstId::None);
  380. auto cpp_return_type = context.ast_context().VoidTy;
  381. auto cpp_function_type = context.ast_context().getFunctionType(
  382. cpp_return_type, cpp_param_types,
  383. clang::FunctionProtoType::ExtProtoInfo());
  384. auto* identifier_info = GetClangIdentifierInfo(context, function.name_id);
  385. CARBON_CHECK(identifier_info, "function with non-identifier name {0}",
  386. function.name_id);
  387. clang::FunctionDecl* function_decl = clang::FunctionDecl::Create(
  388. context.ast_context(), context.ast_context().getTranslationUnitDecl(),
  389. /*StartLoc=*/clang_loc, /*NLoc=*/clang_loc, identifier_info,
  390. cpp_function_type, /*TInfo=*/nullptr, clang::SC_Extern);
  391. // Build parameter decls.
  392. llvm::SmallVector<clang::ParmVarDecl*> param_var_decls;
  393. for (auto [i, type] : llvm::enumerate(cpp_param_types)) {
  394. clang::ParmVarDecl* param = clang::ParmVarDecl::Create(
  395. context.ast_context(), function_decl, /*StartLoc=*/clang_loc,
  396. /*IdLoc=*/clang_loc, /*Id=*/nullptr, type, /*TInfo=*/nullptr,
  397. clang::SC_None, /*DefArg=*/nullptr);
  398. param_var_decls.push_back(param);
  399. }
  400. function_decl->setParams(param_var_decls);
  401. // Mangle the function name and attach it to the `FunctionDecl`.
  402. SemIR::Mangler m(context.sem_ir(), context.total_ir_count());
  403. std::string mangled_name = m.Mangle(function_id, SemIR::SpecificId::None);
  404. function_decl->addAttr(
  405. clang::AsmLabelAttr::Create(context.ast_context(), mangled_name));
  406. return function_decl;
  407. }
  408. // Create the declaration of the C++ thunk.
  409. static auto BuildCppToCarbonThunkDecl(
  410. Context& context, SemIR::LocId loc_id, const FunctionInfo& target,
  411. clang::DeclarationName thunk_name,
  412. llvm::ArrayRef<clang::QualType> thunk_param_types) -> clang::FunctionDecl* {
  413. clang::ASTContext& ast_context = context.ast_context();
  414. auto clang_loc = GetCppLocation(context, loc_id);
  415. // Get the C++ return type (this corresponds to the return type of the
  416. // target Carbon function).
  417. clang::QualType cpp_return_type = context.ast_context().VoidTy;
  418. auto return_type_id = target.function.GetDeclaredReturnType(context.sem_ir());
  419. if (return_type_id != SemIR::TypeId::None) {
  420. cpp_return_type = MapToCppType(context, return_type_id);
  421. if (cpp_return_type.isNull()) {
  422. context.TODO(loc_id, "failed to map Carbon return type to C++ type");
  423. return nullptr;
  424. }
  425. }
  426. clang::DeclarationNameInfo name_info(thunk_name, clang_loc);
  427. auto ext_proto_info = clang::FunctionProtoType::ExtProtoInfo();
  428. clang::QualType thunk_function_type = ast_context.getFunctionType(
  429. cpp_return_type, thunk_param_types, ext_proto_info);
  430. auto* tinfo =
  431. ast_context.getTrivialTypeSourceInfo(thunk_function_type, clang_loc);
  432. bool uses_fp_intrin = false;
  433. bool inline_specified = true;
  434. auto constexpr_kind = clang::ConstexprSpecKind::Unspecified;
  435. auto trailing_requires_clause = clang::AssociatedConstraint();
  436. clang::FunctionDecl* thunk_function_decl = nullptr;
  437. if (auto* parent_class =
  438. dyn_cast<clang::CXXRecordDecl>(target.decl_context)) {
  439. thunk_function_decl = clang::CXXMethodDecl::Create(
  440. ast_context, parent_class, clang_loc, name_info, thunk_function_type,
  441. tinfo, target.GetStorageClass(), uses_fp_intrin, inline_specified,
  442. constexpr_kind, clang_loc, trailing_requires_clause);
  443. // TODO: Map Carbon access to C++ access.
  444. thunk_function_decl->setAccess(clang::AS_public);
  445. } else {
  446. thunk_function_decl = clang::FunctionDecl::Create(
  447. ast_context, target.decl_context, clang_loc, name_info,
  448. thunk_function_type, tinfo, clang::SC_None, uses_fp_intrin,
  449. inline_specified,
  450. /*hasWrittenPrototype=*/true, constexpr_kind, trailing_requires_clause);
  451. }
  452. target.decl_context->addHiddenDecl(thunk_function_decl);
  453. llvm::SmallVector<clang::ParmVarDecl*> param_var_decls;
  454. for (auto [i, type] : llvm::enumerate(thunk_param_types)) {
  455. clang::ParmVarDecl* thunk_param = clang::ParmVarDecl::Create(
  456. ast_context, thunk_function_decl, /*StartLoc=*/clang_loc,
  457. /*IdLoc=*/clang_loc, /*Id=*/nullptr, type,
  458. /*TInfo=*/nullptr, clang::SC_None, /*DefArg=*/nullptr);
  459. param_var_decls.push_back(thunk_param);
  460. }
  461. thunk_function_decl->setParams(param_var_decls);
  462. // Force the thunk to be inlined and discarded.
  463. thunk_function_decl->addAttr(
  464. clang::AlwaysInlineAttr::CreateImplicit(ast_context));
  465. thunk_function_decl->addAttr(
  466. clang::InternalLinkageAttr::CreateImplicit(ast_context));
  467. return thunk_function_decl;
  468. }
  469. // Create the body of a C++ thunk that calls a Carbon thunk. The
  470. // arguments are passed by reference to the callee.
  471. static auto BuildCppToCarbonThunkBody(clang::Sema& sema,
  472. const FunctionInfo& target,
  473. clang::FunctionDecl* function_decl,
  474. clang::FunctionDecl* callee_function_decl)
  475. -> clang::StmtResult {
  476. clang::SourceLocation clang_loc = function_decl->getLocation();
  477. llvm::SmallVector<clang::Stmt*> stmts;
  478. // Create return storage if the target function returns non-void.
  479. const bool has_return_value = !function_decl->getReturnType()->isVoidType();
  480. clang::VarDecl* return_storage_var_decl = nullptr;
  481. clang::ExprResult return_storage_expr;
  482. if (has_return_value) {
  483. auto& return_storage_ident =
  484. sema.getASTContext().Idents.get("return_storage");
  485. return_storage_var_decl =
  486. clang::VarDecl::Create(sema.getASTContext(), function_decl,
  487. /*StartLoc=*/clang_loc,
  488. /*IdLoc=*/clang_loc, &return_storage_ident,
  489. function_decl->getReturnType(),
  490. /*TInfo=*/nullptr, clang::SC_None);
  491. return_storage_var_decl->setNRVOVariable(true);
  492. return_storage_expr = sema.BuildDeclRefExpr(
  493. return_storage_var_decl, return_storage_var_decl->getType(),
  494. clang::VK_LValue, clang_loc);
  495. auto decl_group_ref = clang::DeclGroupRef(return_storage_var_decl);
  496. auto decl_stmt =
  497. sema.ActOnDeclStmt(clang::Sema::DeclGroupPtrTy::make(decl_group_ref),
  498. clang_loc, clang_loc);
  499. stmts.push_back(decl_stmt.get());
  500. }
  501. clang::ExprResult callee = sema.BuildDeclRefExpr(
  502. callee_function_decl, callee_function_decl->getType(), clang::VK_PRValue,
  503. clang_loc);
  504. llvm::SmallVector<clang::Expr*> call_args;
  505. // For methods, pass the `this` pointer as the first argument to the callee.
  506. if (target.has_self()) {
  507. auto* parent_class = cast<clang::CXXRecordDecl>(target.decl_context);
  508. clang::QualType class_type =
  509. sema.getASTContext().getCanonicalTagType(parent_class);
  510. auto class_ptr_type = sema.getASTContext().getPointerType(class_type);
  511. auto* this_expr = sema.BuildCXXThisExpr(clang_loc, class_ptr_type,
  512. /*IsImplicit=*/true);
  513. this_expr = clang::UnaryOperator::Create(
  514. sema.getASTContext(), this_expr, clang::UO_Deref, class_type,
  515. clang::ExprValueKind::VK_LValue, clang::ExprObjectKind::OK_Ordinary,
  516. clang_loc, /*CanOverflow=*/false, clang::FPOptionsOverride());
  517. call_args.push_back(this_expr);
  518. }
  519. for (auto* param : function_decl->parameters()) {
  520. clang::Expr* call_arg =
  521. sema.BuildDeclRefExpr(param, param->getType().getNonReferenceType(),
  522. clang::VK_LValue, clang_loc);
  523. call_args.push_back(call_arg);
  524. }
  525. // If the target function returns non-void, the Carbon thunk takes an
  526. // extra output parameter referencing the return storage.
  527. if (has_return_value) {
  528. call_args.push_back(return_storage_expr.get());
  529. }
  530. clang::ExprResult call = sema.BuildCallExpr(nullptr, callee.get(), clang_loc,
  531. call_args, clang_loc);
  532. CARBON_CHECK(call.isUsable());
  533. stmts.push_back(call.get());
  534. if (has_return_value) {
  535. auto* return_stmt = clang::ReturnStmt::Create(
  536. sema.getASTContext(), clang_loc, return_storage_expr.get(),
  537. return_storage_var_decl);
  538. stmts.push_back(return_stmt);
  539. }
  540. return clang::CompoundStmt::Create(sema.getASTContext(), stmts,
  541. clang::FPOptionsOverride(), clang_loc,
  542. clang_loc);
  543. }
  544. // Create a C++ thunk that calls the Carbon thunk. The C++ thunk's
  545. // parameter types are mapped from the parameters of the target function
  546. // with `MapToCppType`. (Note that the target function here is the
  547. // callee of the Carbon thunk.)
  548. static auto BuildCppToCarbonThunk(Context& context, SemIR::LocId loc_id,
  549. const FunctionInfo& target,
  550. llvm::StringRef thunk_name,
  551. clang::FunctionDecl* carbon_function_decl)
  552. -> clang::FunctionDecl* {
  553. auto& thunk_ident = context.ast_context().Idents.get(thunk_name);
  554. llvm::SmallVector<clang::QualType> param_types;
  555. for (auto param : target.explicit_params) {
  556. auto cpp_type = MapToCppType(context, param.type_id);
  557. if (cpp_type.isNull()) {
  558. context.TODO(loc_id, "failed to map C++ type to Carbon");
  559. return nullptr;
  560. }
  561. if (param.is_ref) {
  562. cpp_type = context.ast_context().getLValueReferenceType(cpp_type);
  563. }
  564. param_types.push_back(cpp_type);
  565. }
  566. auto* thunk_function_decl = BuildCppToCarbonThunkDecl(
  567. context, loc_id, target, &thunk_ident, param_types);
  568. // Build the thunk function body.
  569. clang::Sema& sema = context.clang_sema();
  570. clang::Sema::ContextRAII context_raii(sema, thunk_function_decl);
  571. sema.ActOnStartOfFunctionDef(nullptr, thunk_function_decl);
  572. clang::StmtResult body = BuildCppToCarbonThunkBody(
  573. sema, target, thunk_function_decl, carbon_function_decl);
  574. sema.ActOnFinishFunctionBody(thunk_function_decl, body.get());
  575. CARBON_CHECK(!body.isInvalid());
  576. context.clang_sema().getASTConsumer().HandleTopLevelDecl(
  577. clang::DeclGroupRef(thunk_function_decl));
  578. return thunk_function_decl;
  579. }
  580. // Create a Carbon thunk that calls `callee`. The thunk's parameters are
  581. // all references to the callee parameter type.
  582. static auto BuildCarbonToCarbonThunk(Context& context, SemIR::LocId loc_id,
  583. const FunctionInfo& target)
  584. -> SemIR::FunctionId {
  585. // Create the thunk's name.
  586. llvm::SmallString<64> thunk_name =
  587. context.names().GetFormatted(target.function.name_id);
  588. thunk_name += "__carbon_thunk";
  589. auto& ident = context.ast_context().Idents.get(thunk_name);
  590. auto thunk_name_id =
  591. SemIR::NameId::ForIdentifier(context.identifiers().Add(ident.getName()));
  592. // Get the thunk's parameters. These match the callee parameters, with
  593. // the addition of an output parameter for the callee's return value
  594. // (if it has one).
  595. llvm::SmallVector<SemIR::TypeId> thunk_param_type_ids;
  596. for (const auto& param : target.explicit_params) {
  597. thunk_param_type_ids.push_back(param.type_id);
  598. }
  599. auto callee_return_type_id =
  600. target.function.GetDeclaredReturnType(context.sem_ir());
  601. if (callee_return_type_id != SemIR::TypeId::None) {
  602. thunk_param_type_ids.push_back(callee_return_type_id);
  603. }
  604. auto carbon_thunk_function_id =
  605. MakeGeneratedFunctionDecl(
  606. context, loc_id,
  607. {.parent_scope_id = target.function.parent_scope_id,
  608. .name_id = thunk_name_id,
  609. .self_type_id = target.self_type_id,
  610. .param_type_ids = thunk_param_type_ids,
  611. .param_kind = ParamPatternKind::Ref})
  612. .second;
  613. BuildThunkDefinitionForExport(
  614. context, carbon_thunk_function_id, target.function_id,
  615. context.functions().Get(carbon_thunk_function_id).first_decl_id(),
  616. target.function.first_decl_id());
  617. return carbon_thunk_function_id;
  618. }
  619. auto ExportFunctionToCpp(Context& context, SemIR::LocId loc_id,
  620. SemIR::FunctionId callee_function_id)
  621. -> clang::FunctionDecl* {
  622. const SemIR::Function& callee = context.functions().Get(callee_function_id);
  623. if (callee.generic_id.has_value()) {
  624. context.TODO(loc_id,
  625. "unsupported: C++ calling a Carbon function with "
  626. "generic parameters");
  627. return nullptr;
  628. }
  629. // Map the parent scope into the C++ AST.
  630. auto* decl_context =
  631. ExportNameScopeToCpp(context, loc_id, callee.parent_scope_id);
  632. if (!decl_context) {
  633. return nullptr;
  634. }
  635. FunctionInfo target_function_info(context, callee_function_id, callee,
  636. decl_context);
  637. // Create a Carbon thunk that calls the callee. The thunk's parameters
  638. // are all references so that the ABI is compatible with C++ callers.
  639. auto carbon_thunk_function_id =
  640. BuildCarbonToCarbonThunk(context, loc_id, target_function_info);
  641. // Create a `clang::FunctionDecl` that can be used to call the Carbon thunk.
  642. auto* carbon_function_decl = BuildCppFunctionDeclForCarbonFn(
  643. context, loc_id, carbon_thunk_function_id);
  644. if (!carbon_function_decl) {
  645. return nullptr;
  646. }
  647. // Create a C++ thunk that calls the Carbon thunk.
  648. return BuildCppToCarbonThunk(context, loc_id, target_function_info,
  649. context.names().GetFormatted(callee.name_id),
  650. carbon_function_decl);
  651. }
  652. } // namespace Carbon::Check