Skip to content

Commit 5d1ce01

Browse files
authored
[cxx-interop] Import parameterized public ctors of C++ foreign ref types as Swift Initializer (#80449)
Extends PR #79986 by adding support for calling parameterized C++ initializers from Swift. This patch synthesizes static factory methods corresponding to C++ parameterized constructors, allowing Swift to call them as Swift initializers (e.g., init(_:), init(_:_:), etc.). This patch also aded tests and logic to make sure that we emit no additional diagnostics when a C++ foreign ref type is just referred from Swift and its initializer is not explicitly called. rdar://148285251
1 parent c68fafe commit 5d1ce01

File tree

6 files changed

+391
-136
lines changed

6 files changed

+391
-136
lines changed

lib/ClangImporter/ImportDecl.cpp

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2558,12 +2558,13 @@ namespace {
25582558
});
25592559
});
25602560
if (!hasUserProvidedStaticFactory) {
2561-
if (auto generatedCxxMethodDecl =
2562-
synthesizer.synthesizeStaticFactoryForCXXForeignRef(
2563-
cxxRecordDecl)) {
2561+
auto generatedCxxMethodDecls =
2562+
synthesizer.synthesizeStaticFactoryForCXXForeignRef(
2563+
cxxRecordDecl);
2564+
for (auto *methodDecl : generatedCxxMethodDecls) {
25642565
if (Decl *importedInitDecl =
25652566
Impl.SwiftContext.getClangModuleLoader()
2566-
->importDeclDirectly(generatedCxxMethodDecl))
2567+
->importDeclDirectly(methodDecl))
25672568
result->addMember(importedInitDecl);
25682569
}
25692570
}

lib/ClangImporter/SwiftDeclSynthesizer.cpp

