-
Notifications
You must be signed in to change notification settings - Fork 10.5k
[cxx-interop] Import parameterized public ctors of C++ foreign ref types as Swift Initializer #80449
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
fahadnayyar
merged 8 commits into
swiftlang:main
from
fahadnayyar:cxx-frt-constructors-params
Apr 8, 2025
Merged
[cxx-interop] Import parameterized public ctors of C++ foreign ref types as Swift Initializer #80449
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
abd15ae
[cxx-interop] Support first non default ctor of c++ foreign reference…
fahadnayyar 850ce16
Added support for multiple ctors
fahadnayyar 96518c0
Added new tests for parameterized ctors
fahadnayyar 726e762
Addresses minor comments + refactoring
fahadnayyar 02a284a
Addressed some more comments
fahadnayyar 3c720cb
Default args in ctors (-) rvalue ref in ctors (+) identifierless para…
fahadnayyar d551c7b
Addressed reaminging comments
fahadnayyar 882de07
macOS CI issue fix + SFINAETrap protection on all clangSema APIs
fahadnayyar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2534,128 +2534,197 @@ SwiftDeclSynthesizer::makeDefaultArgument(const clang::ParmVarDecl *param, | |
|
||
// MARK: C++ foreign reference type constructors | ||
|
||
clang::CXXMethodDecl * | ||
llvm::SmallVector<clang::CXXMethodDecl *, 4> | ||
SwiftDeclSynthesizer::synthesizeStaticFactoryForCXXForeignRef( | ||
const clang::CXXRecordDecl *cxxRecordDecl) { | ||
|
||
clang::ASTContext &clangCtx = cxxRecordDecl->getASTContext(); | ||
clang::Sema &clangSema = ImporterImpl.getClangSema(); | ||
|
||
clang::QualType cxxRecordTy = clangCtx.getRecordType(cxxRecordDecl); | ||
clang::SourceLocation cxxRecordDeclLoc = cxxRecordDecl->getLocation(); | ||
|
||
clang::CXXConstructorDecl *defaultCtorDecl = nullptr; | ||
for (clang::CXXConstructorDecl *ctor : cxxRecordDecl->ctors()) { | ||
if (ctor->parameters().empty() && !ctor->isDeleted() && | ||
ctor->getAccess() != clang::AS_private && | ||
ctor->getAccess() != clang::AS_protected) { | ||
defaultCtorDecl = ctor; | ||
break; | ||
} | ||
llvm::SmallVector<clang::CXXConstructorDecl *, 4> ctorDeclsForSynth; | ||
for (clang::CXXConstructorDecl *ctorDecl : cxxRecordDecl->ctors()) { | ||
if (ctorDecl->isDeleted() || ctorDecl->getAccess() == clang::AS_private || | ||
ctorDecl->getAccess() == clang::AS_protected || | ||
ctorDecl->isCopyOrMoveConstructor() || ctorDecl->isVariadic()) | ||
continue; | ||
|
||
bool hasDefaultArg = !ctorDecl->parameters().empty() && | ||
ctorDecl->parameters().back()->hasDefaultArg(); | ||
// TODO: Add support for default args in ctors for C++ foreign reference | ||
// types. | ||
if (hasDefaultArg) | ||
continue; | ||
ctorDeclsForSynth.push_back(ctorDecl); | ||
} | ||
if (!defaultCtorDecl) | ||
return nullptr; | ||
|
||
if (ctorDeclsForSynth.empty()) | ||
return {}; | ||
|
||
clang::FunctionDecl *operatorNew = nullptr; | ||
clang::FunctionDecl *operatorDelete = nullptr; | ||
bool passAlignment = false; | ||
clang::Sema::SFINAETrap trap(clangSema); | ||
bool findingAllocFuncFailed = clangSema.FindAllocationFunctions( | ||
cxxRecordDecl->getLocation(), clang::SourceRange(), clang::Sema::AFS_Both, | ||
clang::Sema::AFS_Both, cxxRecordTy, | ||
/*IsArray*/ false, passAlignment, clang::MultiExprArg(), operatorNew, | ||
operatorDelete, /*Diagnose*/ false); | ||
if (findingAllocFuncFailed || !operatorNew || operatorNew->isDeleted() || | ||
cxxRecordDeclLoc, clang::SourceRange(), clang::Sema::AFS_Both, | ||
clang::Sema::AFS_Both, cxxRecordTy, /*IsArray=*/false, passAlignment, | ||
clang::MultiExprArg(), operatorNew, operatorDelete, | ||
/*Diagnose=*/false); | ||
if (trap.hasErrorOccurred() || findingAllocFuncFailed || !operatorNew || | ||
operatorNew->isDeleted() || | ||
operatorNew->getAccess() == clang::AS_private || | ||
operatorNew->getAccess() == clang::AS_protected) | ||
return nullptr; | ||
return {}; | ||
|
||
clang::QualType cxxRecordPtrTy = clangCtx.getPointerType(cxxRecordTy); | ||
// Adding `_Nonnull` to the return type of synthesized static factory | ||
bool nullabilityCannotBeAdded = | ||
clangSema.CheckImplicitNullabilityTypeSpecifier( | ||
cxxRecordPtrTy, clang::NullabilityKind::NonNull, | ||
cxxRecordDecl->getLocation(), | ||
/*isParam=*/false, | ||
/*OverrideExisting=*/true); | ||
cxxRecordPtrTy, clang::NullabilityKind::NonNull, cxxRecordDeclLoc, | ||
/*isParam=*/false, /*OverrideExisting=*/true); | ||
assert(!nullabilityCannotBeAdded && | ||
"Failed to add _Nonnull specifier to synthesized " | ||
"static factory's return type"); | ||
|
||
clang::IdentifierTable &clangIdents = clangCtx.Idents; | ||
clang::IdentifierInfo *funcNameToSynthesize = &clangIdents.get( | ||
("__returns_" + cxxRecordDecl->getNameAsString()).c_str()); | ||
clang::FunctionProtoType::ExtProtoInfo EPI; | ||
clang::QualType funcTypeToSynthesize = | ||
clangCtx.getFunctionType(cxxRecordPtrTy, {}, EPI); | ||
|
||
clang::CXXMethodDecl *synthesizedCxxMethodDecl = clang::CXXMethodDecl::Create( | ||
clangCtx, const_cast<clang::CXXRecordDecl *>(cxxRecordDecl), | ||
cxxRecordDecl->getLocation(), | ||
clang::DeclarationNameInfo(funcNameToSynthesize, | ||
cxxRecordDecl->getLocation()), | ||
funcTypeToSynthesize, | ||
clangCtx.getTrivialTypeSourceInfo(funcTypeToSynthesize), clang::SC_Static, | ||
/*UsesFPIntrin=*/false, /*isInline=*/true, | ||
clang::ConstexprSpecKind::Unspecified, cxxRecordDecl->getLocation()); | ||
assert(synthesizedCxxMethodDecl && | ||
"Unable to synthesize static factory for c++ foreign reference type"); | ||
synthesizedCxxMethodDecl->setAccess(clang::AccessSpecifier::AS_public); | ||
|
||
if (!hasImmortalAttrs(cxxRecordDecl)) { | ||
clang::SwiftAttrAttr *returnsRetainedAttrForSynthesizedCxxMethodDecl = | ||
clang::SwiftAttrAttr::Create(clangCtx, "returns_retained"); | ||
synthesizedCxxMethodDecl->addAttr( | ||
returnsRetainedAttrForSynthesizedCxxMethodDecl); | ||
|
||
llvm::SmallVector<clang::CXXMethodDecl *, 4> synthesizedFactories; | ||
unsigned int selectedCtorDeclCounter = 0; | ||
for (clang::CXXConstructorDecl *selectedCtorDecl : ctorDeclsForSynth) { | ||
unsigned int ctorParamCount = selectedCtorDecl->getNumParams(); | ||
selectedCtorDeclCounter++; | ||
|
||
std::string funcName = "__returns_" + cxxRecordDecl->getNameAsString(); | ||
if (ctorParamCount > 0) | ||
funcName += "_" + std::to_string(ctorParamCount) + "_params"; | ||
funcName += "_" + std::to_string(selectedCtorDeclCounter); | ||
clang::IdentifierInfo *funcNameToSynth = &clangIdents.get(funcName); | ||
|
||
auto ctorFunctionProtoTy = | ||
selectedCtorDecl->getType()->getAs<clang::FunctionProtoType>(); | ||
clang::ArrayRef<clang::QualType> paramTypes = | ||
ctorFunctionProtoTy->getParamTypes(); | ||
clang::FunctionProtoType::ExtProtoInfo EPI; | ||
clang::QualType funcTypeToSynth = | ||
clangCtx.getFunctionType(cxxRecordPtrTy, paramTypes, EPI); | ||
|
||
clang::CXXMethodDecl *synthCxxMethodDecl = clang::CXXMethodDecl::Create( | ||
clangCtx, const_cast<clang::CXXRecordDecl *>(cxxRecordDecl), | ||
cxxRecordDeclLoc, | ||
clang::DeclarationNameInfo(funcNameToSynth, cxxRecordDeclLoc), | ||
funcTypeToSynth, clangCtx.getTrivialTypeSourceInfo(funcTypeToSynth), | ||
clang::SC_Static, /*UsesFPIntrin=*/false, /*isInline=*/true, | ||
clang::ConstexprSpecKind::Unspecified, cxxRecordDeclLoc); | ||
assert( | ||
synthCxxMethodDecl && | ||
"Unable to synthesize static factory for c++ foreign reference type"); | ||
synthCxxMethodDecl->setAccess(clang::AccessSpecifier::AS_public); | ||
|
||
llvm::SmallVector<clang::ParmVarDecl *, 4> synthParams; | ||
for (unsigned int i = 0; i < ctorParamCount; ++i) { | ||
auto *origParam = selectedCtorDecl->getParamDecl(i); | ||
fahadnayyar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
clang::IdentifierInfo *paramIdent = origParam->getIdentifier(); | ||
if (!paramIdent) { | ||
std::string dummyName = "__unnamed_param_" + std::to_string(i); | ||
paramIdent = &clangIdents.get(dummyName); | ||
} | ||
auto *param = clang::ParmVarDecl::Create( | ||
clangCtx, synthCxxMethodDecl, cxxRecordDeclLoc, cxxRecordDeclLoc, | ||
paramIdent, origParam->getType(), | ||
clangCtx.getTrivialTypeSourceInfo(origParam->getType()), | ||
clang::SC_None, /*DefArg=*/nullptr); | ||
param->setIsUsed(); | ||
synthParams.push_back(param); | ||
} | ||
synthCxxMethodDecl->setParams(synthParams); | ||
|
||
if (!hasImmortalAttrs(cxxRecordDecl)) { | ||
synthCxxMethodDecl->addAttr( | ||
clang::SwiftAttrAttr::Create(clangCtx, "returns_retained")); | ||
} | ||
|
||
std::string swiftInitStr = "init("; | ||
for (unsigned i = 0; i < ctorParamCount; ++i) { | ||
auto paramType = selectedCtorDecl->getParamDecl(i)->getType(); | ||
if (paramType->isRValueReferenceType()) { | ||
swiftInitStr += "consuming:"; | ||
} else { | ||
swiftInitStr += "_:"; | ||
} | ||
} | ||
swiftInitStr += ")"; | ||
synthCxxMethodDecl->addAttr( | ||
clang::SwiftNameAttr::Create(clangCtx, swiftInitStr)); | ||
|
||
llvm::SmallVector<clang::Expr *, 4> ctorArgs; | ||
for (auto *param : synthParams) { | ||
clang::QualType paramTy = param->getType(); | ||
clang::QualType exprTy = paramTy.getNonReferenceType(); | ||
clang::Expr *argExpr = clang::DeclRefExpr::Create( | ||
clangCtx, clang::NestedNameSpecifierLoc(), cxxRecordDeclLoc, param, | ||
/*RefersToEnclosingVariableOrCapture=*/false, cxxRecordDeclLoc, | ||
exprTy, clang::VK_LValue); | ||
if (paramTy->isRValueReferenceType()) { | ||
argExpr = clangSema | ||
.BuildCXXNamedCast( | ||
cxxRecordDeclLoc, clang::tok::kw_static_cast, | ||
clangCtx.getTrivialTypeSourceInfo(paramTy), argExpr, | ||
clang::SourceRange(), clang::SourceRange()) | ||
.get(); | ||
} | ||
ctorArgs.push_back(argExpr); | ||
} | ||
llvm::SmallVector<clang::Expr *, 4> ctorArgsToAdd; | ||
|
||
if (clangSema.CompleteConstructorCall(selectedCtorDecl, cxxRecordTy, | ||
fahadnayyar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
ctorArgs, cxxRecordDeclLoc, | ||
ctorArgsToAdd)) | ||
continue; | ||
|
||
clang::ExprResult synthCtorExprResult = clangSema.BuildCXXConstructExpr( | ||
cxxRecordDeclLoc, cxxRecordTy, selectedCtorDecl, | ||
/*Elidable=*/false, ctorArgsToAdd, | ||
/*HadMultipleCandidates=*/false, | ||
/*IsListInitialization=*/false, | ||
/*IsStdInitListInitialization=*/false, | ||
/*RequiresZeroInit=*/false, clang::CXXConstructionKind::Complete, | ||
clang::SourceRange(cxxRecordDeclLoc, cxxRecordDeclLoc)); | ||
assert(!synthCtorExprResult.isInvalid() && | ||
"Unable to synthesize constructor expression for c++ foreign " | ||
"reference type"); | ||
clang::Expr *synthCtorExpr = synthCtorExprResult.get(); | ||
|
||
clang::ExprResult synthNewExprResult = clangSema.BuildCXXNew( | ||
clang::SourceRange(), /*UseGlobal=*/false, clang::SourceLocation(), {}, | ||
clang::SourceLocation(), clang::SourceRange(), cxxRecordTy, | ||
clangCtx.getTrivialTypeSourceInfo(cxxRecordTy), std::nullopt, | ||
clang::SourceRange(cxxRecordDeclLoc, cxxRecordDeclLoc), synthCtorExpr); | ||
assert( | ||
!synthNewExprResult.isInvalid() && | ||
"Unable to synthesize `new` expression for c++ foreign reference type"); | ||
auto *synthNewExpr = cast<clang::CXXNewExpr>(synthNewExprResult.get()); | ||
|
||
clang::ReturnStmt *synthRetStmt = clang::ReturnStmt::Create( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: I wonder if we want to use |
||
clangCtx, cxxRecordDeclLoc, synthNewExpr, /*NRVOCandidate=*/nullptr); | ||
assert(synthRetStmt && "Unable to synthesize return statement for " | ||
"static factory of c++ foreign reference type"); | ||
|
||
clang::CompoundStmt *synthFuncBody = clang::CompoundStmt::Create( | ||
clangCtx, {synthRetStmt}, clang::FPOptionsOverride(), cxxRecordDeclLoc, | ||
cxxRecordDeclLoc); | ||
assert(synthRetStmt && "Unable to synthesize function body for static " | ||
"factory of c++ foreign reference type"); | ||
|
||
synthCxxMethodDecl->setBody(synthFuncBody); | ||
synthCxxMethodDecl->addAttr(clang::NoDebugAttr::CreateImplicit(clangCtx)); | ||
|
||
synthCxxMethodDecl->setImplicit(); | ||
synthCxxMethodDecl->setImplicitlyInline(); | ||
|
||
synthesizedFactories.push_back(synthCxxMethodDecl); | ||
} | ||
|
||
clang::SwiftNameAttr *swiftNameInitAttrForSynthesizedCxxMethodDecl = | ||
clang::SwiftNameAttr::Create(clangCtx, "init()"); | ||
synthesizedCxxMethodDecl->addAttr( | ||
swiftNameInitAttrForSynthesizedCxxMethodDecl); | ||
|
||
clang::ExprResult synthesizedConstructExprResult = | ||
clangSema.BuildCXXConstructExpr( | ||
clang::SourceLocation(), cxxRecordTy, defaultCtorDecl, | ||
/*Elidable=*/false, clang::MultiExprArg(), | ||
/*HadMultipleCandidates=*/false, | ||
/*IsListInitialization=*/false, | ||
/*IsStdInitListInitialization=*/false, | ||
/*RequiresZeroInit=*/false, clang::CXXConstructionKind::Complete, | ||
clang::SourceRange()); | ||
assert(!synthesizedConstructExprResult.isInvalid() && | ||
"Unable to synthesize constructor expression for c++ foreign " | ||
"reference type"); | ||
clang::CXXConstructExpr *synthesizedConstructExpr = | ||
cast<clang::CXXConstructExpr>(synthesizedConstructExprResult.get()); | ||
|
||
clang::ExprResult synthesizedNewExprResult = clangSema.BuildCXXNew( | ||
clang::SourceRange(), /*UseGlobal=*/false, clang::SourceLocation(), {}, | ||
clang::SourceLocation(), clang::SourceRange(), cxxRecordTy, | ||
clangCtx.getTrivialTypeSourceInfo(cxxRecordTy), std::nullopt, | ||
clang::SourceRange(), synthesizedConstructExpr); | ||
assert( | ||
!synthesizedNewExprResult.isInvalid() && | ||
"Unable to synthesize `new` expression for c++ foreign reference type"); | ||
clang::CXXNewExpr *synthesizedNewExpr = | ||
cast<clang::CXXNewExpr>(synthesizedNewExprResult.get()); | ||
|
||
clang::ReturnStmt *synthesizedRetStmt = | ||
clang::ReturnStmt::Create(clangCtx, clang::SourceLocation(), | ||
synthesizedNewExpr, /*VarDecl=*/nullptr); | ||
assert(synthesizedRetStmt && "Unable to synthesize return statement for " | ||
"static factory of c++ foreign reference type"); | ||
|
||
clang::CompoundStmt *synthesizedFuncBody = clang::CompoundStmt::Create( | ||
clangCtx, {synthesizedRetStmt}, clang::FPOptionsOverride(), | ||
clang::SourceLocation(), clang::SourceLocation()); | ||
assert(synthesizedRetStmt && "Unable to synthesize function body for static " | ||
"factory of c++ foreign reference type"); | ||
|
||
synthesizedCxxMethodDecl->setBody(synthesizedFuncBody); | ||
synthesizedCxxMethodDecl->addAttr( | ||
clang::NoDebugAttr::CreateImplicit(clangCtx)); | ||
|
||
synthesizedCxxMethodDecl->setImplicit(); | ||
synthesizedCxxMethodDecl->setImplicitlyInline(); | ||
|
||
return synthesizedCxxMethodDecl; | ||
return synthesizedFactories; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.