Skip to content

[cxx-interop] Instantiate C++ class templates from Swift #33284

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
merged 42 commits into from
Jan 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
7eabc27
This change makes it possible to instantiate C++ class templates from…
hlopko Oct 7, 2020
c719f9c
Bump SWIFTMODULE_VERSION
hlopko Oct 8, 2020
0a96791
Remove unreachable diagnostics
hlopko Oct 8, 2020
e20c02a
Rename instantiateTemplates
hlopko Oct 8, 2020
2ef9409
Fix tests
hlopko Oct 8, 2020
d6db3b6
Add failing test for defaulted params
hlopko Oct 8, 2020
1298f8b
Add more failing tests
hlopko Oct 8, 2020
0194ace
Cleanup module interface test
hlopko Oct 12, 2020
7feb939
Merge branch 'main' into class_templates
hlopko Oct 27, 2020
53fcea6
Fixes
hlopko Oct 27, 2020
156f2ed
Use getClangTemplateArguments
hlopko Oct 28, 2020
5f2a2a5
Merge branch 'main' into class_templates
hlopko Nov 5, 2020
1d98588
Fix symbol visitibity test
hlopko Nov 5, 2020
712b0d6
Merge branch 'main' into class_templates
hlopko Nov 5, 2020
4cb3724
Dont use String because on mac it will turn to be NSString
hlopko Nov 5, 2020
4126fd9
Add CInt test
hlopko Nov 6, 2020
c75d5e9
Add test
hlopko Nov 6, 2020
2b01aec
Update include/swift/AST/DiagnosticsSema.def
Nov 23, 2020
dda24ec
Update lib/ClangImporter/ClangImporter.cpp
Nov 23, 2020
e79199a
Address comments
hlopko Nov 24, 2020
9f8f8da
Merge branch 'main' into class_templates
hlopko Dec 2, 2020
27b6990
Update test/Interop/Cxx/templates/Inputs/SwiftClassInstantiationModul…
Dec 2, 2020
fd1c618
Address comments
hlopko Dec 2, 2020
51ca547
Merge branch 'class_templates' of github.com:hlopko/swift into class_…
hlopko Dec 3, 2020
0101196
Merge main
hlopko Jan 5, 2021
16493b3
Merge branch 'main' into class_templates
hlopko Jan 18, 2021
fb7974a
Add some header guards
hlopko Jan 19, 2021
1ba9340
Fix bad merge
hlopko Jan 19, 2021
dafab23
Add simple tests for templates with namespaces
hlopko Jan 19, 2021
090f159
WIP
hlopko Jan 21, 2021
c89f07c
WIP
hlopko Jan 22, 2021
b5ecc40
Serialize clang template type before instantiation
hlopko Jan 25, 2021
e3641c1
Cleanup
hlopko Jan 25, 2021
4e5fb25
Polish
hlopko Jan 25, 2021
e9a44d4
Polish
hlopko Jan 25, 2021
71a9065
Add (failing) test for nested types
hlopko Jan 25, 2021
4d09706
Merge branch 'main' into class_templates
hlopko Jan 25, 2021
c082a8c
Fix test
hlopko Jan 25, 2021
3bfdce6
Merge branch 'main' into class_templates
hlopko Jan 26, 2021
22e8eda
Update lib/Serialization/Deserialization.cpp
Jan 26, 2021
435a796
Update test/Interop/Cxx/templates/class-template-instantiation-existi…
Jan 26, 2021
ff7cdc3
Addressing comments.
hlopko Jan 26, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions include/swift/AST/ClangModuleLoader.h
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,16 @@ class ClangModuleLoader : public ModuleLoader {
StringRef relatedEntityKind,
llvm::function_ref<void(TypeDecl *)> receiver) = 0;

/// Instantiate and import class template using given arguments.
///
/// This method will find the clang::ClassTemplateSpecialization decl if
/// it already exists, or it will create one. Then it will import this
/// decl the same way as we import typedeffed class templates - using
/// the hidden struct prefixed with `__CxxTemplateInst`.
virtual StructDecl *
instantiateCXXClassTemplate(clang::ClassTemplateDecl *decl,
ArrayRef<clang::TemplateArgument> arguments) = 0;