Lines changed: 165 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -2534,128 +2534,197 @@ SwiftDeclSynthesizer::makeDefaultArgument(const clang::ParmVarDecl *param,
25342534

25352535
// MARK: C++ foreign reference type constructors
25362536

2537-
clang::CXXMethodDecl *
2537+
llvm::SmallVector<clang::CXXMethodDecl *, 4>
25382538
SwiftDeclSynthesizer::synthesizeStaticFactoryForCXXForeignRef(
25392539
const clang::CXXRecordDecl *cxxRecordDecl) {
25402540

25412541
clang::ASTContext &clangCtx = cxxRecordDecl->getASTContext();
25422542
clang::Sema &clangSema = ImporterImpl.getClangSema();
25432543

25442544
clang::QualType cxxRecordTy = clangCtx.getRecordType(cxxRecordDecl);
2545+
clang::SourceLocation cxxRecordDeclLoc = cxxRecordDecl->getLocation();
25452546

2546-
clang::CXXConstructorDecl *defaultCtorDecl = nullptr;
2547-
for (clang::CXXConstructorDecl *ctor : cxxRecordDecl->ctors()) {
2548-
if (ctor->parameters().empty() && !ctor->isDeleted() &&
2549-
ctor->getAccess() != clang::AS_private &&
2550-
ctor->getAccess() != clang::AS_protected) {
2551-
defaultCtorDecl = ctor;
2552-
break;
2553-
}
2547+
llvm::SmallVector<clang::CXXConstructorDecl *, 4> ctorDeclsForSynth;
2548+
for (clang::CXXConstructorDecl *ctorDecl : cxxRecordDecl->ctors()) {
2549+
if (ctorDecl->isDeleted() || ctorDecl->getAccess() == clang::AS_private ||
2550+
ctorDecl->getAccess() == clang::AS_protected ||
2551+
ctorDecl->isCopyOrMoveConstructor() || ctorDecl->isVariadic())
2552+
continue;
2553+
2554+
bool hasDefaultArg = !ctorDecl->parameters().empty() &&
2555+
ctorDecl->parameters().back()->hasDefaultArg();
2556+
// TODO: Add support for default args in ctors for C++ foreign reference
2557+
// types.
2558+
if (hasDefaultArg)
2559+
continue;
2560+
ctorDeclsForSynth.push_back(ctorDecl);
25542561
}
2555-
if (!defaultCtorDecl)
2556-
return nullptr;
2562+
2563+
if (ctorDeclsForSynth.empty())
2564+
return {};
25572565

25582566
clang::FunctionDecl *operatorNew = nullptr;
25592567
clang::FunctionDecl *operatorDelete = nullptr;
25602568
bool passAlignment = false;
2569+
clang::Sema::SFINAETrap trap(clangSema);
25612570
bool findingAllocFuncFailed = clangSema.FindAllocationFunctions(
2562-
cxxRecordDecl->getLocation(), clang::SourceRange(), clang::Sema::AFS_Both,
2563-
clang::Sema::AFS_Both, cxxRecordTy,
2564-
/*IsArray*/ false, passAlignment, clang::MultiExprArg(), operatorNew,
2565-
operatorDelete, /*Diagnose*/ false);
2566-
if (findingAllocFuncFailed || !operatorNew || operatorNew->isDeleted() ||
2571+
cxxRecordDeclLoc, clang::SourceRange(), clang::Sema::AFS_Both,
2572+
clang::Sema::AFS_Both, cxxRecordTy, /*IsArray=*/false, passAlignment,
2573+
clang::MultiExprArg(), operatorNew, operatorDelete,
2574+
/*Diagnose=*/false);
2575+
if (trap.hasErrorOccurred() || findingAllocFuncFailed || !operatorNew ||
2576+
operatorNew->isDeleted() ||
25672577
operatorNew->getAccess() == clang::AS_private ||
25682578
operatorNew->getAccess() == clang::AS_protected)
2569-
return nullptr;
2579+
return {};
25702580

25712581
clang::QualType cxxRecordPtrTy = clangCtx.getPointerType(cxxRecordTy);
25722582
// Adding `_Nonnull` to the return type of synthesized static factory
25732583
bool nullabilityCannotBeAdded =
25742584
clangSema.CheckImplicitNullabilityTypeSpecifier(
2575-
cxxRecordPtrTy, clang::NullabilityKind::NonNull,
2576-
cxxRecordDecl->getLocation(),
2577-
/*isParam=*/false,
2578-
/*OverrideExisting=*/true);
2585+
cxxRecordPtrTy, clang::NullabilityKind::NonNull, cxxRecordDeclLoc,
2586+
/*isParam=*/false, /*OverrideExisting=*/true);
25792587
assert(!nullabilityCannotBeAdded &&
25802588
"Failed to add _Nonnull specifier to synthesized "
25812589
"static factory's return type");
25822590

25832591
clang::IdentifierTable &clangIdents = clangCtx.Idents;
2584-
clang::IdentifierInfo *funcNameToSynthesize = &clangIdents.get(
2585-
("__returns_" + cxxRecordDecl->getNameAsString()).c_str());
2586-
clang::FunctionProtoType::ExtProtoInfo EPI;
2587-
clang::QualType funcTypeToSynthesize =
2588-
clangCtx.getFunctionType(cxxRecordPtrTy, {}, EPI);
2589-
2590-
clang::CXXMethodDecl *synthesizedCxxMethodDecl = clang::CXXMethodDecl::Create(
2591-
clangCtx, const_cast<clang::CXXRecordDecl *>(cxxRecordDecl),
2592-
cxxRecordDecl->getLocation(),
2593-
clang::DeclarationNameInfo(funcNameToSynthesize,
2594-
cxxRecordDecl->getLocation()),
2595-
funcTypeToSynthesize,
2596-
clangCtx.getTrivialTypeSourceInfo(funcTypeToSynthesize), clang::SC_Static,
2597-
/*UsesFPIntrin=*/false, /*isInline=*/true,
2598-
clang::ConstexprSpecKind::Unspecified, cxxRecordDecl->getLocation());
2599-
assert(synthesizedCxxMethodDecl &&
2600-
"Unable to synthesize static factory for c++ foreign reference type");
2601-
synthesizedCxxMethodDecl->setAccess(clang::AccessSpecifier::AS_public);
2602-
2603-
if (!hasImmortalAttrs(cxxRecordDecl)) {
2604-
clang::SwiftAttrAttr *returnsRetainedAttrForSynthesizedCxxMethodDecl =
2605-
clang::SwiftAttrAttr::Create(clangCtx, "returns_retained");
2606-
synthesizedCxxMethodDecl->addAttr(
2607-
returnsRetainedAttrForSynthesizedCxxMethodDecl);
2592+
2593+
llvm::SmallVector<clang::CXXMethodDecl *, 4> synthesizedFactories;
2594+
unsigned int selectedCtorDeclCounter = 0;
2595+
for (clang::CXXConstructorDecl *selectedCtorDecl : ctorDeclsForSynth) {
2596+
unsigned int ctorParamCount = selectedCtorDecl->getNumParams();
2597+
selectedCtorDeclCounter++;
2598+
2599+
std::string funcName = "__returns_" + cxxRecordDecl->getNameAsString();
2600+
if (ctorParamCount > 0)
2601+
funcName += "_" + std::to_string(ctorParamCount) + "_params";
2602+
funcName += "_" + std::to_string(selectedCtorDeclCounter);
2603+
clang::IdentifierInfo *funcNameToSynth = &clangIdents.get(funcName);
2604+
2605+
auto ctorFunctionProtoTy =
2606+
selectedCtorDecl->getType()->getAs<clang::FunctionProtoType>();
2607+
clang::ArrayRef<clang::QualType> paramTypes =
2608+
ctorFunctionProtoTy->getParamTypes();
2609+
clang::FunctionProtoType::ExtProtoInfo EPI;
2610+
clang::QualType funcTypeToSynth =
2611+
clangCtx.getFunctionType(cxxRecordPtrTy, paramTypes, EPI);
2612+
2613+
clang::CXXMethodDecl *synthCxxMethodDecl = clang::CXXMethodDecl::Create(
2614+
clangCtx, const_cast<clang::CXXRecordDecl *>(cxxRecordDecl),
2615+
cxxRecordDeclLoc,
2616+
clang::DeclarationNameInfo(funcNameToSynth, cxxRecordDeclLoc),
2617+
funcTypeToSynth, clangCtx.getTrivialTypeSourceInfo(funcTypeToSynth),
2618+
clang::SC_Static, /*UsesFPIntrin=*/false, /*isInline=*/true,
2619+
clang::ConstexprSpecKind::Unspecified, cxxRecordDeclLoc);
2620+
assert(
2621+
synthCxxMethodDecl &&
2622+
"Unable to synthesize static factory for c++ foreign reference type");
2623+
synthCxxMethodDecl->setAccess(clang::AccessSpecifier::AS_public);
2624+
2625+
llvm::SmallVector<clang::ParmVarDecl *, 4> synthParams;
2626+
for (unsigned int i = 0; i < ctorParamCount; ++i) {
2627+
auto *origParam = selectedCtorDecl->getParamDecl(i);
2628+
clang::IdentifierInfo *paramIdent = origParam->getIdentifier();
2629+
if (!paramIdent) {
2630+
std::string dummyName = "__unnamed_param_" + std::to_string(i);
2631+
paramIdent = &clangIdents.get(dummyName);
2632+
}
2633+
auto *param = clang::ParmVarDecl::Create(
2634+
clangCtx, synthCxxMethodDecl, cxxRecordDeclLoc, cxxRecordDeclLoc,
2635+
paramIdent, origParam->getType(),
2636+
clangCtx.getTrivialTypeSourceInfo(origParam->getType()),
2637+
clang::SC_None, /*DefArg=*/nullptr);
2638+
param->setIsUsed();
2639+
synthParams.push_back(param);
2640+
}
2641+
synthCxxMethodDecl->setParams(synthParams);
2642+
2643+
if (!hasImmortalAttrs(cxxRecordDecl)) {
2644+
synthCxxMethodDecl->addAttr(
2645+
clang::SwiftAttrAttr::Create(clangCtx, "returns_retained"));
2646+
}
2647+
2648+
std::string swiftInitStr = "init(";
2649+
for (unsigned i = 0; i < ctorParamCount; ++i) {
2650+
auto paramType = selectedCtorDecl->getParamDecl(i)->getType();
2651+
if (paramType->isRValueReferenceType()) {
2652+
swiftInitStr += "consuming:";
2653+
} else {
2654+
swiftInitStr += "_:";
2655+
}
2656+
}
2657+
swiftInitStr += ")";
2658+
synthCxxMethodDecl->addAttr(
2659+
clang::SwiftNameAttr::Create(clangCtx, swiftInitStr));
2660+
2661+
llvm::SmallVector<clang::Expr *, 4> ctorArgs;
2662+
for (auto *param : synthParams) {
2663+
clang::QualType paramTy = param->getType();
2664+
clang::QualType exprTy = paramTy.getNonReferenceType();
2665+
clang::Expr *argExpr = clang::DeclRefExpr::Create(
2666+
clangCtx, clang::NestedNameSpecifierLoc(), cxxRecordDeclLoc, param,
2667+
/*RefersToEnclosingVariableOrCapture=*/false, cxxRecordDeclLoc,
2668+
exprTy, clang::VK_LValue);
2669+
if (paramTy->isRValueReferenceType()) {
2670+
argExpr = clangSema
2671+
.BuildCXXNamedCast(
2672+
cxxRecordDeclLoc, clang::tok::kw_static_cast,
2673+
clangCtx.getTrivialTypeSourceInfo(paramTy), argExpr,
2674+
clang::SourceRange(), clang::SourceRange())
2675+
.get();
2676+
}
2677+
ctorArgs.push_back(argExpr);
2678+
}
2679+
llvm::SmallVector<clang::Expr *, 4> ctorArgsToAdd;
2680+
2681+
if (clangSema.CompleteConstructorCall(selectedCtorDecl, cxxRecordTy,
2682+
ctorArgs, cxxRecordDeclLoc,
2683+
ctorArgsToAdd))
2684+
continue;
2685+
2686+
clang::ExprResult synthCtorExprResult = clangSema.BuildCXXConstructExpr(
2687+
cxxRecordDeclLoc, cxxRecordTy, selectedCtorDecl,
2688+
/*Elidable=*/false, ctorArgsToAdd,
2689+
/*HadMultipleCandidates=*/false,
2690+
/*IsListInitialization=*/false,
2691+
/*IsStdInitListInitialization=*/false,
2692+
/*RequiresZeroInit=*/false, clang::CXXConstructionKind::Complete,
2693+
clang::SourceRange(cxxRecordDeclLoc, cxxRecordDeclLoc));
2694+
assert(!synthCtorExprResult.isInvalid() &&
2695+
"Unable to synthesize constructor expression for c++ foreign "
2696+
"reference type");
2697+
clang::Expr *synthCtorExpr = synthCtorExprResult.get();
2698+
2699+
clang::ExprResult synthNewExprResult = clangSema.BuildCXXNew(
2700+
clang::SourceRange(), /*UseGlobal=*/false, clang::SourceLocation(), {},
2701+
clang::SourceLocation(), clang::SourceRange(), cxxRecordTy,
2702+
clangCtx.getTrivialTypeSourceInfo(cxxRecordTy), std::nullopt,
2703+
clang::SourceRange(cxxRecordDeclLoc, cxxRecordDeclLoc), synthCtorExpr);
2704+
assert(
2705+
!synthNewExprResult.isInvalid() &&
2706+
"Unable to synthesize `new` expression for c++ foreign reference type");
2707+
auto *synthNewExpr = cast<clang::CXXNewExpr>(synthNewExprResult.get());
2708+
2709+
clang::ReturnStmt *synthRetStmt = clang::ReturnStmt::Create(
2710+
clangCtx, cxxRecordDeclLoc, synthNewExpr, /*NRVOCandidate=*/nullptr);
2711+
assert(synthRetStmt && "Unable to synthesize return statement for "
2712+
"static factory of c++ foreign reference type");
2713+
2714+
clang::CompoundStmt *synthFuncBody = clang::CompoundStmt::Create(
2715+
clangCtx, {synthRetStmt}, clang::FPOptionsOverride(), cxxRecordDeclLoc,
2716+
cxxRecordDeclLoc);
2717+
assert(synthRetStmt && "Unable to synthesize function body for static "
2718+
"factory of c++ foreign reference type");
2719+
2720+
synthCxxMethodDecl->setBody(synthFuncBody);
2721+
synthCxxMethodDecl->addAttr(clang::NoDebugAttr::CreateImplicit(clangCtx));
2722+
2723+
synthCxxMethodDecl->setImplicit();
2724+
synthCxxMethodDecl->setImplicitlyInline();
2725+
2726+
synthesizedFactories.push_back(synthCxxMethodDecl);
26082727
}
26092728

2610-
clang::SwiftNameAttr *swiftNameInitAttrForSynthesizedCxxMethodDecl =
2611-
clang::SwiftNameAttr::Create(clangCtx, "init()");
2612-
synthesizedCxxMethodDecl->addAttr(
2613-
swiftNameInitAttrForSynthesizedCxxMethodDecl);
2614-
2615-
clang::ExprResult synthesizedConstructExprResult =
2616-
clangSema.BuildCXXConstructExpr(
2617-
clang::SourceLocation(), cxxRecordTy, defaultCtorDecl,
2618-
/*Elidable=*/false, clang::MultiExprArg(),
2619-
/*HadMultipleCandidates=*/false,
2620-
/*IsListInitialization=*/false,
2621-
/*IsStdInitListInitialization=*/false,
2622-
/*RequiresZeroInit=*/false, clang::CXXConstructionKind::Complete,
2623-
clang::SourceRange());
2624-
assert(!synthesizedConstructExprResult.isInvalid() &&
2625-
"Unable to synthesize constructor expression for c++ foreign "
2626-
"reference type");
2627-
clang::CXXConstructExpr *synthesizedConstructExpr =
2628-
cast<clang::CXXConstructExpr>(synthesizedConstructExprResult.get());
2629-
2630-
clang::ExprResult synthesizedNewExprResult = clangSema.BuildCXXNew(
2631-
clang::SourceRange(), /*UseGlobal=*/false, clang::SourceLocation(), {},
2632-
clang::SourceLocation(), clang::SourceRange(), cxxRecordTy,
2633-
clangCtx.getTrivialTypeSourceInfo(cxxRecordTy), std::nullopt,
2634-
clang::SourceRange(), synthesizedConstructExpr);
2635-
assert(
2636-
!synthesizedNewExprResult.isInvalid() &&
2637-
"Unable to synthesize `new` expression for c++ foreign reference type");
2638-
clang::CXXNewExpr *synthesizedNewExpr =
2639-
cast<clang::CXXNewExpr>(synthesizedNewExprResult.get());
2640-
2641-
clang::ReturnStmt *synthesizedRetStmt =
2642-
clang::ReturnStmt::Create(clangCtx, clang::SourceLocation(),
2643-
synthesizedNewExpr, /*VarDecl=*/nullptr);
2644-
assert(synthesizedRetStmt && "Unable to synthesize return statement for "
2645-
"static factory of c++ foreign reference type");
2646-
2647-
clang::CompoundStmt *synthesizedFuncBody = clang::CompoundStmt::Create(
2648-
clangCtx, {synthesizedRetStmt}, clang::FPOptionsOverride(),
2649-
clang::SourceLocation(), clang::SourceLocation());
2650-
assert(synthesizedRetStmt && "Unable to synthesize function body for static "
2651-
"factory of c++ foreign reference type");
2652-
2653-
synthesizedCxxMethodDecl->setBody(synthesizedFuncBody);
2654-
synthesizedCxxMethodDecl->addAttr(
2655-
clang::NoDebugAttr::CreateImplicit(clangCtx));
2656-
2657-
synthesizedCxxMethodDecl->setImplicit();
2658-
synthesizedCxxMethodDecl->setImplicitlyInline();
2659-
2660-
return synthesizedCxxMethodDecl;
2729+
return synthesizedFactories;
26612730
}

lib/ClangImporter/SwiftDeclSynthesizer.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,8 @@ class SwiftDeclSynthesizer {
337337
/// Synthesize a static factory method for a C++ foreign reference type,
338338
/// returning a `CXXMethodDecl*` or `nullptr` if the required constructor or
339339
/// allocation function is not found.
340-
clang::CXXMethodDecl *synthesizeStaticFactoryForCXXForeignRef(
340+
llvm::SmallVector<clang::CXXMethodDecl *, 4>
341+
synthesizeStaticFactoryForCXXForeignRef(
341342
const clang::CXXRecordDecl *cxxRecordDecl);
342343

343344
private:

0 commit comments

Comments
 (0)