Commit Graph

6140 Commits

Author SHA1 Message Date
Arnold Schwaighofer
7ac551636b Merge pull request #81714 from aschwaighofer/se0460
SE-0460: Introduce @specialized attribute
2025-05-28 12:03:48 -07:00
Steven Wu
2999ab722d Merge pull request #81454 from cachemeifyoucan/clang-scanner-invocation-callback
[DependencyScanning] Avoid extra cc1 arg round-trip to speed up bridging
2025-05-27 10:58:35 -07:00
Arnold Schwaighofer
13ff5abdb8 Introduce @specialized attribute
Implements SE-0460 -- the non-underscored version of @specialized.

It allows to specify "internal" (not abi affecting) specializations.

rdar://150033316
2025-05-23 13:12:47 -07:00
Henrik G. Olsson
262a53f599 [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
2025-05-22 15:36:19 -07:00
John Hui
828876f4ec Merge pull request #81625 from j-hui/fix-unavailable-enum 2025-05-22 00:01:30 -07:00
John Hui
89f8855ad6 [cxx-interop] Check for NS_OPTIONS macro in findOptionSetEnum()
importer::findOptionSetEnum() uses some fragile heuristics to determine
whether a typedef is involved in the construction of a CF_OPTIONS or
NS_OPTIONS type. This patch adds an explicit check that the typedef is
expanded from either of those macros, to prevent, e.g., an unavailable
NS_ENUM, from being mistakenly recognized as an NS_OPTIONS.

Note that doing this is still kind of fragile, and prevents users from
building {NS,CF}_OPTIONS with their own macros. The right thing to do is
probably specifically look for the flag_enum attribute, but that is not
currently what we're doing for reasons whose discovery is left as
an exercise to the future git archaeologist.

This patch also removes (part of) a test case that builds
a CF_OPTIONS-like type with the "SOME_OPTIONS" macro, which is no longer
supported as of this patch.

rdar://150399978
2025-05-21 15:01:09 -07:00
John Hui
fa5c4f298f [cxx-interop] Remove NDEBUG check when importing OptionSetTypes 2025-05-21 10:18:05 -07:00
John Hui
80db05455f [cxx-interop] Fix assertion failure from unavailable NS_ENUM typedef
The NS_OPTIONS macro sometimes uses a pattern where it loosely
associates a typedef with an anonymous enum via a shared underlying
integer type (emphasis on "loosely"). The typedef is marked as
unavailable in Swift so as to not cause name ambiguity when we associate
the anonymous enum with said typedef. We use unavailability as
a heuristic during the import process, but that conflates NS_OPTIONS
with NS_ENUMs that can be marked as unavailable for entirely unrelated
reasons.

That in and of itself is fine, because the import logic is general
enough to handle both cases, but we have an assertion that seems to be
unaware of this scenario, and trips on unavailable NS_ENUMs. (In those
cases, the typedef points to the enum rather than the underlying integer
type.) This patch fixes the assertion to be resilient against such cases
by looking through the enum a typedef refers to.

rdar://150399978
2025-05-21 10:16:11 -07:00
Steven Wu
391446d4b3 [DependencyScanning] Avoid extra cc1 arg round-trip to speed up bridging
Use the underlying compiler invocation inside module scanning result to
speed up the clang module dependency bridging. This avoids converting
cc1 arguments to compiler invocation and back, just to modify the cc1
arguments needed for building PCM using swift-frontend.

rdar://151705822
2025-05-20 09:54:54 -07:00
Henrik G. Olsson
6534b9b14f [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
2025-05-20 08:06:20 -07:00
John Hui
2c7d01fa91 [NFC] Use explicit ImportedType() constructor 2025-05-19 22:17:08 -07:00
John Hui
5aa5bcfea2 [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).
2025-05-19 14:21:49 -07:00
John Hui
c7070e73fe [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().
2025-05-19 14:10:49 -07:00
Hamish Knight
edca7c85ad Adopt ABORT throughout the compiler
Convert a bunch of places where we're dumping to stderr and calling
`abort` over to using `ABORT` such that the message gets printed to
the pretty stack trace. This ensures it gets picked up by
CrashReporter.
2025-05-19 20:55:01 +01:00
Henrik G. Olsson
e1eb960e7f [Swiftify] Don't create safe wrapper for autoreleasing pointers (#81568)
_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-17 20:33:00 -07:00
Steven Wu
531227d4b9 [Caching] Clear benign CodeGen options when building modules
Use `resetBenignCodeGenOptions()` from clang dependency scanner to clear
the swift explicit module build cc1 arguments. This fixes the problem
that CurrentWorkingDirectory is leaking through
`-fcoverage-compilation-dir` that can cause extra module variants when
caching is enabled. This also avoid the duplicating the logics for
clearing CodeGen options inside Swift.

rdar://151395300
2025-05-15 11:45:21 -07:00
Steven Wu
f2ef2d3d86 Merge pull request #81494 from cachemeifyoucan/eng/PR-remove-clang-module-cas-fs
[Caching] Remove CASFS based clang module implementation
2025-05-14 15:55:17 -07:00
Kuba (Brecka) Mracek
749e9ee090 Merge pull request #81492 from kubamracek/import-values-apinotes
[ClangImporter] Fix enum conversion type when importing global values (unwrap if needed)
2025-05-14 10:03:11 -07:00
Steven Wu
1506a0d495 [Caching] Remove capture clang extra files
After removing the CASFS implementation for clang modules, there is no
need to capture clang extra file that sets up the VFS for the clang
modules since all content imported by ClangImporter is dependency
scanned and available via include-tree. This saves more ClangImporter
instance when caching is enabled.

Update the test to check that clang content found via `-Xcc` VFS options
can currently work without capture the headermaps and vfs overlays.
2025-05-14 09:35:03 -07:00
Steven Wu
3c81c1ca9f [Caching] Remove CASFS clang module implemenation
Remove the CASFS based clang module implemenation as it is not longer
used.
2025-05-14 09:35:03 -07:00
Kuba Mracek
1ecdb17fcc [ClangImporter] Fix enum conversion type when importing global values (unwrap if needed) 2025-05-13 16:02:15 -07:00
Steven Wu
201e4faea7 [Caching] Reduce the number of cas ID passed on frontend commandline
Using IncludeTree::FileList to concat the include tree file systems that
are passed on the command-line. This significantly reduce the
command-line size, and also makes the cache key computation a lot
faster.

rdar://148752988
2025-05-13 09:20:13 -07:00
Artem Chikin
8ab726c2be Merge pull request #81361 from artemcm/DepScanFewerClangs
[Dependency Scanning][Refactor] Reduce the number of `ClangImporter` instances used by the scanner
2025-05-12 09:57:38 -07:00
fahadnayyar
49aea31e41 [cxx-interop] Disabling should be annotated with SWIFT_RETURNS_(UN)RETAINED warning (#81411)
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. 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.

rdar://150937617
rdar://150800115
2025-05-09 17:36:00 -07:00
John Hui
203acbbb47 [NFC] Tidy up formatting for CountedByExpressionValidator
(Renamed from CATExprValidator)
2025-05-09 00:25:20 -07:00
John Hui
e5b1f4a251 [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
2025-05-08 21:13:20 -07:00
Henrik G. Olsson
59d7d3160f [Swiftify] Emit @availability when expansions contain Span (#81320)
This prevents errors when compiling for older targets using a newer
compiler.

rdar://150740330
2025-05-08 16:13:24 -07:00
Qiongsi Wu
024dbd040f Merge pull request #81243 from qiongsiwu/eng_144794793
[Dependency Scanning] Update Uses of `ModuleDeps::ClangModuleDeps`

https://github.com/llvm/llvm-project/pull/137421 changes the type of `ModuleDeps::ClangModuleDeps`. This PR updates Swift's use of this data structure to use the correct fields. 

rdar://144794793
2025-05-08 11:11:17 -07:00
Robert Widmann
7c5a59f4a3 Merge pull request #81359 from CodaFi/sending-type-beat
[ClangImporter] Import 'swift_attr("sending")' As a Type Attribute
2025-05-08 13:08:11 +01:00
Artem Chikin
8cd193fc08 [Dependency Scanning] Remove 'ClangImporter' instance from dependency scanning worker
Move relevant logic directly into the worker
2025-05-07 16:43:45 -07:00
fahadnayyar
b311c63ea9 [cxx-interop] Remove SWIFT_RETURNED_AS_RETAINED_BY_DEFAULT annotation (#81329)
This patch removes the `SWIFT_RETURNED_AS_RETAINED_BY_DEFAULT`
annotation while maintaining the support for
`SWIFT_RETURNED_AS_UNRETAINED_BY_DEFAULT`. These type-level annotations
were initially introduced in
[PR-81093](https://github.com/swiftlang/swift/pull/81093) to reduce the
annotation burden in large C++ codebases where many C++ APIs returning
`SWIFT_SHARED_REFERENCE` types are exposed to Swift.

### Motivation
The original goal was to make C++ interop more ergonomic by allowing
type-level defaults for ownership conventions
for`SWIFT_SHARED_REFERENCE` types . However, defaulting to retained
return values (+1) seems to be problematic and poses memory safety
risks.

### Why we’re removing `SWIFT_RETURNED_AS_RETAINED_BY_DEFAULT`

- **Memory safety risks:** Defaulting to retained can potentially lead
to use-after-free bugs when the API implementation actually returns
`unowned` (`+0`). These errors are subtle and can be hard to debug or
discover, particularly in the absence of explicit API-level
`SWIFT_RETURNS_(UN)RETAINED` annotations.
- **Risky transitive behavior:** If a `SWIFT_SHARED_REFERENCE` type is
annotated with `SWIFT_RETURNED_AS_RETAINED_BY_DEFAULT`, any new C++ API
returning this type will inherit the retained behavior by default—even
if the API's actual return behavior is unretained. Unless explicitly
overridden with `SWIFT_RETURNS_UNRETAINED`, this can introduce a silent
mismatch in ownership expectations and lead to use-after-free bugs. This
is especially risky in large or evolving codebases where such defaults
may be overlooked.
- **Simpler multiple inheritance semantics:** With only one type-level
default (`SWIFT_RETURNED_AS_UNRETAINED_BY_DEFAULT`), we avoid
complications that can arise when multiple base classes specify
conflicting ownership defaults. This simplifies reasoning about behavior
in class hierarchies and avoids ambiguity when Swift determines the
ownership convention for inherited APIs.

### Why we’re keeping `SWIFT_RETURNED_AS_UNRETAINED_BY_DEFAULT`
- It still enables projects to suppress warnings for unannotated C++
APIs returning `SWIFT_SHARED_REFERENCE` types, helping to reduce noise
while maintaining clarity.
- It encourages explicitness for retained behavior. Developers must
annotate retained return values with `SWIFT_RETURNS_RETAINED`, making
ownership intent clearer and safer.
- The worst-case outcome of assuming unretained when the return is
actually retained is a memory leak, which is more tolerable and easier
to debug than a use-after-free.
- Having a single default mechanism improves clarity for documentation,
diagnostics, and long-term maintenance of Swift/C++ interop code.
2025-05-07 13:25:25 -07:00
Robert Widmann
edcde7c55c [ClangImporter] Import 'swift_attr("sending")' As a Type Attribute
Previously, `__attribute__((swift_attr("sending")))` would only be
resolved when attached to declarations. This patch expands it to be
a type attribute as well, which enables it to occur in the result and
parameter positions for blocks, function pointers, and lambdas.

Resolves rdar://148435359
2025-05-07 18:19:38 +01:00
Artem Chikin
69f8a6fefa Merge pull request #81313 from artemcm/DepScanVariantError
[Dependency Scanning] Emit a detailed error diagnostic on Clang module variant discovery
2025-05-06 13:26:47 -07:00
Artem Chikin
4b26a3d10a [Dependency Scanning] Emit a detailed error diagnostic on Clang module variant discovery
In expectation, this should never happen. Such a situation means that within the same scanning action, Clang Dependency Scanner has produced two different variants of the same module. This is not supposed to happen, but we are currently hunting down the rare cases where it does, seemingly due to differences in Clang Scanner direct by-name queries and transitive header lookup queries.
2025-05-06 08:55:57 -07:00
Pavel Yaskevich
63ee0a47ed Merge pull request #81282 from ludwwwig/update-header-comments
[gardening] Update file header comments for headers in lib
2025-05-05 14:46:52 -07:00
Egor Zhdan
294e4cf21b Merge pull request #81257 from swiftlang/egorzhdan/remove-symbolic-mode
[cxx-interop] Remove symbolic import mode
2025-05-05 18:36:32 +01:00
Artem Chikin
0164aed30b Merge pull request #81113 from artemcm/ParameterizeWeakQueryForSwift
Modify clang declaration weakly-imported query to use Swift's code-gen target triple
2025-05-05 09:21:37 -07:00
Ludwig Hollmann
39aa950660 Update file header comments for headers in lib. 2025-05-04 22:26:26 +02:00
fahadnayyar
e7bbd4b762 [cxx-interop] Introduce type-level annotations to specify default ownership convention for C++ foreign reference return values (#81093)
In Swift 6.1, we introduced `SWIFT_RETURNS_RETAINED` and
`SWIFT_RETURNS_UNRETAINED` annotations for C++ APIs to explicitly
specify the ownership convention of `SWIFT_SHARED_REFERENCE` type return
values.

Currently the Swift compiler emits warnings for unannotated C++ APIs
returning `SWIFT_SHARED_REFERENCE` types. We've received some feedback
that people are finding these warnings useful to get a reminder to
annotate their APIs. While this improves correctness , it also imposes a
high annotation burden on adopters — especially in large C++ codebases.

This patch addresses that burden by introducing two new type-level
annotations:
- `SWIFT_RETURNED_AS_RETAINED_BY_DEFAULT`
- `SWIFT_RETURNED_AS_UNRETAINED_BY_DEFAULT`

These annotations allow developers to specify a default ownership
convention for all C++ APIs returning a given
`SWIFT_SHARED_REFERENCE`-annotated type, unless explicitly overridden at
the API by using `SWIFT_RETURNS_RETAINED` or `SWIFT_RETURNS_UNRETAINED`.
If a C++ class inherits from a base class annotated with
`SWIFT_RETURNED_AS_RETAINED_BY_DEFAULT` or
`SWIFT_RETURNED_AS_UNRETAINED_BY_DEFAULT`, the derived class
automatically inherits the default ownership convention unless it is
explicitly overridden. This strikes a balance between safety/correctness
and usability:

- It avoids the need to annotate every API individually.
- It retains the ability to opt out of the default at the API level when
needed.
- To verify correctness, the user can just remove the
`SWIFT_RETURNED_AS_(UN)RETAINED_BY_DEFAULT` annotation from that type
and they will start seeing the warnings on all the unannotated C++ APIs
returning that `SWIFT_SHARED_REFERENCE` type. They can add
`SWIFT_RETURNS_(UN)RETAINED` annotation at each API in which they want a
different behaviour than the default. Then they can reintroduce the
`SWIFT_RETURNED_AS_(UN)RETAINED_BY_DEFAULT` at the type level to
suppress the warnings on remaining unannotated APIs.

A global default ownership convention (like always return
`unretained`/`unowned`) was considered but it would weaken the
diagnostic signal and remove valuable guardrails that help detect
use-after-free bugs and memory leaks in absence of
`SWIFT_RETURNS_(UN)RETAINED` annotations. In the absence of these
annotations when Swift emits the unannotated API warning, the current
fallback behavior (e.g. relying on heuristics based on API name such as
`"create"`, `"copy"`, `"get"`) is derived from Objective-C interop but
is ill-suited for C++, which has no consistent naming patterns for
ownership semantics.

Several codebases are expected to have project-specific conventions,
such as defaulting to unretained except for factory methods and
constructors. A type-level default seems like the most precise and
scalable mechanism to support such patterns. It integrates cleanly with
existing `SWIFT_SHARED_REFERENCE` usage and provides a per-type opt-in
mechanism without global silencing of ownership diagnostics.

This addition improves ergonomics while preserving the safety benefits
of explicit annotations and diagnostics.

rdar://145453509
2025-05-02 16:26:07 -07:00
Egor Zhdan
b51cfa5c76 [cxx-interop] Remove symbolic import mode
Importing C++ class templates in symbolic mode has proven to be problematic in interaction with other compiler features, and it isn't used widely. This change removes the feature.

rdar://150528798
2025-05-02 18:43:09 +01:00
Qiongsi Wu
5ddff7c24c Fix the API breaking change introduced by https://github.com/llvm/llvm-project/pull/137421. 2025-05-01 16:03:45 -07:00
Artem Chikin
fe632e530f Modify clang declaration weakly-imported query to use Swift's code-gen target triple
Similarly to how https://github.com/swiftlang/swift/pull/70564 configures 'ClangImporter's 'CodeGenerator' using Swift's compilation target triple, we must use the versioned version of the 'isWeakImported' query to determine linkage for imported Clang symbols.
2025-05-01 10:39:19 -07:00
John Hui
34be8f988e Merge pull request #81228 from j-hui/fix-ast-layout-dependent-types 2025-05-01 08:40:32 -07:00
John Hui
c2f904caa4 Merge pull request #81188 from j-hui/fix-recursive-inheritance
[cxx-interop] Avoid unchecked recursion when importing C++ classes with circular inheritance
2025-05-01 02:00:46 -07:00
John Hui
1fdb239cea [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
2025-04-30 18:36:29 -07:00
John Hui
1f2107f357 [cxx-interop] Avoid unchecked recursion when importing C++ classes with circular inheritance
It is possible for a C++ class template to inherit from a specialization
of itself. Normally, these are imported to Swift as separate (unrelated)
types, but when symbolic import is enabled, unspecialized templates are
imported in place of their specializations, leading to circularly
inheriting classes to seemingly inherit from themselves.

This patch adds a check to guard against the most common case of
circular inheritance, when a class template directly inherits from
itself. This pattern appears in a recent version of libc++,
necessitating this patch. However, the solution here is imperfect as it
does not handle more complex/contrived circular inheritance patterns.

This patch also adds a test case exercising this pattern. The
-index-store-path flag causes swift-frontend to index the C++ module
with symbolic import enabled, without the fix in this patch, that test
triggers an assertion failure due to the circular reference (and can
infinitely recurse in the StorageVisitor when assertions are disabled).

rdar://148026461
2025-04-30 13:33:33 -07:00
Yeoul Na
2d7b7a73f8 [Swiftify] SafeInteropWrapper crashes with 'cgImage.width' (#80948)
* [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

* [NFC] Fix test/Interop/ObjC/swiftify-import/getter.swift
2025-04-30 08:53:22 -07:00
Gabor Horvath
939ee49dcb [cxx-interop] Fix a crash with [[no_unique_address]]
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.

Fixes #80764

rdar://149072458
2025-04-25 12:46:31 +01:00
Gábor Horváth
c2f560e329 Merge pull request #81030 from swiftlang/gaborh/span-ctor-crash 2025-04-23 12:46:21 -07:00
Gabor Horvath
5238c3fc9b [cxx-interop] Work around crash in codegen when initializing C++ span
When initializing span with an UnsafePointer<Element>? we call into the
generic initializer that we imported from the C++ templated constructor
instead of the concrete initializer we have in the overlay that takes an
UnsafePointer<Element> (non-optional). We cannot properly codegen for
this generic initializer at the moment, so let's stop importing them
since the user probably wanted to call the initializer from the overlay.

We should come back later and fix the root cause.

rdar://148961349
2025-04-23 16:12:58 +01:00