Commit Graph

2546 Commits

Author SHA1 Message Date
Henrik G. Olsson
6a9ac22cd2 Merge pull request #84507 from hnrklssn/swiftify-import-as-method
[Swiftify] Add support for free functions imported as instance methods

(cherry picked from commit ed4f058c01)
2025-10-07 20:12:44 -07:00
Egor Zhdan
c5c33d6c5a [cxx-interop] Allow retain/release operations to be methods
Some foreign reference types such as IUnknown define retain/release operations as methods of the type.

Previously Swift only supported retain/release operations as standalone functions.

The syntax for member functions would be `SWIFT_SHARED_REFERENCE(.doRetain, .doRelease)`.

rdar://160696723
(cherry picked from commit e78ce6165f)
2025-09-23 14:45:41 +01:00
Gábor Horváth
859f60d4d4 Merge pull request #84120 from Xazax-hun/no-vwt-for-anon-types-on-6.2
[6.2][cxx-interop] Basic support for anonymous structs with non-copyable fields
2025-09-17 15:38:33 +02:00
Gábor Horváth
95ff51c739 Merge pull request #84199 from Xazax-hun/no-reflection-anon-types
[cxx-interop] Restrict the uses of anonymous types
2025-09-11 09:56:35 +01:00
Egor Zhdan
7b6b576d45 [cxx-interop] Avoid trying to instantiate copy constructor of std::optional<NonCopyable>
In libc++, `std::optional` inherits from several mixin base types. Some of those base types do not declare a deleted copy constructor for non-copyable value types, which works fine because clients are not supposed to use those base types directly from C++.

Swift, however, imports all of the transitive base types when importing a C++ type. As part of this, ClangImporter will attempt to instantiate e.g. `std::__optional_copy_assign_base<NonCopyable>`, and will fail with a hard error while doing so.

rdar://152718041

(cherry picked from commit 124055a51a)
2025-09-10 18:42:26 +01:00
Gábor Horváth
e58347e8d2 [6.2][cxx-interop] Basic support for anonymous structs with non-copyable fields
Explanation: Anonymous structs cannot be copied or moved, these operations only
can happen to their enclosing non-anonymous types. Stop trying to emit special
member functions and value witness tables for these structs. This fix is
required to unblock a high priority libc++ change that fixes an
unintended ABI break.
Issues: rdar://159928354
Original PRs: #84105
Risk: Medium. I believe this is the right change but hard to anticipate
if something depends on the presence of these operations (which is
likely to be a bug). But this is required to unblock an important libc++
fix.
Testing: Added a compiler test.
Reviewers: @rjmccall
2025-09-05 10:53:46 +01:00
susmonteiro
29e5549e44 [6.2][cxx-interop] Prevent crash when importing a std::optional of nonescapable
When we tried to create a std::optional of a nonescapable type in Swift, the compiler would run into an assertion failure.
This is because std::optional has an anonymous union where one of its members would be of this nonescapable type.

Turns out that we were not handling anonymous unions with nonescapable members correctly.
Fields of anonymous unions are injected to the parent as IndirectFieldDecl, so we need to handle these indirect fields the same way we handle "normal" fields.

rdar://156704699
2025-09-04 16:21:21 +01:00
Gábor Horváth
cda402c225 [6.2][cxx-interop] Do not define inherited copy/move operations
Explanationi: When inheriting constructors, we define the inherited ctors in the derived class. We should not do that for copy and move operations as these operations can never be invoked (the implicit/defined/deleted ctor in the derived class always takes precedence). This fixes an issue where the lifetime parameters are not getting inferred for these spurious constructor definitions. This should also save us from doing some redundant work in the importer.
Issues: rdar://153081347
Original PRs: #83694
Risk: Low, we do not import some ctors that can never be called.
Testing: Added a compiler test.
Reviewers: @egorzhdan
2025-09-03 11:30:03 +01:00
Egor Zhdan
eaf9a80ab8 Merge pull request #83810 from egorzhdan/egorzhdan/6.2-c-frt-validation
🍒[cxx-interop] Validate C foreign reference types
2025-08-21 09:55:26 +01:00
Egor Zhdan
a57432aae9 Merge pull request #83815 from egorzhdan/egorzhdan/6.2-retain-release-unsigned
🍒[cxx-interop] Allow retain/release operations to return an unsigned integer
2025-08-20 02:58:41 +01:00
Egor Zhdan
44429648ea [cxx-interop] Allow retain/release operations to return an unsigned integer
Release/retain functions for C++ foreign reference types might return a reference count as an integer value.

