Commit Graph

2428 Commits

Author SHA1 Message Date
Gábor Horváth
91d7cc445a Merge pull request #78761 from swiftlang/gaborh/span-lifetimebound-end-to-end
[cxx-interop] Make ClangImporter support lifetimebound annotated spans
2025-01-22 19:04:34 +00:00
Gábor Horváth
795d62987f Merge pull request #78771 from swiftlang/gaborh/unsafe-lifetime-unannotated
[cxx-interop] Require lifetime annotations in safe mode
2025-01-22 18:45:26 +00:00
Gabor Horvath
042b108e6f [cxx-interop] Make ClangImporter support lifetimebound annotated spans
Generate safe Swift Span wrappers using the new SwiftifyImport macro.

rdar://139074571
2025-01-22 15:07:02 +00:00
Becca Royal-Gordon
ebea19d7b9 Merge pull request #78697 from beccadax/rdar142693093
Work around Foundation NS_TYPED_ENUM bug
2025-01-22 00:57:41 -08:00
Gabor Horvath
0a38617e39 [cxx-interop] Require lifetime annotations in safe mode
In strict safe mode we should consider all C++ APIs with non-escapable
parameters unsafe unless they have their lifetimes annotated. This can
be done using [[clang::lifetimebound]], [[clang::lifetime_capture_by]],
or [[clang::noescape]].
2025-01-21 12:54:21 +00:00
Gábor Horváth
3bbb126e4c Merge pull request #78522 from swiftlang/gaborh/instantiation-unsafe
[cxx-interop] Check the safety of C++ template arguments
2025-01-20 16:59:56 +00:00
Becca Royal-Gordon
56b20351e3 Work around Foundation NS_TYPED_ENUM bug
Consider code like:

```
// Foo.h
typealias NSString * FooKey NS_EXTENSIBLE_TYPED_ENUM;

// Foo.swift
extension FooKey { … }
```

When Swift binds the extension to `FooKey`, that forces ClangImporter to import `FooKey`. ClangImporter’s newtype logic, among other things, checks whether the underlying type (`Swift.String` here) is Objective-C bridgeable and, if so, makes `FooKey` bridgeable too.

But what happens if this code is actually *in* Foundation, which is where the `extension String: _ObjectiveCBridgeable` lives? Well, if the compiler has already bound that extension, it works fine…but if it hasn’t, `FooKey` ends up unbridgeable, which can cause both type checking failures and IRGen crashes when code tries to use its bridging capabilities. And these symptoms are sensitive to precise details of the order Swift happens to bind extensions in, so e.g. adding empty files to the project can make the bug appear or disappear. Spooky.

Add a narrow hack to ClangImporter (only active for types in Foundation) to *assume* that `String` is bridgeable even if the extension declaring this hasn’t been bound yet.

Fixes rdar://142693093.
2025-01-17 17:22:55 -08:00
Gabor Horvath
f12b48aa86 [cxx-interop] Check the safety of C++ template arguments
Swift imports template specializations as a standalone type (not as an
instantiation of a generic) so unsafety is not propagated from the
template arguments to the specialization. This PR propagates this
information explicitly.
2025-01-17 17:39:25 +00:00
Egor Zhdan
cb2bd321ce [cxx-interop] Do not import std::__compressed_pair
This type is triggering modularization issues in libc++:
```
error: definition of '__builtin_new_deleter' must be imported from module 'std_private_memory_builtin_new_allocator' before it is required
```

This is a workaround to keep things building.

rdar://142576799
2025-01-16 23:41:29 +00:00
Cassie Jones
c7021ae979 [cxx-interop] Workaround name lookup issues with namespace simd
On Apple platforms, a system module `simd` declares a `namespace simd`
under `#if defined(__cplusplus)`. This namespace defines C++ overlays of
the simd types, but these types are already refined for Swift
separately, so it's not necessary to import this namespace.

This is the same issue previously encountered for the `os` module, work
around it in the same way.

rdar://143007477
2025-01-15 21:29:17 -08:00
Egor Zhdan
430809d35d [cxx-interop] Workaround name lookup issues with namespace os
On Apple platforms, a system module `os` declares a `namespace os` under `#if defined(__cplusplus)`. This causes ClangImporter to import it as `enum os` when C++ interop is enabled. This causes name lookup ambiguity (module os vs namespace os) which is resolved in namespace's favor, breaking existing usages.

