Skip to content

[cxx-interop] Add rules to recognize escapability of aggregates #76673

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 1 commit into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
43 changes: 41 additions & 2 deletions include/swift/ClangImporter/ClangImporterRequests.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@
#ifndef SWIFT_CLANG_IMPORTER_REQUESTS_H
#define SWIFT_CLANG_IMPORTER_REQUESTS_H

#include "swift/AST/SimpleRequest.h"
#include "swift/AST/ASTTypeIDs.h"
#include "swift/AST/EvaluatorDependencies.h"
#include "swift/AST/FileUnit.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/SimpleRequest.h"
#include "swift/Basic/Statistic.h"
#include "clang/AST/Type.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/TinyPtrVector.h"

Expand Down Expand Up @@ -500,6 +500,45 @@ class CustomRefCountingOperation
CustomRefCountingOperationDescriptor desc) const;
};

enum class CxxEscapability { Escapable, NonEscapable, Unknown };

struct EscapabilityLookupDescriptor final {
const clang::Type *type;

friend llvm::hash_code hash_value(const EscapabilityLookupDescriptor &desc) {
return llvm::hash_combine(desc.type);
}

friend bool operator==(const EscapabilityLookupDescriptor &lhs,
const EscapabilityLookupDescriptor &rhs) {
return lhs.type == rhs.type;
}

friend bool operator!=(const EscapabilityLookupDescriptor &lhs,
const EscapabilityLookupDescriptor &rhs) {
return !(lhs == rhs);
}
};

class ClangTypeEscapability
: public SimpleRequest<ClangTypeEscapability,
CxxEscapability(EscapabilityLookupDescriptor),
RequestFlags::Cached> {
public:
using SimpleRequest::SimpleRequest;

bool isCached() const { return true; }

private:
friend SimpleRequest;

CxxEscapability evaluate(Evaluator &evaluator,
EscapabilityLookupDescriptor desc) const;
};

void simple_display(llvm::raw_ostream &out, EscapabilityLookupDescriptor desc);
SourceLoc extractNearestSourceLoc(EscapabilityLookupDescriptor desc);