Swift previously emitted an error for such functions, saying that the retain/release functions need to return void or a reference to the value.

rdar://157853183

(cherry picked from commit 3887ed0637)
2025-08-19 18:11:18 +01:00
Egor Zhdan
fd7b7fede2 [cxx-interop] Validate C foreign reference types
Swift validates the retain/release operations for foreign reference types to check for obvious errors, e.g. a wrong parameter type or return type.

That logic was only running for C++ foreign reference types. This patch enables it for C foreign reference types as well.

rdar://158609723
(cherry picked from commit c73f528b82)
2025-08-19 15:09:39 +01:00
Crazy凡
21f23dcebb [c++ interop] Swift should allow multiple SWIFT_CONFORMS_TO_PROTOCOL attributes on a C++ class.
(cherry picked from commit c05d1fc135)
2025-08-12 12:19:59 -07:00
Doug Gregor
89018a7ec8 [Clang importer] Diagnose various issues with the new "destroy:"
When we cannot respect the "destroy:" annotation, mark the type as
deprecated with a message thst says why there is a problem. There are
various potential problems:

* Multiple conflicting destroy functions
* Destroy functions that don't meet the pattern
* Type isn't imported as a move-only type
* Type has a non-trivial destructor (in C++)

(cherry picked from commit 63135e8929)
2025-08-12 11:29:24 -07:00
Doug Gregor
8b10bdc189 [Clang importer] Allow noncopyable C structs to define "destroy" operation
A C struct can be imported as noncopyable, but C doesn't have
destructors, so there is no way to provide user-defined logic to
perform the destruction. Introduce a new swift_attr that applies to
imported noncopyable types and which provides such a "destroy"
operation. It can be used like this:

    typedef struct __attribute__((swift_attr("~Copyable")))
                   __attribute__((swift_attr("destroy:wgpuAdapterInfoFreeMembers")))
      WGPUAdapterInfo { /*...*/ } WGPUAdapterInfo;

    void wgpuAdapterInfoFreeMembers(WGPUAdapterInfo adapterInfo);

This will bring the WGPUAdapterInfo struct in as a noncopyable type
that will be cleaned up by calling wgpuAdapterInfoFreeMembers once it
is no longer in use.

Implements rdar://156889370.

(cherry picked from commit 6ba560fb4b)
2025-08-12 11:27:54 -07:00
Doug Gregor
8a4d30c620 [Clang importer] Handle Swift conformances on typedefs and C types
The code for handling Swift conforms_to attributes was specific to
C++ record types. Generalize it to work on typedefs imported as
nominal types, also in C.

Fixes rdar://156290361.

(cherry picked from commit c5db5cced5)
2025-08-12 11:27:50 -07:00
Egor Zhdan
7a67b350e9 [cxx-interop] Enable foreign reference types in C interop
Most of the logic for C++ foreign reference types can be applied to C types as well. Swift had a compiler flag `-Xfrontend -experimental-c-foreign-reference-types` for awhile now which enables foreign reference types without having to enable C++ interop. This change makes it the default behavior.

Since we don't expect anyone to pass `experimental-c-foreign-reference-types` currently, this also removes the frontend flag.