rdar://119044493
2025-01-14 18:11:18 +00:00
Henrik G. Olsson
d7bd76e9f1 [Swiftify] Add return pointer support (#78571)
* Import __counted_by for function return values

Instead of simply passing a parameter index to _SwiftifyInfo, the
_SwiftifyExpr enum is introduced. It currently has two cases:
 - .param(index: Int), corresponding to the previous parameter index
 - .return, corresponding to the function's return value.

ClangImporter is also updated to pass this new information along to
_SwiftifyImport, allowing overloads with buffer pointer return types to
be generated. The swiftified return values currently return Span when
the return value is marked as nonescaping, despite this not being sound.
This is a bug that will be fixed in the next commit, as the issue is
greater than just for return values.

* Fix Span variant selection

There was an assumption that all converted pointers were either
converted to Span-family pointers, or UnsafeBufferPointer-family
pointers. This was not consistently handled, resulting in violating the
`assert(nonescaping)` assert when the two were mixed. This patch removes
the Variant struct, and instead each swiftified pointer separately
tracks whether it should map to Span or UnsafeBufferPointer.
This also fixes return pointers being incorrectly mapped to Span when
marked as nonescaping.
2025-01-13 08:08:36 -08:00
Ellie Shin
727fb8c32d Merge pull request #78258 from swiftlang/elsh/disallow-bypass-deser-check
Package CMO: add deserialization checks to ensure correct memory layout
2025-01-11 05:40:49 -08:00
Allan Shortlidge
7b4af34f40 ClangImporter: Adopt new AvailableAttr constructor. 2025-01-10 18:43:12 -08:00
Allan Shortlidge
86ea1ae775 AST: Introduce a Kind enum and new constructor for AvailableAttr.
AvailableAttr::Kind and AvailabilityDomain are designed to replace
PlatformAgnosticAvailabilityKind, allowing AvailableAttr to more flexibly model
availability for arbitrary domains. For now, the new constructor just
translates its inputs into inputs for the existing constructor. Once all of the
callers of the existing AvailableAttr constructor have been updated to use the
new constructor, the representation of AvailableAttr will be updated to store
the new properties.
2025-01-10 18:43:12 -08:00
Allan Shortlidge
635ea34bb5 Merge pull request #78503 from tshortli/available-attr-creation-conveniences
AST: Introduce new conveniences for synthesizing AvailabilityAttrs
2025-01-09 08:21:40 -08:00
Gábor Horváth
b31b90d862 Merge pull request #78422 from swiftlang/gaborh/cxx-span-overload-importer
[cxx-interop] Generate safe overloads for non-escapable spans
2025-01-09 12:10:30 +00:00
Allan Shortlidge
70a2363b97 AST: Introduce new conveniences for synthesizing AvailabilityAttrs.
This makes intent clearer at the call site and removes a lot of explicit uses
of PlatformAgnosticAvailabilityKind, which is going away.
2025-01-08 19:59:47 -08:00
Fahad Nayyar
69332f706f [cxx-interop] Diagnose ObjC APIs returning SWIFT_SHARED_REFERENCE types
rdar://142500663
2025-01-08 11:36:49 -08:00
Gabor Horvath
4846c56795 [cxx-interop] Generate safe overloads for non-escapable spans
A previous PR already added support to the SwiftifyImport macro to
generate safe wrappers. This PR makes ClangImporter emit the macro to do
the transformation.
2025-01-08 11:19:35 +00:00
elsh
c03abed00d Package optimization allows bypassing resilience, but that assumes the memory layout of the
decl being accessed is correct. When this assumption fails due to a deserialization error
of its members, the use site accesses the layout with a wrong field offset, resulting in
UB or a crash. The deserialization error is currently not caught at compile time due to
LangOpts.EnableDeserializationRecovery being enabled by default to allow for recovery of some
of the deserialization errors at a later time. In case of member deserialization, however,
it's not necessarily recovered later on.

This PR tracks whether member deserialization had an error by recursively loading members and
checking for deserialization error, and fails and emits a diagnostic. It provides a way to
prevent resilience bypassing when the deserialized decl's layout is incorrect.

Resolves rdar://132411524
2025-01-07 21:51:49 -08:00
Allan Shortlidge
d0f63a0753 AST: Split Availability.h into multiple headers.
Put AvailabilityRange into its own header with very few dependencies so that it
can be included freely in other headers that need to use it as a complete type.

NFC.
2025-01-03 18:36:04 -08:00
Doug Gregor
5b90b8851a Generalize protocol conformance options spelled via attribute and incorporate @unsafe
Protocol conformances have a handful attributes that can apply to them
directly, including @unchecked (for Sendable), @preconcurrency, and
@retroactive. Generalize this into an option set that we carry around,
so it's a bit easier to add them, as well as reworking the
serialization logic to deal with an arbitrary number of such options.

Use this generality to add support for @unsafe conformances, which are
needed when unsafe witnesses are used to conform to safe requirements.
Implement general support for @unsafe conformances, including
producing a single diagnostic per missing @unsafe that provides a
Fix-It and collects together all of the unsafe witnesses as notes.
2024-12-20 23:16:23 -08:00
Henrik G. Olsson
ef9d2b744d Rename pointer bounds (#78210)
* Make pointer bounds non-experimental

* Rename @PointerBounds to @_SwiftifyImport

* Rename filenames containing PointerBounds

* Add _PointerParam exception to stdlib ABI test

* Add _PointerParam to stdlib API changes

* Rename _PointerParam to _SwiftifyInfo
2024-12-20 11:36:01 +01:00
Allan Shortlidge
94e678da37 ClangImporter: Ignore missing imports in SwiftDeclConverter::recordObjCOverride().
`recordObjCOverride()` records semantic overrides for imported Obj-C methods.
Since these methods are imported from a different language, it doesn't make
sense to enforce Swift's member import visibility rules when performing lookups
to find overridden methods. Doing so caused the Constrain Solver to lack
important information needed to eliminate overloads, resulting in erroneous
ambiguities.

Resolves rdar://141636723.
2024-12-18 08:34:44 -08:00
Gábor Horváth
568fa14b14 Merge pull request #77617 from swiftlang/gaborh/support-lifetime-capture-by
[cxx-interop] Support lifetime_capture_by in ClangImporter
2024-12-18 13:53:16 +00:00
Gabor Horvath
8399971f06 [cxx-interop] Support lifetime_capture_by in ClangImporter
Import it as lifetime dependencies.

rdar://137671377
2024-12-18 10:05:43 +00:00
Gabor Horvath
985c3a44f8 [cxx-interop] Make sure C++ span is imported as @unsafe
The C++ span should be a non-escapable type but is imported as escapable
for backward compatibility reason. This is inherently unsafe, so make
sure std::span is imported as such. In the future, we plan to generate
safe overloads using Swift's Span and that will be the preferred way of
using the API.
2024-12-16 17:11:22 +00:00
Henrik G. Olsson
ec8ea94fb9 Infer @PointerBounds macro from clang __counted_by parameters (#77387)
This results in an automatic wrapper function with safe pointer types
when the imported function has bounds attributes. This exercises similar
pathways as the recently added functionality for specifying macros from
swift_attr. The new functionality is guarded by the experimental
language feature SafeInteropWrappers.

rdar://97942270
2024-12-11 13:36:56 -08:00
Doug Gregor
41073a881c Merge pull request #77837 from lhoward/lhoward/retain-return-self
[cxx-interop] allow shared ref retain function to return self
2024-12-05 11:25:31 -08:00
Egor Zhdan
70ce8c67f5 Merge pull request #77932 from swiftlang/egorzhdan/spurious-lifetime-diags
[cxx-interop] Do not emit spurious lifetime diagnostics for C++ types
2024-12-05 17:17:12 +00:00
Doug Gregor
0c91a3409c Formalize the notion of "can clone" so we don't try to clone an attribute that won't work 2024-12-04 15:25:13 -08:00
Doug Gregor
ac448b865b [Clang importer] Don't cache swift_attr source files that have CustomAttrs with arguments
Since we can't do a proper "deep" clone of expression nodes, cloning
such a CustomAttr is necessarily shallow. In such cases, don't cache
the swift_attr source files at all, so we get fresh attribute nodes
for each such usage.
2024-12-04 15:24:00 -08:00
Egor Zhdan
8202dfdecd [cxx-interop] Do not emit spurious lifetime diagnostics for C++ types
In rare scenarios, Swift was emitting diagnostics that looked like this:
```
warning: 'import_owned' swift attribute ignored on type 'basic_string': type is not copyable or destructible
```

This change makes sure the compiler does not emit these (incorrect) warnings. See the inline comment for more details.
2024-12-04 16:10:08 +00:00
fahadnayyar
4bab2a8419 Merge pull request #77397 from fahadnayyar/frt-return-unannotated-warning-improve
[cxx-interop] Improve the warnings for unannotated c++ APIs returning SWIFT_SHARED_REFERENCE types
2024-12-04 00:26:03 -08:00
fahadnayyar
2e501754dd [cxx-interop] Improve the warnings for unannotated c++ APIs returning SWIFT_SHARED_REFERENCE types 2024-12-03 18:26:13 -08:00
Luke Howard
da23bcf1c6 [cxx-interop] allow shared ref retain function to return self
Many existing C APIs for retaining references, including Apple's own, return
the reference. Support this pattern, along with the existing void return
signature, with when importing reference types from C++.
2024-12-03 11:45:29 +11:00
Luke Howard
51fd394065 [cxx-interop] fix typo in RetainReleaseOperationKind enum 2024-12-03 11:45:29 +11:00
Allan Shortlidge
5143382265 AST: Introduce Decl::isUnavailableInCurrentSwiftVersion(). 2024-12-02 07:35:58 -08:00
Allan Shortlidge
2358712870 AST/Sema: Remove DeclAttr::isUnavailable().
Update callers to use `Decl::isUnavailable()` instead.
2024-12-02 07:35:58 -08:00
Allan Shortlidge
cd13d7d777 AST: Remove AvailableAttr::RenameDecl.
The renamed decl is now stored exclusively in the split request evaluator
storage, which is more efficient since most availability attributes do not
specify a renamed decl.
2024-11-29 10:35:02 -05:00
Allan Shortlidge
5de7211984 AST: Rename createForAlternative() to createForAsyncAlternative(). 2024-11-22 14:35:47 -08:00
Gabor Horvath
51e92d9db4 [cxx-interop] Use the new lifetime dependence language feature flag
Non-escapable types are now enabled by default. Use the new lifetime
dependence feature flag to gate interpreting lifetime annotations on the
C++ side and add tests to make sure we get the expected diagnostics when
the feaature flag is off.
2024-11-21 13:13:16 +00:00
Doug Gregor
c5de02f60e Merge pull request #77628 from DougGregor/clang-importer-parse-request
[Clang importer] Use ParseSourceFileRequest for parsing swift_attr attributes
2024-11-16 01:12:27 -08:00
Doug Gregor
24a12ebc34 Renable GeneratedSourceInfo::Attribute to GeneratedSourceInfo::AttributeFromClang 2024-11-15 09:02:49 -08:00
Doug Gregor
f8f14b4ab6 [Clang importer] Use ParseSourceFileRequest for parsing swift_attr attributes
The Clang importer was directly calling into the parser to parse the
attribute (or modifier) within swift_attr. Aside from being gross, this
isn't possible with ASTGen.

Instead, teach ParseSourceFileRequest to deal with modifiers in the
same way that the Clang importer was hardcoding, and have the Clang
importer pull the attributes/modifiers off of the "missing"
declaration introduced by the request.

One benefit of this approach is that we're only parsing each
swift_attr source buffer once, then cloning the attributes each time
it's used, so we should be doing less work overall.

Fixes rdar://139119159.
2024-11-15 09:02:47 -08:00
Gabor Horvath
558380f6f8 [cxx-interop] Support conditional escapability
This PR adds a variadic macro that builds a SwiftAttr string containing
the names of the template type parameters that need to be escapable for
the type to be considered escapable. It also adds logic to interpret
this annotation.

rdar://139065437
2024-11-15 14:27:54 +00:00
Doug Gregor
aa4c548c0f Clang importer: switch swift_attr attribute text cache over to be module-sensitive
We need different buffers for each imported module that has swift_attr attributes,
so cache them appropriately.
2024-11-13 21:19:39 -08:00
Doug Gregor
989c73d014 Ensure that buffers containing Clang swift_attr attributes are parsed as attributes
Previously, they were being parsed as top-level code, which would cause
errors because there are no definitions. Introduce a new
GeneratedSourceInfo kind to mark the purpose of these buffers so the
parser can handle them appropriately.
2024-11-13 21:19:37 -08:00
Egor Zhdan
6943986c71 [cxx-interop] Import private fields of C++ structs
While private and protected fields coming from C++ cannot be accessed from Swift, they can affect Swift typechecking.

For instance, the Swift typechecker mechanism that adds implicit `Sendable` conformances works by iterating over all of the struct's fields and checking whether all of them are `Sendable`. This logic was broken for C++ types with private fields, since they were never accounted for. This resulted in erroneous implicit `Sendable` confromances being added.

Same applies for `BitwiseCopyable`.

In addition to this, ClangImporter used to mistakenly mark all C++ structs that have private fields as types with unreferenceable storage, which hampered optimizations.

As a side effect of this change, we now also provide a better diagnostic when someone tries to access a private C++ field from Swift.

rdar://134430857
2024-11-12 12:47:26 +00:00