Commit Graph

9306 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
Joe Groff
dd59797638 Merge pull request #81617 from jckarter/no-non-escapable-property-descriptors
SILGen: Emit property descriptors for conditionally Copyable and Escapable types.
2025-05-27 19:22:56 -07:00
Meghana Gupta
1998f416a5 Merge pull request #81678 from meg-gupta/fixsubst
Fix use-after-free on substituting function type involving conditional ~Escapable with Escapable type
2025-05-27 12:47:29 -07:00
Joe Groff
22eb7e62d9 SILGen: Emit property descriptors for conditionally Copyable and Escapable types.
Key paths can't reference non-escapable or non-copyable storage declarations,
so we don't need to refer to them resiliently, and can elide their property
descriptors.

However, declarations may still be conditionally Copyable and Escapable, and
if so, then they still need a property descriptor for resilient key path
references. When a property or subscript can be used in a context where it
is fully Copyable and Escapable, emit the property descriptor in a generic
environment constrained by the necessary conditional constraints.

Fixes rdar://151628396.
2025-05-27 09:35:40 -07:00
Daniil Kovalev
1e403ecf5c [AutoDiff] Support custom derivatives for @_alwaysEmitIntoClient functions (#78908)
Consider an `@_alwaysEmitIntoClient` function and a custom derivative
defined
for it. Previously, such a combination resulted different errors under
different
circumstances.

Sometimes, there were linker errors due to missing derivative function
symbol -
these occurred when we tried to find the derivative in a module, while
it
should have been emitted into client's code (and it did not happen).

Sometimes, there were SIL verification failures like this:

```
SIL verification failed: internal/private function cannot be serialized or serializable: !F->isAnySerialized() || embedded
```

Linkage and serialization options for the derivative were not handled
properly,
and, instead of PublicNonABI linkage, we had Private one which is
unsupported
for serialization - but we need to serialize `@_alwaysEmitIntoClient`
functions
so the client's code is able to see them.

This patch resolves the issue and adds proper handling of custom
derivatives
of `@_alwaysEmitIntoClient` functions. Note that either both the
function and
its custom derivative or none of them should have
`@_alwaysEmitIntoClient`
attribute, mismatch in this attribute is not supported.

The following cases are handled (assume that in each case client's code
uses
the derivative).

1. Both the function and its derivative are defined in a single file in
   one module.

2. Both the function and its derivative are defined in different files
which
   are compiled to a single module.

3. The function is defined in one module, its derivative is defined in
another
   module.

4. The function and the derivative are defined as members of a protocol
extension in two separate modules - one for the function and one for the
   derivative. A struct conforming the protocol is defined in the third
   module.

5. The function and the derivative are defined as members of a struct
extension in two separate modules - one for the function and one for the
   derivative.

The changes allow to define derivatives for methods of `SIMD`.

Fixes #54445
<!--
If this pull request is targeting a release branch, please fill out the
following form:

https://github.com/swiftlang/.github/blob/main/PULL_REQUEST_TEMPLATE/release.md?plain=1

Otherwise, replace this comment with a description of your changes and
rationale. Provide links to external references/discussions if
appropriate.
If this pull request resolves any GitHub issues, link them like so:

  Resolves <link to issue>, resolves <link to another issue>.

For more information about linking a pull request to an issue, see:

https://docs.github.com/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue
-->

<!--
Before merging this pull request, you must run the Swift continuous
integration tests.
For information about triggering CI builds via @swift-ci, see:

https://github.com/apple/swift/blob/main/docs/ContinuousIntegration.md#swift-ci

Thank you for your contribution to Swift!
-->
2025-05-25 09:47:15 -04: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
eeckstein
021bd4a2c4 Merge pull request #81684 from eeckstein/fix-mark-dependence-addr
SIL: define `mark_dependence_addr` to read and write to its address operand
2025-05-22 07:10:24 +02:00
Meghana Gupta
dbe548d4e1 Fix use-after-free on substituting function type involving conditional ~Escapable with Escapable type 2025-05-21 15:40:49 -07:00
nate-chandler
393465262b Merge pull request #81581 from nate-chandler/rdar147207926
[TypeLowering] Record packs used in signatures.
2025-05-21 13:37:10 -07:00
Erik Eckstein
e0f5888a8d SIL: define mark_dependence_addr to read and write to its address operand
This prevents simplification and SILCombine passes to remove (alive) `mark_dependence_addr`.
The instruction is conceptually equivalent to
```
  %v = load %addr
  %d = mark_dependence %v on %base
  store %d to %addr
```

Therefore the address operand has to be defined as writing to the address.
2025-05-21 20:03:53 +02:00
Egor Zhdan
5583f93de3 Merge pull request #81614 from swiftlang/egorzhdan/silverifier-trivial-frt
[cxx-interop] Relax a SILVerifier assertion for immortal reference types
2025-05-21 12:59:55 +01:00
Nate Chandler
aa49b8540d [TypeLowering] Record packs used in signatures.
To determine whether an instruction may require pack metadata, the types
of its operands are examined.

Previously, the top level type was checked for having a pack in its
signature, and the whole type was checked for having a type anywhere in
its layout (via TypeLowering).  This didn't account for the case where
the metadata was required for a resilient type which uses a pack in its
signature.

Here, during type lowering, a type having a pack in its signature is
counted towards the type having a pack.

Fixes a compiler crash.

rdar://147207926
2025-05-20 16:53:28 -07:00
Erik Eckstein
9052652651 add the prepareInitialization builtin.
It is like `zeroInitializer`, but does not actually initialize the memory.
It only indicates to mandatory passes that the memory is going to be initialized.
2025-05-20 20:46:33 +02:00
Stephen Canon
3aa7b592b6 Implement Builtin.select binding llvm select instruction (#81598)
Not used (yet), but needed to implement SIMD.replacing(with:where:) idiomatically, and probably useful otherwise.
2025-05-20 13:30:59 -04:00
Egor Zhdan
2e3df1c0f3 [cxx-interop] Relax a SILVerifier assertion for immortal reference types
Immortal C++ foreign reference types get TrivialTypeLowering instead of ReferenceTypeLowering, since they do not have retain/release lifetime operations. This was tripping up an assertion in SILVerifier.

rdar://147251759 / resolves https://github.com/swiftlang/swift/issues/80065
2025-05-20 13:58:43 +01:00
Hamish Knight
3ec3421987 Merge pull request #81604 from hamishknight/pretty-crash
Adopt `ABORT` throughout the compiler
2025-05-20 10:05:03 +01: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
Michael Gottesman
abcc134621 Merge pull request #81542 from gottesmm/rdar150209093_rdar151394209
[concurrency] Fix a few issues around not emitted correct protocol witness and vtable thunks for nonisolated(nonsending)
2025-05-19 10:43:18 -07:00
Meghana Gupta
f7529eae86 Merge pull request #81520 from meg-gupta/disableverifysemantics
Add a new semantics attribute to disable SIL verification on a function
2025-05-16 15:38:32 -07:00
Meghana Gupta
aa01b2ad06 Add a new semantics attribute to disable SIL verification on a function
This provides a way to disable verification per function instead of the entire module.
2025-05-15 14:30:28 -07:00
Michael Gottesman
39a013f807 [silgen] Place the correct isolation on protocol witness thunks.
We were using the isolation from the witness not from the requirement which we
are supposed to do. The witness thunk thunks the isolation from the requirement
to the witness so from an ABI perspective it should have the interface implied
by the requirement's isolation since that is what callers of the witness method
will expect.

rdar://151394209
2025-05-15 14:11:55 -07:00
Michael Gottesman
ff1cbea576 [silgen] Begin placing isolation on protocol witness thunks.
This will cause tests today to crash since even though we are placing the
isolation now, to make it easier to read, I left in the old isolation selecting
code. This code uses the witness's isolation instead of the requirement's
isolation which is incorrect since the protocol witness thunk needs to look the
requirement from an ABI perspective since the two must be substitutable. The
crash comes from the ABI verification I added in earlier commits.
2025-05-15 14:10:43 -07:00
Michael Gottesman
ed1654c3cf [sil] Verify that witness table witnesses are ABI compatible with their requirements. 2025-05-15 14:04:34 -07:00
Michael Gottesman
634435d8cf [gardening] Clean up SILWitnessTable::verify before I touch it.
I just renamed a few variables and eliminated a bunch of unnecessary
indentation.

Just to make it easier to review the actual functional change.
2025-05-15 14:04:34 -07:00
Michael Gottesman
e25c664c98 [sil] Change SILDefaultWitnessTable verification to use verificationEnabled instead of #ifndef NDEBUG to match the rest of the SILVerifier.
I think this was just an oversight. There is really no reason that this should
not match the rest of the SILVerifier w here we have moved from using #ifndef
NDEBUG to verificationEnabled checking.
2025-05-15 14:04:34 -07:00
Michael Gottesman
71adae4c0c [gardening] Cleanup SILDefaultWitnessTable before I change it.
Just to make review easier.
2025-05-15 14:04:34 -07:00
Pavel Yaskevich
6c911f5d42 [SIL] Add isolation captured by @_inheritActorContext(always) while lowering captures
`getLoweredLocalCaptures` seems the best place to do it because
during Sema there is a chicken and an egg situation where isolation
depends on captures and in this case captures depend on isolation.
2025-05-14 20:08:00 -07:00
Erik Eckstein
dc0e7a34ae SIL: Make the verifier's ImmutableAddressUseVerifier generally available
Also, make it more tolerant to instructions and builtins, which are not explicitly handled.
This avoids crashes when new instructions are added. We got lucky that this didn't happen so far.
2025-05-13 18:53:31 +02:00
Erik Eckstein
a38db6439a SIL: add the vector_base_addr instruction
It derives the address of the first element of a vector, i.e. a `Builtin.FixedArray`, from the address of the vector itself.
Addresses of other vector elements can then be derived with `index_addr`.
2025-05-12 19:24:31 +02:00
Michael Gottesman
ced96aa5cd [concurrency] Ensure that we treat closures that are nonisolated(nonsending) via their ActorIsolation as nonisolated(nonsending).
Some notes:

1. In most cases, I think we were getting lucky with this by just inferring the
closure's isolation from its decl context. In the specific case that we were
looking at here, this was not true since we are returning from an @concurrent
async function a nonisolated(nonsending) method that closes over self. This
occurs since even when NonisolatedNonsendingByDefault we want to start importing
objc async functions as nonisolated(nonsending).

2. I also discovered that in the ActorIsolationChecker we were not visiting the
inner autoclosure meaning that we never set the ActorIsolation field on the
closure. After some discussion with @xedin about potentially visiting the
function in the ActorIsolationChecker, we came to the conclusion that this was
likely to result in source stability changes. So we put in a targeted fix just
for autoclosures in this specific case by setting their actor isolation in the
type checker.

3. Beyond adding tests to objc_async_from_swift to make sure that when
NonisolatedNonsendingByDefault is disabled we do the right thing, I noticed that
we did not have any tests that actually tested the behavior around
objc_async_from_swift when NonisolatedNonsendingByDefault is enabled. So I added
the relevant test lines so we can be sure that we get correct behavior in such a
case.

rdar://150209093
2025-05-06 14:15:23 -07: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
eeckstein
fba1f1d21c Merge pull request #81253 from eeckstein/copy-block-opt2
Optimizer: support partial_apply of thunks in the `copy_block` simplification
2025-05-05 07:40:08 +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
Erik Eckstein
55d1e8276b SIL ownership verifier: don't require scope-ending instructions for unchecked_ownership_conversion
The optimizer may convert unowned blocks to guaranteed blocks for a partial_apply. This does not require any scope-ending instructions.
2025-05-02 18:07:35 +02:00
eeckstein
cc11a9baf3 Merge pull request #81203 from eeckstein/fix-objc-class-casting
CastOptimizer: don't assume dynamic casts from ObjectiveC classes to unrelated classes will fail
2025-05-02 07:07:56 +02: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
Meghana Gupta
3cad5c5924 Merge pull request #81043 from meg-gupta/fixcow
Insert end_cow_mutation_addr for lifetime dependent values dependent on mutable addresses
2025-05-01 07:26:28 -07:00
Meghana Gupta
35d62a4a36 Introduce end_cow_mutation_addr instruction 2025-04-30 13:39:45 -07:00
Slava Pestov
6ffa8fd489 AST: Change signature of LookupConformanceFn
Instead of passing in the substituted type, we pass in the
InFlightSubstitution. This allows the substituted type to be
recovered if needed, but we can now skip computing it for
the common case of LookUpConformanceInSubstitutionMap.
2025-04-30 13:42:20 -04:00
Erik Eckstein
7a5dbdc20b CastOptimizer: don't assume dynamic casts from ObjectiveC classes to unrelated classes will fail
In case of ObjectiveC classes, the runtime type can differ from its declared type.
Therefore a cast between (compile-time) unrelated classes may succeed at runtime.

rdar://149810124
2025-04-30 16:42:42 +02:00
eeckstein
e2ee00700f Merge pull request #81159 from eeckstein/deinit-barrier-optimizations
Some small deinit-barrier related optimizations
2025-04-30 15:33:46 +02:00
Slava Pestov
6b4710ed22 Merge pull request #81142 from slavapestov/more-type-subst-cleanup
Clean up duplicated opened existential archetype handling in SIL and more
2025-04-30 02:42:57 -04:00
Slava Pestov
7b5b5e9602 Merge pull request #81171 from slavapestov/fix-issue-81036
AST: Use weighted reduction order for opaque return types
2025-04-30 01:53:29 -04:00
Erik Eckstein
ffc17322f9 SIL: bridge Function.isDeinitBarrier back from Swift to C++ SIL
This API already existed in Swift, but not in the C++ SIL.
2025-04-29 20:30:21 +02:00
Slava Pestov
e1fc29193d AST: Add GenericTypeParamType::getWeight()
This is currently always 0, but can be set to 1.
2025-04-29 13:55:29 -04:00
Slava Pestov
7285a9b4e1 SIL: Basic block argument type should not contain type parameters 2025-04-29 10:54:59 -04:00
Slava Pestov
2fa49b0458 AST: SubstitutionMap overload of substOpaqueTypesWithUnderlyingTypes()
This replaces the oddly-named mapIntoTypeExpansionContext() method
on SubstitutionMap itself in favor of a global function, just like
the ones that take Type and ProtocolConformanceRef.
2025-04-28 13:48:35 -04:00
nate-chandler
b93ed3e32b Merge pull request #81081 from swiftlang/revert-80839-moveonly-trivial-field-as-reinitialize
Revert "MoveOnlyChecker: Treat trivial stores as reinitializations rather than initializations."
2025-04-24 19:34:08 -07:00
Slava Pestov
57ca3d4d54 Merge pull request #81079 from slavapestov/fix-rdar149353285
SIL: Use SubstitutionMap::mapIntoTypeExpansionContext() in SILTypeSubstituter
2025-04-24 19:09:37 -04:00
nate-chandler
c66bf26377 Merge pull request #81065 from nate-chandler/rdar149850921
[FSPL] Look through unchecked addr casts.
2025-04-24 15:22:44 -07:00