rdar://150308819
(cherry picked from commit 9178af3ec7)
2025-08-12 11:22:27 -07:00
Henrik G. Olsson
43d8b13cf1 Merge pull request #82644 from hnrklssn/cherry-pick-macro-adjustment-check
Cherry-pick "Merge pull request #81855 from hnrklssn/swiftify-availability-check-sdk"
2025-07-03 11:07:43 -07:00
Anthony Latsis
6ddd1c95f3 Merge pull request #82664 from swiftlang/jepa2-6.2
[6.2] Sema: Fix the insertion location for conformances attributes
2025-07-02 16:51:55 +01:00
Anthony Latsis
1f28a04d29 Sema: Fix the insertion location for conformances attributes 2025-07-01 02:58:48 +01:00
Henrik G. Olsson
9de099a4b0 Merge pull request #81855 from hnrklssn/swiftify-availability-check-sdk
[Swiftify] Adjust _SwiftifyImport invocation to align with the signature

(cherry picked from commit e9ba8f8a03)
2025-06-30 12:02:55 -07:00
Henrik G. Olsson
8db1ad6222 Cherry-pick [Swiftify] Don't import counted_by with suffixed integer literals (#82469) (#82594)
Integer literal expressions with types that are not of type `int` are
printed with a suffix to indicate the type (e.g. `123U` or `456L` for
`unsigned` and `long`). This is not valid syntax for integer literals in
Swift, so until we fully translate the count expr syntax to Swift we
need to avoid importing these count expressions.

Also fixes some -Werror related stuff in test cases.

rdar://154141719
(cherry picked from commit 374658a)
2025-06-30 11:58:55 -07:00
Slava Pestov
acb53d2050 Merge pull request #82132 from slavapestov/bind-extensions-macro-6.2
[6.2] Sema: Don't expand macros when binding extensions
2025-06-14 12:14:10 -04:00
Slava Pestov
15f968f269 AST: Call setExtendedNominal() instead of cacheOutput(ExtendedNominalRequest...) 2025-06-13 16:00:16 -04:00
John Hui
a2bd6cafd9 Merge pull request #82171 from j-hui/j-hui/6.2/jump-to-def-for-macro-expanded-clang-imports
🍒 [6.2] [SourceKit] Support location info for macro-expanded Clang imports
2025-06-13 04:10:37 -07:00
John Hui
c94955b571 [SourceKit] Support location info for macro-expanded Clang imports
Currently, when we jump-to-definition for decls that are macro-expanded
from Clang imported decls (e.g., safe overloads generated by
@_SwiftifyImport), setLocationInfo() emits a bongus location pointing to
a generated buffer, leading the IDE to try to jump to a file that does
not exist.

The root cause here is that setLocationInfo() calls getOriginalRange()
(earlier, getOriginalLocation()), which was not written to account for
such cases where a macro is generated from another generated buffer
whose kind is 'AttributeFromClang'.

This patch fixes setLocationInfo() with some refactoring:

-   getOriginalRange() is inlined into setLocationInfo(), so that the
    generated buffer-handling logic is localized to that function. This
    includes how it handles buffers generated for ReplacedFunctionBody.

-   getOriginalLocation() is used in a couple of other places that only
    care about macros expanded from the same buffer (so other generated
    buffers not not relevant). This "macro-chasing" logic is simplified
    and moved from ModuleDecl::getOriginalRange() to a free-standing
    function, getMacroUnexpandedRange() (there is no reason for it to be
    a method of ModuleDecl).

-   GeneratedSourceInfo now carries an extra ClangNode field, which is
    populated by getClangSwiftAttrSourceFile() when constructing
    a generated buffer for an 'AttributeFromClang'. This could probably
    be union'ed with one or more of the other fields in the future.