#define SWIFT_TYPEID_ZONE ClangImporter
#define SWIFT_TYPEID_HEADER "swift/ClangImporter/ClangImporterTypeIDZone.def"
#include "swift/Basic/DefineTypeIDZone.h"
Expand Down
3 changes: 3 additions & 0 deletions include/swift/ClangImporter/ClangImporterTypeIDZone.def
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,6 @@ SWIFT_REQUEST(ClangImporter, IsSafeUseOfCxxDecl,
SWIFT_REQUEST(ClangImporter, CustomRefCountingOperation,
CustomRefCountingOperationResult(CustomRefCountingOperationDescriptor), Cached,
NoLocationInfo)
SWIFT_REQUEST(ClangImporter, ClangTypeEscapability,
CxxEscapability(EscapabilityLookupDescriptor), Cached,
NoLocationInfo)
70 changes: 70 additions & 0 deletions lib/ClangImporter/ClangImporter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@
#include "swift/Strings.h"
#include "swift/Subsystems.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/Type.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileEntry.h"
#include "clang/Basic/IdentifierTable.h"
Expand Down Expand Up @@ -5018,6 +5020,74 @@ TinyPtrVector<ValueDecl *> CXXNamespaceMemberLookup::evaluate(
return result;
}

CxxEscapability
ClangTypeEscapability::evaluate(Evaluator &evaluator,
EscapabilityLookupDescriptor desc) const {
auto desugared = desc.type->getUnqualifiedDesugaredType();
if (const auto *recordType = desugared->getAs<clang::RecordType>()) {
if (importer::hasNonEscapableAttr(recordType->getDecl()))
return CxxEscapability::NonEscapable;
if (importer::hasEscapableAttr(recordType->getDecl()))
return CxxEscapability::Escapable;
auto recordDecl = recordType->getDecl();
auto cxxRecordDecl = dyn_cast<clang::CXXRecordDecl>(recordDecl);
if (!cxxRecordDecl || cxxRecordDecl->isAggregate()) {
bool hadUnknown = false;
auto evaluateEscapability = [&](const clang::Type *type) {
auto escapability = evaluateOrDefault(
evaluator, ClangTypeEscapability({type}), CxxEscapability::Unknown);
if (escapability == CxxEscapability::Unknown)
hadUnknown = true;
return escapability;
};

if (cxxRecordDecl) {
for (auto base : cxxRecordDecl->bases()) {
auto baseEscapability = evaluateEscapability(
base.getType()->getUnqualifiedDesugaredType());
if (baseEscapability == CxxEscapability::NonEscapable)
return CxxEscapability::NonEscapable;
}
}

for (auto field : recordDecl->fields()) {
auto fieldEscapability = evaluateEscapability(
field->getType()->getUnqualifiedDesugaredType());
if (fieldEscapability == CxxEscapability::NonEscapable)
return CxxEscapability::NonEscapable;
}

return hadUnknown ? CxxEscapability::Unknown : CxxEscapability::Escapable;
}
}
if (desugared->isArrayType()) {
auto elemTy = cast<clang::ArrayType>(desugared)
->getElementType()
->getUnqualifiedDesugaredType();
return evaluateOrDefault(evaluator, ClangTypeEscapability({elemTy}),
CxxEscapability::Unknown);
}

// Base cases
if (desugared->isAnyPointerType() || desugared->isBlockPointerType() ||
desugared->isMemberPointerType() || desugared->isReferenceType())
return CxxEscapability::NonEscapable;
if (desugared->isScalarType())
return CxxEscapability::Escapable;
return CxxEscapability::Unknown;
}

void swift::simple_display(llvm::raw_ostream &out,
EscapabilityLookupDescriptor desc) {
out << "Computing escapability for type '";
out << clang::QualType(desc.type, 0).getAsString();
out << "'";
}

SourceLoc swift::extractNearestSourceLoc(EscapabilityLookupDescriptor) {
return SourceLoc();
}

// Just create a specialized function decl for "__swift_interopStaticCast"
// using the types base and derived.
static
Expand Down
9 changes: 4 additions & 5 deletions lib/ClangImporter/ImportDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8155,8 +8155,7 @@ bool swift::importer::isMutabilityAttr(const clang::SwiftAttrAttr *swiftAttr) {
swiftAttr->getAttribute() == "nonmutating";
}

static bool importAsUnsafe(const ASTContext &context,
const clang::RecordDecl *decl,
static bool importAsUnsafe(ASTContext &context, const clang::RecordDecl *decl,
const Decl *MappedDecl) {
if (!context.LangOpts.hasFeature(Feature::SafeInterop) ||
!context.LangOpts.hasFeature(Feature::AllowUnsafeAttribute) || !decl)
Expand All @@ -8165,9 +8164,9 @@ static bool importAsUnsafe(const ASTContext &context,
if (isa<ClassDecl>(MappedDecl))
return false;

// TODO: Add logic to cover structural rules.
return !importer::hasNonEscapableAttr(decl) &&
!importer::hasEscapableAttr(decl);
return evaluateOrDefault(
context.evaluator, ClangTypeEscapability({decl->getTypeForDecl()}),
CxxEscapability::Unknown) == CxxEscapability::Unknown;
}

void
Expand Down
19 changes: 17 additions & 2 deletions test/Interop/Cxx/class/safe-interop-mode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,22 @@ private:

struct SWIFT_ESCAPABLE Owner {};

struct Unannotated {};
struct Unannotated {
Unannotated();
};

struct SWIFT_UNSAFE_REFERENCE UnsafeReference {};

struct SafeEscapableAggregate {
int a;
float b[5];
};

struct UnknownEscapabilityAggregate {
SafeEscapableAggregate agg;
Unannotated unann;
};

//--- test.swift

import Test
Expand All @@ -42,7 +54,10 @@ func useUnsafeParam(x: Unannotated) { // expected-warning{{reference to unsafe s
func useUnsafeParam2(x: UnsafeReference) { // expected-warning{{reference to unsafe class 'UnsafeReference'}}
}

func useSafeParams(x: Owner, y: View) {
func useUnsafeParam3(x: UnknownEscapabilityAggregate) { // expected-warning{{reference to unsafe struct 'UnknownEscapabilityAggregate'}}
}

func useSafeParams(x: Owner, y: View, z: SafeEscapableAggregate) {
}

func useCfType(x: CFArray) {
Expand Down