cpp_thunk.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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/Sema.h"
  8. #include "toolchain/check/call.h"
  9. #include "toolchain/check/context.h"
  10. #include "toolchain/check/control_flow.h"
  11. #include "toolchain/check/convert.h"
  12. #include "toolchain/check/literal.h"
  13. #include "toolchain/check/type.h"
  14. #include "toolchain/check/type_completion.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::Check {
  18. // Returns the C++ thunk mangled name given the callee function.
  19. static auto GenerateThunkMangledName(
  20. clang::MangleContext& mangle_context,
  21. const clang::FunctionDecl& callee_function_decl) -> std::string {
  22. RawStringOstream mangled_name_stream;
  23. mangle_context.mangleName(clang::GlobalDecl(&callee_function_decl),
  24. mangled_name_stream);
  25. mangled_name_stream << ".carbon_thunk";
  26. return mangled_name_stream.TakeStr();
  27. }
  28. // Returns true if a C++ thunk is required for the given type. A C++ thunk is
  29. // required for any type except for void, pointer types and signed 32-bit and
  30. // 64-bit integers.
  31. static auto IsThunkRequiredForType(Context& context, SemIR::TypeId type_id)
  32. -> bool {
  33. if (!type_id.has_value() || type_id == SemIR::ErrorInst::TypeId) {
  34. return false;
  35. }
  36. type_id = context.types().GetUnqualifiedType(type_id);
  37. switch (context.types().GetAsInst(type_id).kind()) {
  38. case SemIR::PointerType::Kind: {
  39. return false;
  40. }
  41. case SemIR::ClassType::Kind: {
  42. if (!context.types().IsComplete(type_id)) {
  43. // Signed integers of 32 or 64 bits should be completed when imported.
  44. return true;
  45. }
  46. if (!context.types().IsSignedInt(type_id)) {
  47. return true;
  48. }
  49. llvm::APInt bit_width =
  50. context.ints().Get(context.types().GetIntTypeInfo(type_id).bit_width);
  51. return bit_width != 32 && bit_width != 64;
  52. }
  53. default:
  54. return true;
  55. }
  56. }
  57. auto IsCppThunkRequired(Context& context, const SemIR::Function& function)
  58. -> bool {
  59. if (!function.clang_decl_id.has_value()) {
  60. return false;
  61. }
  62. if (function.self_param_id.has_value()) {
  63. // TODO: Support member methods.
  64. return false;
  65. }
  66. SemIR::TypeId return_type_id =
  67. function.GetDeclaredReturnType(context.sem_ir());
  68. if (return_type_id.has_value()) {
  69. // TODO: Support non-void return values.
  70. return false;
  71. }
  72. bool thunk_required_for_param = false;
  73. for (auto param_id :
  74. context.inst_blocks().GetOrEmpty(function.call_params_id)) {
  75. if (param_id == SemIR::ErrorInst::InstId) {
  76. return false;
  77. }
  78. if (!thunk_required_for_param &&
  79. IsThunkRequiredForType(
  80. context,
  81. context.insts().GetAs<SemIR::AnyParam>(param_id).type_id)) {
  82. thunk_required_for_param = true;
  83. }
  84. }
  85. return thunk_required_for_param;
  86. }
  87. // Returns whether the type is a pointer or a signed int of 32 or 64 bits.
  88. static auto IsSimpleAbiType(clang::ASTContext& ast_context,
  89. clang::QualType type) -> bool {
  90. if (type->isPointerType()) {
  91. return true;
  92. }
  93. if (const auto* builtin_type = type->getAs<clang::BuiltinType>()) {
  94. if (builtin_type->isSignedInteger()) {
  95. uint64_t type_size = ast_context.getIntWidth(type);
  96. return type_size == 32 || type_size == 64;
  97. }
  98. }
  99. return false;
  100. }
  101. // Creates the thunk parameter types given the callee function. Also returns for
  102. // each type whether it is different from the matching callee function parameter
  103. // type.
  104. static auto BuildThunkParameterTypes(
  105. clang::ASTContext& ast_context,
  106. const clang::FunctionDecl& callee_function_decl)
  107. -> std::tuple<llvm::SmallVector<clang::QualType>, llvm::SmallVector<bool>> {
  108. std::tuple<llvm::SmallVector<clang::QualType>, llvm::SmallVector<bool>>
  109. result;
  110. auto& [thunk_param_types, param_type_changed] = result;
  111. unsigned num_params = callee_function_decl.getNumParams();
  112. thunk_param_types.reserve(num_params);
  113. param_type_changed.reserve(num_params);
  114. for (const clang::ParmVarDecl* callee_param :
  115. callee_function_decl.parameters()) {
  116. clang::QualType param_type = callee_param->getType();
  117. bool is_simple_abi_type = IsSimpleAbiType(ast_context, param_type);
  118. if (!is_simple_abi_type) {
  119. clang::QualType pointer_type = ast_context.getPointerType(param_type);
  120. param_type = ast_context.getAttributedType(
  121. clang::NullabilityKind::NonNull, pointer_type, pointer_type);
  122. }
  123. param_type_changed.push_back(!is_simple_abi_type);
  124. thunk_param_types.push_back(param_type);
  125. }
  126. return result;
  127. }
  128. // Returns the thunk parameters using the callee function parameter identifiers.
  129. static auto BuildThunkParameters(
  130. clang::ASTContext& ast_context,
  131. const clang::FunctionDecl& callee_function_decl,
  132. clang::FunctionDecl* thunk_function_decl)
  133. -> llvm::SmallVector<clang::ParmVarDecl*> {
  134. clang::SourceLocation clang_loc = callee_function_decl.getLocation();
  135. unsigned num_params = thunk_function_decl->getNumParams();
  136. CARBON_CHECK(callee_function_decl.getNumParams() == num_params);
  137. const auto* thunk_function_proto_type =
  138. thunk_function_decl->getFunctionType()->getAs<clang::FunctionProtoType>();
  139. llvm::SmallVector<clang::ParmVarDecl*> thunk_params;
  140. thunk_params.reserve(num_params);
  141. for (unsigned i = 0; i < num_params; ++i) {
  142. clang::ParmVarDecl* thunk_param = clang::ParmVarDecl::Create(
  143. ast_context, thunk_function_decl, clang_loc, clang_loc,
  144. callee_function_decl.getParamDecl(i)->getIdentifier(),
  145. thunk_function_proto_type->getParamType(i), nullptr, clang::SC_None,
  146. nullptr);
  147. thunk_params.push_back(thunk_param);
  148. }
  149. return thunk_params;
  150. }
  151. // Returns the thunk function declaration given the callee function and the
  152. // thunk parameter types.
  153. static auto CreateThunkFunctionDecl(
  154. Context& context, const clang::FunctionDecl& callee_function_decl,
  155. llvm::ArrayRef<clang::QualType> thunk_param_types) -> clang::FunctionDecl* {
  156. clang::ASTContext& ast_context = context.ast_context();
  157. clang::SourceLocation clang_loc = callee_function_decl.getLocation();
  158. clang::IdentifierInfo& identifier_info = ast_context.Idents.get(
  159. callee_function_decl.getNameAsString() + "__carbon_thunk");
  160. const auto* callee_function_type = callee_function_decl.getFunctionType()
  161. ->castAs<clang::FunctionProtoType>();
  162. // TODO: Check whether we need to modify `ExtParameterInfo` in `ExtProtoInfo`.
  163. clang::QualType thunk_function_type = ast_context.getFunctionType(
  164. callee_function_decl.getReturnType(), thunk_param_types,
  165. callee_function_type->getExtProtoInfo());
  166. clang::DeclContext* decl_context = ast_context.getTranslationUnitDecl();
  167. // TODO: Thunks should not have external linkage, consider using `SC_Static`.
  168. clang::FunctionDecl* thunk_function_decl = clang::FunctionDecl::Create(
  169. ast_context, decl_context, clang_loc, clang_loc,
  170. clang::DeclarationName(&identifier_info), thunk_function_type,
  171. /*TInfo=*/nullptr, clang::SC_Extern);
  172. decl_context->addDecl(thunk_function_decl);
  173. thunk_function_decl->setParams(BuildThunkParameters(
  174. ast_context, callee_function_decl, thunk_function_decl));
  175. // Set always_inline.
  176. thunk_function_decl->addAttr(
  177. clang::AlwaysInlineAttr::CreateImplicit(ast_context));
  178. // Set asm("<callee function mangled name>.carbon_thunk").
  179. thunk_function_decl->addAttr(clang::AsmLabelAttr::CreateImplicit(
  180. ast_context,
  181. GenerateThunkMangledName(*context.sem_ir().clang_mangle_context(),
  182. callee_function_decl),
  183. clang_loc));
  184. return thunk_function_decl;
  185. }
  186. // Takes the thunk function parameters and for each one creates an arg for the
  187. // callee function which is the thunk parameter or its address.
  188. static auto BuildCalleeArgs(clang::Sema& sema,
  189. clang::FunctionDecl* thunk_function_decl,
  190. llvm::ArrayRef<bool> param_type_changed)
  191. -> llvm::SmallVector<clang::Expr*> {
  192. llvm::SmallVector<clang::Expr*> call_args;
  193. size_t num_params = thunk_function_decl->getNumParams();
  194. CARBON_CHECK(param_type_changed.size() == num_params);
  195. call_args.reserve(num_params);
  196. for (unsigned i = 0; i < num_params; ++i) {
  197. clang::ParmVarDecl* thunk_param = thunk_function_decl->getParamDecl(i);
  198. clang::SourceLocation clang_loc = thunk_param->getLocation();
  199. clang::Expr* call_arg = sema.BuildDeclRefExpr(
  200. thunk_param, thunk_param->getType(), clang::VK_LValue, clang_loc);
  201. if (param_type_changed[i]) {
  202. // TODO: Consider inserting a cast to an rvalue. Note that we currently
  203. // pass pointers to non-temporary objects as the argument when calling a
  204. // thunk, so we'll need to either change that or generate different thunks
  205. // depending on whether we're moving from each parameter.
  206. clang::ExprResult deref_result =
  207. sema.BuildUnaryOp(nullptr, clang_loc, clang::UO_Deref, call_arg);
  208. CARBON_CHECK(deref_result.isUsable());
  209. call_arg = deref_result.get();
  210. }
  211. call_args.push_back(call_arg);
  212. }
  213. return call_args;
  214. }
  215. // Builds the thunk function body which calls the callee function using the call
  216. // args and returns the callee function return value. Returns nullptr on
  217. // failure.
  218. static auto BuildThunkBody(clang::Sema& sema,
  219. clang::FunctionDecl* callee_function_decl,
  220. llvm::MutableArrayRef<clang::Expr*> call_args)
  221. -> clang::Stmt* {
  222. clang::SourceLocation clang_loc = callee_function_decl->getLocation();
  223. clang::DeclRefExpr* callee_function_ref = sema.BuildDeclRefExpr(
  224. callee_function_decl, callee_function_decl->getType(), clang::VK_PRValue,
  225. clang_loc);
  226. clang::ExprResult call_result = sema.BuildCallExpr(
  227. nullptr, callee_function_ref, clang_loc, call_args, clang_loc);
  228. if (!call_result.isUsable()) {
  229. return nullptr;
  230. }
  231. clang::Expr* call = call_result.get();
  232. clang::StmtResult return_result = sema.BuildReturnStmt(clang_loc, call);
  233. CARBON_CHECK(return_result.isUsable());
  234. return return_result.get();
  235. }
  236. auto BuildCppThunk(Context& context, const SemIR::Function& callee_function)
  237. -> clang::FunctionDecl* {
  238. clang::FunctionDecl* callee_function_decl =
  239. context.sem_ir()
  240. .clang_decls()
  241. .Get(callee_function.clang_decl_id)
  242. .decl->getAsFunction();
  243. CARBON_CHECK(callee_function_decl);
  244. // Build the thunk function declaration.
  245. auto [thunk_param_types, param_type_changed] =
  246. BuildThunkParameterTypes(context.ast_context(), *callee_function_decl);
  247. clang::FunctionDecl* thunk_function_decl = CreateThunkFunctionDecl(
  248. context, *callee_function_decl, thunk_param_types);
  249. // Build the thunk function body.
  250. clang::Sema& sema = context.sem_ir().clang_ast_unit()->getSema();
  251. clang::Sema::ContextRAII context_raii(sema, thunk_function_decl);
  252. sema.ActOnStartOfFunctionDef(nullptr, thunk_function_decl);
  253. llvm::SmallVector<clang::Expr*> call_args =
  254. BuildCalleeArgs(sema, thunk_function_decl, param_type_changed);
  255. clang::Stmt* body = BuildThunkBody(sema, callee_function_decl, call_args);
  256. sema.ActOnFinishFunctionBody(thunk_function_decl, body);
  257. if (!body) {
  258. return nullptr;
  259. }
  260. return thunk_function_decl;
  261. }
  262. auto PerformCppThunkCall(Context& context, SemIR::LocId loc_id,
  263. SemIR::FunctionId callee_function_id,
  264. llvm::ArrayRef<SemIR::InstId> callee_arg_ids,
  265. SemIR::InstId thunk_callee_id) -> SemIR::InstId {
  266. llvm::ArrayRef<SemIR::InstId> callee_function_params =
  267. context.inst_blocks().GetOrEmpty(
  268. context.functions().Get(callee_function_id).call_params_id);
  269. llvm::ArrayRef<SemIR::InstId> thunk_function_params =
  270. context.inst_blocks().GetOrEmpty(
  271. context.functions()
  272. .Get(GetCalleeFunction(context.sem_ir(), thunk_callee_id)
  273. .function_id)
  274. .call_params_id);
  275. size_t num_params = callee_function_params.size();
  276. CARBON_CHECK(thunk_function_params.size() == num_params);
  277. CARBON_CHECK(callee_arg_ids.size() == num_params);
  278. llvm::SmallVector<SemIR::InstId> thunk_arg_ids;
  279. thunk_arg_ids.reserve(callee_arg_ids.size());
  280. for (size_t i = 0; i < callee_function_params.size(); ++i) {
  281. SemIR::TypeId callee_param_type_id =
  282. context.insts()
  283. .GetAs<SemIR::AnyParam>(callee_function_params[i])
  284. .type_id;
  285. SemIR::TypeId thunk_param_type_id =
  286. context.insts()
  287. .GetAs<SemIR::AnyParam>(thunk_function_params[i])
  288. .type_id;
  289. SemIR::InstId arg_id = callee_arg_ids[i];
  290. if (callee_param_type_id != thunk_param_type_id) {
  291. CARBON_CHECK(thunk_param_type_id ==
  292. GetPointerType(context, context.types().GetInstId(
  293. callee_param_type_id)));
  294. arg_id = Convert(context, loc_id, arg_id,
  295. {.kind = ConversionTarget::CppThunkRef,
  296. .type_id = callee_param_type_id});
  297. arg_id = AddInst<SemIR::AddrOf>(
  298. context, loc_id,
  299. {.type_id = thunk_param_type_id, .lvalue_id = arg_id});
  300. }
  301. thunk_arg_ids.push_back(arg_id);
  302. }
  303. return PerformCall(context, loc_id, thunk_callee_id, thunk_arg_ids);
  304. }
  305. } // namespace Carbon::Check