rdar://151020332
(cherry picked from commit 44aba1382d)
2025-06-12 18:24:04 -07:00
Gábor Horváth
4590d5551b [6.2][cxx-interop] Only swiftify template instantiations behind type aliases
Explanation: C++ template instantiations that are not behind type
aliases don't have corresponding Swift names that are both syntactically
and semantically valid types. This PR prevents generating swiftified
overloads for those types.
Issue: rdar://151422108
Risk: Low, we swiftify functions less often.
Testing: Regression test added.
Original PR: #81973
Reviewer: @hnrklssn
2025-06-12 19:05:36 +01:00
Gábor Horváth
5d243730b4 Merge pull request #82061 from swiftlang/gaborh/swiftify-initializers-on-6.2
[6.2][cxx-interop] Support Swiftifying C++ constructors
2025-06-12 19:01:26 +01:00
Devin Coughlin
dd2f521d86 Merge pull request #82104 from swiftlang/gaborh/swiftify-private-on-6.2
[6.2][cxx-interop] Avoid swiftifying private and protected methods
2025-06-12 10:08:29 -07:00
Henrik G. Olsson
993929c3e1 Merge pull request #81752 from hnrklssn/swiftify-sized-sizedby
[Swiftify] Support __sized_by on byte-sized pointee types