/// Try to parse the string as a Clang function type.
///
/// Returns null if there was a parsing failure.
Expand Down
39 changes: 39 additions & 0 deletions include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -3402,6 +3402,42 @@ class EnumDecl final : public NominalTypeDecl {
class StructDecl final : public NominalTypeDecl {
SourceLoc StructLoc;

// We import C++ class templates as generic structs. Then when in Swift code
// we want to substitude generic parameters with actual arguments, we
// convert the arguments to C++ equivalents and ask Clang to instantiate the
// C++ template. Then we import the C++ class template instantiation
// as a non-generic structs with a name prefixed with `__CxxTemplateInst`.
//
// To reiterate:
// 1) We need to have a C++ class template declaration in the Clang AST. This
// declaration is simply imported from a Clang module.
// 2) We need a Swift generic struct in the Swift AST. This will provide
// template arguments to Clang.
// 3) We produce a C++ class template instantiation in the Clang AST
// using 1) and 2). This declaration does not exist in the Clang module
// AST initially in the general case, it's added there on instantiation.
// 4) We import the instantiation as a Swift struct, with the name prefixed
// with `__CxxTemplateInst`.
//
// This causes a problem for serialization/deserialization of the Swift
// module. Imagine the Swift struct from 4) is used in the function return
// type. We cannot just serialize the non generic Swift struct, because on
// deserialization we would need to find its backing Clang declaration
// (the C++ class template instantiation), and it won't be found in the
// general case. Only the C++ class template from step 1) is in the Clang
// AST.
//
// What we need is to serialize enough information to be
// able to instantiate C++ class template on deserialization. It turns out
// that all that information is conveniently covered by the BoundGenericType,
// which we store in this field. The field is set during the typechecking at
// the time when we instantiate the C++ class template.
//
// Alternative, and likely better solution long term, is to serialize the
// C++ class template instantiation into a synthetic Clang module, and load
// this Clang module on deserialization.
Type TemplateInstantiationType = Type();

public:
StructDecl(SourceLoc StructLoc, Identifier Name, SourceLoc NameLoc,
ArrayRef<TypeLoc> Inherited,
Expand Down Expand Up @@ -3445,6 +3481,9 @@ class StructDecl final : public NominalTypeDecl {
bool isCxxNonTrivial() const { return Bits.StructDecl.IsCxxNonTrivial; }

void setIsCxxNonTrivial(bool v) { Bits.StructDecl.IsCxxNonTrivial = v; }

Type getTemplateInstantiationType() const { return TemplateInstantiationType; }
void setTemplateInstantiationType(Type t) { TemplateInstantiationType = t; }
};

/// This is the base type for AncestryOptions. Each flag describes possible
Expand Down
4 changes: 4 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -2789,6 +2789,10 @@ ERROR(unexportable_clang_function_type,none,
"it may use anonymous types or types defined outside of a module",
(Type))

ERROR(cxx_class_instantiation_failed,none,
"couldn't instantiate a C++ class template",
())

WARNING(warn_implementation_only_conflict,none,
"%0 inconsistently imported as implementation-only",
(Identifier))
Expand Down
4 changes: 4 additions & 0 deletions include/swift/ClangImporter/ClangImporter.h
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,10 @@ class ClangImporter final : public ClangModuleLoader {
StringRef relatedEntityKind,
llvm::function_ref<void(TypeDecl *)> receiver) override;

StructDecl *
instantiateCXXClassTemplate(clang::ClassTemplateDecl *decl,
ArrayRef<clang::TemplateArgument> arguments) override;

/// Just like Decl::getClangNode() except we look through to the 'Code'
/// enum of an error wrapper struct.
ClangNode getEffectiveClangNode(const Decl *decl) const;
Expand Down
22 changes: 22 additions & 0 deletions lib/ClangImporter/ClangImporter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4150,3 +4150,25 @@ clang::FunctionDecl *ClangImporter::instantiateCXXFunctionTemplate(
sema.InstantiateFunctionDefinition(clang::SourceLocation(), spec);
return spec;
}

StructDecl *
ClangImporter::instantiateCXXClassTemplate(
clang::ClassTemplateDecl *decl,
ArrayRef<clang::TemplateArgument> arguments) {
void *InsertPos = nullptr;
auto *ctsd = decl->findSpecialization(arguments, InsertPos);
if (!ctsd) {
ctsd = clang::ClassTemplateSpecializationDecl::Create(
decl->getASTContext(), decl->getTemplatedDecl()->getTagKind(),
decl->getDeclContext(), decl->getTemplatedDecl()->getBeginLoc(),
decl->getLocation(), decl, arguments, nullptr);
decl->AddSpecialization(ctsd, InsertPos);
}

auto CanonType = decl->getASTContext().getTypeDeclType(ctsd);
assert(isa<clang::RecordType>(CanonType) &&
"type of non-dependent specialization is not a RecordType");

return dyn_cast_or_null<StructDecl>(
Impl.importDecl(ctsd, Impl.CurrentVersion));
}
57 changes: 37 additions & 20 deletions lib/ClangImporter/ImportDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3575,13 +3575,6 @@ namespace {
decl->getDefinition());
assert(def && "Class template instantiation didn't have definition");

// If this type is fully specialized (i.e. "Foo<>" or "Foo<int, int>"),
// bail to prevent a crash.
// TODO: we should be able to support fully specialized class templates.
// See SR-13775 for more info.
if (def->getTypeAsWritten())
return nullptr;

// FIXME: This will instantiate all members of the specialization (and detect
// instantiation failures in them), which can be more than is necessary
// and is more than what Clang does. As a result we reject some C++
Expand All @@ -3592,19 +3585,6 @@ namespace {
return VisitCXXRecordDecl(def);
}

Decl *VisitClassTemplateDecl(const clang::ClassTemplateDecl *decl) {
// When loading a namespace's sub-decls, we won't add template
// specilizations, so make sure to do that here.
for (auto spec : decl->specializations()) {
if (auto importedSpec = Impl.importDecl(spec, getVersion())) {
if (auto namespaceDecl =
dyn_cast<EnumDecl>(importedSpec->getDeclContext()))
namespaceDecl->addMember(importedSpec);
}
}
return nullptr;
}

Decl *VisitClassTemplatePartialSpecializationDecl(
const clang::ClassTemplatePartialSpecializationDecl *decl) {
// Note: partial template specializations are not imported.
Expand Down Expand Up @@ -4256,6 +4236,43 @@ namespace {
correctSwiftName, None, decl);
}

Decl *VisitClassTemplateDecl(const clang::ClassTemplateDecl *decl) {
// When loading a namespace's sub-decls, we won't add template
// specilizations, so make sure to do that here.
for (auto spec : decl->specializations()) {
if (auto importedSpec = Impl.importDecl(spec, getVersion())) {
if (auto namespaceDecl =
dyn_cast<EnumDecl>(importedSpec->getDeclContext()))
namespaceDecl->addMember(importedSpec);
}
}

Optional<ImportedName> correctSwiftName;
auto importedName = importFullName(decl, correctSwiftName);
auto name = importedName.getDeclName().getBaseIdentifier();
if (name.empty())
return nullptr;
auto loc = Impl.importSourceLoc(decl->getLocation());
auto dc = Impl.importDeclContextOf(
decl, importedName.getEffectiveContext());

SmallVector<GenericTypeParamDecl *, 4> genericParams;
for (auto &param : *decl->getTemplateParameters()) {
auto genericParamDecl = Impl.createDeclWithClangNode<GenericTypeParamDecl>(
param, AccessLevel::Public, dc,
Impl.SwiftContext.getIdentifier(param->getName()),
Impl.importSourceLoc(param->getLocation()),
/*depth*/ 0, /*index*/ genericParams.size());
genericParams.push_back(genericParamDecl);
}
auto genericParamList = GenericParamList::create(
Impl.SwiftContext, loc, genericParams, loc);

auto structDecl = Impl.createDeclWithClangNode<StructDecl>(
decl, AccessLevel::Public, loc, name, loc, None, genericParamList, dc);
return structDecl;
}

Decl *VisitUsingDecl(const clang::UsingDecl *decl) {
// Using declarations are not imported.
return nullptr;
Expand Down
43 changes: 43 additions & 0 deletions lib/Sema/TypeCheckType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/Strings.h"
#include "swift/Subsystems.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclTemplate.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
Expand Down Expand Up @@ -834,6 +837,46 @@ static Type applyGenericArguments(Type type, TypeResolution resolution,
diags.diagnose(loc, diag::use_of_void_pointer, "").
fixItReplace(generic->getSourceRange(), "UnsafeRawPointer");
}

if (auto clangDecl = decl->getClangDecl()) {
if (auto classTemplateDecl =
dyn_cast<clang::ClassTemplateDecl>(clangDecl)) {
SmallVector<Type, 2> typesOfGenericArgs;
for (auto typeRepr : generic->getGenericArgs()) {
typesOfGenericArgs.push_back(resolution.resolveType(typeRepr));
}

SmallVector<clang::TemplateArgument, 2> templateArguments;
std::unique_ptr<TemplateInstantiationError> error =
ctx.getClangTemplateArguments(
classTemplateDecl->getTemplateParameters(), typesOfGenericArgs,
templateArguments);

if (error) {
std::string failedTypesStr;
llvm::raw_string_ostream failedTypesStrStream(failedTypesStr);
llvm::interleaveComma(error->failedTypes, failedTypesStrStream);
// TODO: This error message should not reference implementation details.
// See: https://github.com/apple/swift/pull/33053#discussion_r477003350
ctx.Diags.diagnose(
loc, diag::unable_to_convert_generic_swift_types.ID,
{classTemplateDecl->getName(), StringRef(failedTypesStr)});
return ErrorType::get(ctx);
}

auto *clangModuleLoader = decl->getASTContext().getClangModuleLoader();
auto instantiatedDecl = clangModuleLoader->instantiateCXXClassTemplate(
const_cast<clang::ClassTemplateDecl *>(classTemplateDecl),
templateArguments);
if (instantiatedDecl) {
instantiatedDecl->setTemplateInstantiationType(result);
return instantiatedDecl->getDeclaredInterfaceType();
} else {
diags.diagnose(loc, diag::cxx_class_instantiation_failed);
return ErrorType::get(ctx);
}
}
}
return result;
}

Expand Down
26 changes: 26 additions & 0 deletions lib/Serialization/Deserialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Statistic.h"
#include "clang/AST/DeclTemplate.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
Expand Down Expand Up @@ -5353,6 +5354,31 @@ class TypeDeserializer {
genericArgs.push_back(argTy.get());
}

if (auto clangDecl = nominal->getClangDecl()) {
if (auto ctd = dyn_cast<clang::ClassTemplateDecl>(clangDecl)) {
auto clangImporter = static_cast<ClangImporter *>(
nominal->getASTContext().getClangModuleLoader());

SmallVector<Type, 2> typesOfGenericArgs;
for (auto arg : genericArgs) {
typesOfGenericArgs.push_back(arg);
}

SmallVector<clang::TemplateArgument, 2> templateArguments;
std::unique_ptr<TemplateInstantiationError> error =
ctx.getClangTemplateArguments(ctd->getTemplateParameters(),
typesOfGenericArgs,
templateArguments);

auto instantiation = clangImporter->instantiateCXXClassTemplate(
const_cast<clang::ClassTemplateDecl *>(ctd), templateArguments);

instantiation->setTemplateInstantiationType(
BoundGenericType::get(nominal, parentTy, genericArgs));
return instantiation->getDeclaredInterfaceType();
}
}

return BoundGenericType::get(nominal, parentTy, genericArgs);
}

Expand Down
20 changes: 17 additions & 3 deletions lib/Serialization/Serialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
#include "swift/Demangling/ManglingMacros.h"
#include "swift/Serialization/SerializationOptions.h"
#include "swift/Strings.h"
#include "clang/AST/DeclTemplate.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
Expand All @@ -73,6 +74,7 @@ using namespace llvm::support;
using swift::version::Version;
using llvm::BCBlockRAII;


ASTContext &SerializerBase::getASTContext() {
return M->getASTContext();
}
Expand Down Expand Up @@ -626,13 +628,25 @@ DeclID Serializer::addDeclRef(const Decl *D, bool allowTypeAliasXRef) {
}

serialization::TypeID Serializer::addTypeRef(Type ty) {
Type typeToSerialize = ty;
if (ty) {
if (auto nominalDecl = ty->getAnyNominal()) {
if (auto structDecl = dyn_cast<StructDecl>(nominalDecl)) {
if (auto templateInstantiationType =
structDecl->getTemplateInstantiationType()) {
typeToSerialize = templateInstantiationType;
}
}
}
}

#ifndef NDEBUG
PrettyStackTraceType trace(M->getASTContext(), "serializing", ty);
PrettyStackTraceType trace(M->getASTContext(), "serializing", typeToSerialize);
assert(M->getASTContext().LangOpts.AllowModuleWithCompilerErrors ||
!ty || !ty->hasError() && "serializing type with an error");
!typeToSerialize || !typeToSerialize->hasError() && "serializing type with an error");
#endif

return TypesToSerialize.addRef(ty);
return TypesToSerialize.addRef(typeToSerialize);
}

serialization::ClangTypeID Serializer::addClangTypeRef(const clang::Type *ty) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import ClassTemplateForSwiftModule

public func makeWrappedMagicNumber() -> MagicWrapper<IntWrapper> {
let t = IntWrapper(value: 42)
return MagicWrapper<IntWrapper>(t: t)
}

public func readWrappedMagicNumber(_ i: inout MagicWrapper<IntWrapper>) -> CInt {
return i.getValuePlusArg(13)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import ClassTemplateInNamespaceForSwiftModule

public func receiveShip(_ i: inout Space.Ship<Bool>) {}

public func returnShip() -> Space.Ship<Bool> {
return Space.Ship<Bool>()
}

public func receiveShipWithEngine(_ i: inout Space.Ship<Engine.Turbojet>) {}

public func returnShipWithEngine() -> Space.Ship<Engine.Turbojet> {
return Space.Ship<Engine.Turbojet>()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import ClassTemplateNestedTypeForSwiftModule

public func receiveShipEngine(_ i: inout Ship<Bool>.Engine) {}

public func returnShipEngine() -> Ship<Bool>.Engine {
return Ship<Bool>.Engine()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#ifndef TEST_INTEROP_CXX_TEMPLATES_INPUTS_CLASS_TEMPLATE_FOR_SWIFT_MODULE_H
#define TEST_INTEROP_CXX_TEMPLATES_INPUTS_CLASS_TEMPLATE_FOR_SWIFT_MODULE_H

struct IntWrapper {
int value;
int getValue() const { return value; }
};

template<class T>
struct MagicWrapper {
T t;
int getValuePlusArg(int arg) const { return t.getValue() + arg; }
};

#endif // TEST_INTEROP_CXX_TEMPLATES_INPUTS_CLASS_TEMPLATE_FOR_SWIFT_MODULE_H
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#ifndef TEST_INTEROP_CXX_TEMPLATES_INPUTS_CLASS_TEMPLATE_IN_NAMESPACE_FOR_SWIFT_MODULE_H
#define TEST_INTEROP_CXX_TEMPLATES_INPUTS_CLASS_TEMPLATE_IN_NAMESPACE_FOR_SWIFT_MODULE_H

namespace Space {
template <class T> struct Ship { T t; };
} // namespace Space

namespace Engine {
struct Turbojet {};
} // namespace Engine

#endif // TEST_INTEROP_CXX_TEMPLATES_INPUTS_CLASS_TEMPLATE_IN_NAMESPACE_FOR_SWIFT_MODULE_H
Loading