(cherry picked from commit 89b09a69e4)
2025-06-10 21:49:52 +02:00
Gábor Horváth
7548cbf71a [6.2][cxx-interop] Avoid swiftifying private and protected methods
Explanation: We do not serialize the private macro generated swift
method's bodies which crashes the compiler. This PR skips generating
swiftified overloads to these private/protected method to work around
the crash.
Issue: rdar://152181531
Risk: Low, the change is straightforward.
Testing: Regression test added.
Original PR: #82016
Reviewer: @hnrklssn
2025-06-09 13:15:55 +01:00
Gábor Horváth
2b33c44796 [6.2][cxx-interop] Support Swiftifying C++ constructors
Explanation: We did not have support to generate swiftified overload for
initializers. This PR adds that support.
Issue: rdar://152112660
Risk: Low, the feature is localized to swiftified overloads.
Testing: Regression test added.
Original PR: #81947
Reviewer: @hnrklssn
2025-06-06 15:34:15 +01:00
Henrik G. Olsson
8584d343cb [Swiftify] Update availability for CxxSpan<->Span, fix lifetimebound on parameters with reference type (#81634)
Update availability for CxxSpan<->Span, fix lifetimebound on parameters
with reference type

Because swift-ide-test doesn't care about typechecking,
std-span-interface.swift passed despite containing 2 separate errors.
This updates the test file to properly exercise the entire compilation
pipeline for the macro expansions, by running swift-frontend
-emit-module and calling each macro expansion.

The first issue was that CxxSpan initializers taking [Mutable]Span still
had their availability set to Swift 6.2+, even after back-deploying
caused [Mutable]Span to have availability back to Swift 5.0. Since
_SwiftifyImport expansions copy the availbility of Span, this resulted
in the macro expansions calling unavailable initializers. Interestingly
enough, this manifested itself in the form of a tripped assert in SIL
verification, because although we do now typecheck the expansions from
_SwiftifyImport, the compilation can still keep going after
`shouldEmitFunctionBody` returns false: the macro expansion declaration
is still there, but is now missing its definition, despite not being
external.

The second issue was when parameters with C++ reference types were
annotated with `[[clang::lifetimebound]]`. For parameters with a type
that is `Escapable`, this is normally done using `@lifetime(borrow
foo)`. However C++ reference parameters are imported as `inout`, which
requires the `@lifetime(&foo)` syntax.

rdar://151493400
rdar://151678415
(cherry picked from commit 262a53f599)
2025-05-30 18:19:57 -07:00
Henrik G. Olsson
341ee5124a [Swiftify] Copy doc comment from clang node (#81584)
Swift nodes imported from clang don't have doc comments carried over,
but IDEs are clever enough to fetch the comments from the associated
clang node. The swift node in the macro expansion from _SwiftifyImport
doesn't have a clang node directly associated with it however.

This patch adds the same comment from the clang node to the
_SwiftifyImport macro invocation node. Since the macro has access to
this node, it can easily copy over its leading trivia.

For now the comment is not altered at all, meaning @param still remains
even if the parmeter is removed.

rdar://151346977
(cherry picked from commit 6534b9b14f)
2025-05-29 00:20:07 -07:00
John Hui
3db1314ba8 Merge pull request #81699 from j-hui/cherry-pick-6.2/fix-unavailable-enum
[6.2 🍒][cxx-interop] Fix assertion failure from unavailable typedef + enum pattern
2025-05-22 09:47:32 -07:00
John Hui
d1c2c76a19 [NFC] [cxx-interop] Flatten findOptionSetEnum() and move it to ImportEnumInfo.cpp
It's at home there alongside other ObjC enum-specific logic, rather than
in the middle of ImportDecl.cpp (since it isn't directly or exclusively
related to importing decls).

(cherry picked from commit 5aa5bcfea2)
2025-05-21 18:54:42 -07:00
John Hui
1f4ce612ba [NFC] [cxx-interop] Consolidate uses of findOptionSetType() helper function
Also renames it to findOptionSetEnum() to make it a bit clearer at face
value that the returned ImportedType will contain a Swift enum.

Also refactors some nearby instances of

  if (auto e = dyn_cast<ElaboratedType>(t))
      t = e->desugar();

into a helper function, desugarIfElaborated().

(cherry picked from commit c7070e73fe)
2025-05-21 18:54:42 -07:00
Henrik G. Olsson
c335b80ebd [Swiftify] Don't create safe wrapper for autoreleasing pointers (#81568) (#81590)
_SwiftifyImport doesn't know how to handle
AutoreleasingUnsafeMutablePointer, so we should not attach any
.countedBy information for pointers that are imported as this type.

This also adds defensive checks against adding .countedBy to any pointer
type that _SwiftifyImport doesn't know how to transform.

rdar://151479521
2025-05-20 08:03:10 -07:00
Devin Coughlin
2e941ef2db Merge pull request #81388 from hnrklssn/swiftify-anonymous-params-qual
[Swiftify] Emit @availability when expansions contain Span (#81320)
2025-05-12 17:29:18 -07:00
John Hui
97c5fbfe99 Merge pull request #81397 from j-hui/cherry-pick-6.2/dont-swiftify-invalid-expr
🍒  [6.2] [Swiftify] Do not swiftify non-Swift-like counted_by exprs
2025-05-09 11:55:23 -07:00
fahadnayyar
5ac1e63ad6 [6.2] [cxx-interop] Disabling should be annotated with SWIFT_RETURNS_(UN)RETAINED warning (#81390)
**Explanation**:
In Swift 6.1, we introduced warnings for C++ APIs returning
`SWIFT_SHARED_REFERENCE` types that lack the
`SWIFT_RETURNS_(UN)RETAINED` annotations. These warnings serve as a
reminder to annotate APIs, as the absence of these annotations can lead
to arbitrary assumptions about the ownership of returned
`SWIFT_SHARED_REFERENCE` values. This could result in both
use-after-free (memory safety) bugs and memory leaks.
We have received feedback from a few adopters indicating potential false
positive cases where these warnings are triggered. Consequently, we have
decided to disable these warnings in Swift 6.2 and re-qualify the
warnings on larger projects to ensure their effectiveness and eliminate
false positives.

- **Scope**: Disabling a previously shipped warning. There is no
likelihood of any source breakage or semantic alterations.
- **Issues**: rdar://150937617 , rdar://150800115
- **Original PRs**: N/A
- **Risk**: Low
- **Testing**: Lit test and adopted manually on a demo Xcode project
- **Reviewers**: N/A Our intention is to re-enable the warnings in later
beta releases of Swift 6.2 once we have stronger evidence of their
effectiveness on large codebases and proof that there are no false
positives.
2025-05-09 08:08:01 -07:00
John Hui
8be78da6de [Swiftify] Do not swiftify non-Swift-like counted_by exprs
__counted_by (and __sized_by) expressions can have arbitrary C syntax
in them, such as:

    void foo(int * __counted_by(*len) p, int *len);

When @_SwififyImport tries to generate Swift code for this, the
expression `*len` leads to a syntax error, since it isn't valid Swift.

This patch adds a check to ensure we only attach the Swiftify macro to
__counted_by expressions that are also syntactically valid in Swift.

rdar://150956352
(cherry picked from commit e5b1f4a251)
2025-05-08 21:14:08 -07:00
Henrik G. Olsson
f70676a340 [Swiftify] Emit @availability when expansions contain Span (#81320)
This prevents errors when compiling for older targets using a newer
compiler.

rdar://150740330
(cherry picked from commit 59d7d3160f)
2025-05-08 16:40:20 -07:00
Henrik G. Olsson
5498c5db05 [Swiftify] Skip swiftify during symbolic import (#81349)
Swiftify cannot work in this mode. This mode has been removed entirely
in main. This takes a smaller change into the release to minimise risk.

rdar://149953125
2025-05-07 16:18:33 -07:00
Doug Gregor
751678d7fb Merge pull request #81235 from j-hui/cherry-pick-6.2/fix-ast-layout-dependent-types
🍒 [6.2] [cxx-interop] Avoid querying layout of dependent types during symbolic import
2025-05-06 14:04:51 -07:00
John Hui
f6f5adb5f4 [cxx-interop] Avoid querying layout of dependent types during symbolic import
In #80786, we started importing certain padded fields as opaque blobs.
Part of this logic involved querying those fields' ASTRecordLayout.
However, dependent types (which are imported symbolically) do not have
an ASTRecordLayout, so calling Clang's getASTRecordLayout() would lead
to an assertion error for class templates where a no_unique_address
field is some kind of dependent C++ record type.

This patch avoids the field padding check during symbolic import mode
because that check is only relevant for codegen anyway.

rdar://150067288
(cherry picked from commit 1fdb239cea)
2025-05-01 10:10:56 -07:00
Yeoul Na
203ee392f1 [Swiftify] SafeInteropWrapper crashes with 'cgImage.width' (#81075)
* [Swiftify] Fix crash calling cgImage.width

cgImage.width calls the C function, CGImageGetWidth(CGImageRef).
Swift representation and Clang representation of this function
seem to have a parameter number mismatch, causing swiftify function
to crash.

rdar://149691207
(cherry picked from commit af8579fac0)

* [NFC] Fix test/Interop/ObjC/swiftify-import/getter.swift
2025-04-30 12:25:33 -07:00
Gabor Horvath
291a63fd80 [6.2][cxx-interop] Fix a crash with [[no_unique_address]]
Explanation: Swift does not support storing fields in the padding of the previous
fields just yet, so let's not import fields like that from C++.
Represent them as opaque blobs instead.
Issue: rdar://149072458
Risk: Low, the fix is targeted at a scenario that was crashing before.
Testing: Regression test added.
Original PR: #80786
Reviewer:
2025-04-25 12:51:13 +01:00
Gábor Horváth
1c92940446 Merge pull request #81047 from swiftlang/gaborh/span-ctor-crash-6.2
[6.2][cxx-interop] Work around crash in codegen when initializing C++ span
2025-04-23 23:47:46 -07:00
Gábor Horváth
0b1df04fc1 [6.2][cxx-interop] Work around crash in codegen when initializing C++ span
Explanation: C++ templates are imported as Swift generics.
Unfortunately, the codegen for some of the instantiations will crash
codegen due to a confusion in how Swift pointer types are mapped back to their
native counterparts. As a result, when a user is passing an
UnsafePointer<Element>? to a C++ span constructor we got a crash. The
user should never need the generic version of the initializer as we
already have an initializer taking an UnsafePointer<Element> in the C++
overlay. This PR avoids importing the templated span constructors to
work around this issue.
Issue: rdar://148961349
Risk: Low, the fix is very targeted.
Testing: Regression test added.
Original PR: #81030
Reviewer: @j-hui
2025-04-23 21:46:56 +01:00