Commit Graph

692 Commits

Author SHA1 Message Date
Ryan Mansfield
57ee779b02 [Test] Fix AutoDiff/SILGen/throw.swift ordering issue
The test was failing in CI with Debug stdlib due to a different
ordering of struct_extract operations. Changed to use CHECK-DAG
for the two independent struct_extract operations that can appear
in either order.

rdar://165265446
2025-11-25 12:00:59 -05:00
Slava Pestov
819738c83e AST: Rename mapTypeIntoContext() => mapTypeIntoEnvironment(), mapTypeOutOfContext() => mapTypeOutOfEnvironment() 2025-11-12 14:48:19 -05:00
Anton Korobeynikov
89a7663f1d [AutoDiff] Initial support for differentiation of throwing functions (#82653)
This adds initial support for differentiation of functions that may produce `Error` result. 

Essentially we wrap the pullback into `Optional` and emit a diamond-shape control flow pattern depending on whether the pullback value is available or not. VJP emission was modified to accommodate for this. In addition to this, some additional tricks are required as `try_apply` result is not available in the instruction parent block, it is available in normal successor basic block.

As a result we can now:
- differentiate an active `try_apply` result (that would be produced from `do ... try .. catch` constructions)
- `try_apply` when error result is unreachable (usually `try!` and similar source code constructs)
- Support (some) throwing functions with builtin differentiation operators. stdlib change will follow. Though we cannot support typed throws here (yet)
- Correctly propagate error types during currying around differentiable functions as well as type-checking for `@derivative(of:)` attribute, so we can register custom derivatives for functions producing error result
- Added custom derivative for `Optional.??` operator (note that support here is not yet complete as we cannot differentiate through autoclosures, so `x ?? y` works only if `y` is not active, e.g. a constant value).

Some fixes here and there
2025-11-06 13:12:43 -08:00
Anthony Latsis
e0ca132af2 Merge pull request #85102 from swiftlang/jepa-main2
[test] Remove pre-rebranch `nocapture` matches
2025-10-29 22:21:38 +00:00
Hamish Knight
b5627c9337 Merge pull request #85145 from a7medev/autodiff-comma-fix-its
[Diagnostics] Add missing fix-its for unexpected/expected comma in attribute arguments
2025-10-27 09:08:16 +00:00
Ahmed Mahmoud
d0c2d8b317 [Diagnostics] Add fix-its for unexpected/expected comma in auto-diff attributes 2025-10-26 23:47:19 +03:00
Anton Korobeynikov
186f88bead [AutoDiff] Fix two issues related with emission of differentiability witnesses (#80983)
1. When differentiable nested function (closure) is specialized by capture promotion pass ensure we generate a differentiability witness for the specialized function as well. Ensure the original witness is removed if the original function becomes dead. 
2. Differentiability witnesses for a function could originate either from its `@differentiable` attribute or from explicit `@derivative(of:)` attribute on the derivative. In the latter case the derivative itself might not be emitted, while original function is (e.g. original function is `@inlineable`, but derivative is `@usableFromInline`). Previously both cases were handled only when function body was emitted. As a result we missed witness in the aforementioned case. Ensure the
differentiability witness originating from `@derivative(of:)` is emitted even if we're not going to emit body of the derivative.

Fixes #59135
2025-10-24 20:02:08 -07:00
Anthony Latsis
b5aec4cc34 [test] Remove pre-rebranch nocapture matches
These were added in https://github.com/swiftlang/swift/pull/81375 (and
several other follow-up PRs because we missed a few places) and
are no longer needed.
2025-10-24 02:07:22 +01:00
Pavel Yaskevich
2b7adbc4ff Merge pull request #84800 from xedin/remove-csapply-operator-devirt
[CSApply] Don't attempt operator devirtualization
2025-10-18 23:09:23 +09:00
Daniil Kovalev
90ad689471 [AutoDiff][test] Enable some previously XFAIL'ed tests (#84915)
In #84704, some tests were XFAIL'ed since they've become failing. The
root cause of failures is lack of ownership info on the 2nd run of
AutoDiff closure specialization pass. Ownership info is required for the
pass run after #84704, so at the moment only the 1st run of the pass is
effective.

Several test cases still remain passing because for some cases we are
lucky and all the inlining required for specialization is done before
the 1st pass run. This patch enables such test cases back so we have at
least some test coverage.
2025-10-16 12:55:03 +00:00
Anton Korobeynikov
2943d63ce5 Update tests not to use Tracked<T> for now. Also XFAIL SIMD tests 2025-10-12 19:48:52 -07:00
Erik Eckstein
ecf7747335 autodiff: support the new array literal initialization pattern 2025-10-10 14:20:36 +02:00
Jaap Wijnen
b4fb57459d [AutoDiff] Make sure rhs is negated in all cases when subtracting two Array.TangentVectors (#84731)
`Array.TangentVector` conformance to `AdditiveArithmetic` was incorrect as the returned values weren't negated if the lhs was an empty vector (considered to be a zero tangentvector)
2025-10-08 17:07:59 -07:00
eeckstein
401a2ac2bc Merge pull request #84704 from eeckstein/closure-specialization
ClosureSpecialization: support for OSSA and a big overhaul
2025-10-07 06:59:08 +02:00
Erik Eckstein
df20d36255 ClosureSpecialization: support for OSSA and a big overhaul
Beside supporting OSSA, this change significantly simplifies the pass.
The main change is that instead of starting at a closure (e.g. `partial_apply`) and finding all call sites, we now start at a call site and look for closures for all arguments. This makes a lot of things much simpler, e.g. not so many intermediate data structures are required to track all the states.

I needed to remove the 3 unit tests because the things those tests were testing are not there anymore. However, the pass is tested with a lot of sil tests (and I added quite a few), which should give good test coverage.

The old ClosureSpecializer pass is still kept in place, because at that point in the pipeline we don't have OSSA, yet. Once we have that, we can replace the old pass withe the new one.
However, the autodiff closure specializer already runs in the OSSA pipeline and there the new changes take effect.
2025-10-06 12:02:48 +02:00
Henrik G. Olsson
cbc0ec3b88 Add -verify-ignore-unrelated where necessary (NFC)
These are tests that fail in the next commit without this flag. This
does not add -verify-ignore-unrelated to all tests with -verify, only
the ones that would fail without it. This is NFC since this flag is
currently a no-op.
2025-10-04 14:19:52 -07:00
Arnold Schwaighofer
25a071efc8 Add experimental feature @inline(always)
The intent for `@inline(always)` is to act as an optimization control.
The user can rely on inlining to happen or the compiler will emit an error
message.

Because function values can be dynamic (closures, protocol/class lookup)
this guarantee can only be upheld for direct function references.

In cases where the optimizer can resolve dynamic function values the
attribute shall be respected.

rdar://148608854
2025-09-30 08:36:26 -07:00
Anton Korobeynikov
e6409d7d9d Correctly handle multiple semantic results for autodiff subset differential thunks (#84366)
Fixes https://github.com/swiftlang/swift/issues/84365
2025-09-19 13:54:30 -07:00
Anton Korobeynikov
7668666ad2 Support differentiation of wrapped value modify accessors (#78794)
Some fixes for coroutines with normal results and `partial_apply` of coroutines were required.

Fixes #55084
2025-09-10 02:30:26 -07:00
Eric Miotto
1034a7a24b Do not an AutoDiff test on backdeployment configurations 2025-08-07 15:13:44 -07:00
Ryan Mansfield
02747ded65 Add %target-codesign to newly added AutoDiff tests.
rdar://155386319
2025-07-09 19:58:00 -06:00
Meghana Gupta
ce6ac88813 Enable test for 64bit platforms only 2025-07-08 06:43:32 -07:00
Daniil Kovalev
5528cf1cc4 [AutoDiff] Run AutoDiff closure spec pass for all VJPs (#81548)
Previously, AutoDiff closure specialization pass was triggered only on
VJPs containing single basic block. However, the pass logic allows
running on arbitrary VJPs. This PR enables the pass for all VJPs
unconditionally. So, if the pullback corresponding to multiple-BB VJP
accepts some closures directly as arguments, these closures might become
specialized by the pass. Closures passed via payload of branch tracing
enum are not specialized - this is subject for future changes.

The PR contains several commits.
1. The thing named "call site" in the code is partial_apply of pullback
corresponding to the VJP. This might appear only once, so we drop
support for multiple "call sites".
2. Enhance existing SILOptimizer tests for the pass.
3. Add validation-tests for single basic block case.
4. The change itself - delete check against single basic block.
5. Add validation-tests for multiple basic block case.
6. Add SILOptimizer tests for multiple basic block case.
2025-07-07 13:00:14 +00:00
Erik Eckstein
6714a72256 Optimizer: re-implement and improve the AllocBoxToStack pass
This pass replaces `alloc_box` with `alloc_stack` if the box is not escaping.
The original implementation had some limitations. It could not handle cases of local functions which are called multiple times or even recursively, e.g.

```
public func foo() -> Int {
  var i = 1

  func localFunction() { i += 1 }

  localFunction()
  localFunction()
  return i
}

```

The new implementation (done in Swift) fixes this problem with a new algorithm.
It's not only more powerful, but also simpler: the new pass has less than half lines of code than the old pass.

The pass is invoked in the mandatory pipeline and later in the optimizer pipeline.
The new implementation provides a module-pass for the mandatory pipeline (whereas the "regular" pass is a function pass).
This is required because the mandatory pass needs to remove originals of specialized closures, which cannot be done from a function-pass.
In the old implementation this was done with a hack by adding a semantic attribute and deleting the function later in the pipeline.

I still kept the sources of the old pass for being able to bootstrap the compiler without a host compiler.

rdar://142756547
2025-06-20 08:15:04 +02:00
Ryan Mansfield
44ec621980 Add %target-codesign to executables and dylibs in newly added AutoDiff tests. 2025-05-28 23:13:30 -04:00
eeckstein
ddca2bae98 Merge pull request #81706 from eeckstein/mandatory-temprvalue-elimination
Optimizer: Improve performance of large InlineArrays at Onone
2025-05-26 07:56:42 +02: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
Erik Eckstein
198d4ab0bb Optimizer: run TempRValueElimination also at Onone
Introduce a new pass MandatoryTempRValueElimination, which works as the original TempRValueElimination, except that it does not remove any alloc_stack instruction which are associated with source variables.

Running this pass at Onone helps to reduce copies of large structs, e.g. InlineArrays or structs containing InlineArrays.
Copying large structs can be a performance problem, even at Onone.

rdar://151629149
2025-05-23 18:56:56 +02:00
Anton Korobeynikov
799e0f81b0 [AutoDiff] Correct propagate adjoints for array literal values (#81676)
Fixes #81607
2025-05-22 03:03:28 -07:00
Anton Korobeynikov
bc94ac3342 [AutoDiff] Better diagnose non-differentiability for throwing functions (#81669)
Fixes #81608
2025-05-21 09:13:18 -07:00
finagolfin
35ee368bb9 [android][test] Fix or disable the remaining failing tests on the Android CI (#81398)
Also, fix and enable `IRGen/lto_autolink` for all non-Wasm targets and
`IRGen/static_initializer` for aarch64.


This should get [the community Android
CI](https://ci-external.swift.org/job/oss-swift-RA-linux-ubuntu-24.04-android-build/)
green
[again](https://ci-external.swift.org/job/oss-swift-RA-linux-ubuntu-24.04-android-arm64/).
2025-05-17 13:27:33 +05:30
Becca Royal-Gordon
b6be85222f Standardize serialization of DeclNameRefs
There are four attributes which serialize out a DeclNameRef, sometimes by dropping some of its components. Standardize them with a representation that can handle module selectors.
2025-05-14 11:16:30 -07:00
Anthony Latsis
55e5618eab [test] Match nocapture to succeed both on main and rebranch
Both the syntax and relative order of the LLVM `nocapture` parameter
attribute changed upstream in 29441e4f5fa5f5c7709f7cf180815ba97f611297.
To reduce conflicts with rebranch, adjust FileCheck patterns to expect
both syntaxes and orders anywhere the presence of the attribute is not
critical to the test. These changes are temporary and will be cleaned
up once rebranch is merged into main.
2025-05-08 23:52:43 +01:00
Anthony Latsis
17fc00f8a7 [test] IRGen: Adjust FileCheck patterns for new nuw attribute in upstream LLVM
This attribute was introduced in
7eca38ce76d5d1915f4ab7e665964062c0b37697 (llvm-project).

Match it using a wildcard regex, since it is not relevant to these
tests.

This is intended to reduce future conflicts with rebranch.
2025-05-04 03:28:56 +01:00
Erik Eckstein
8cf4e34cc1 RedundantLoadElimination: support replacing a redundant copy_addr with a store
For example:
```
  %0 = load %1
  copy_addr %1 to %2
```
->
```
  %0 = load %1
  store %0 to %2
```

This is important for MandatoryRedundantLoadElimination to be able to create statically initialized globals in the mandatory pipeline.
For example:
```
public struct MyStruct {
  public static let r: Range<Int> = 1 ..< 3
}

```
gets a statically initialized global, even at Onone, with this improvement.

rdar://149356742
2025-04-23 11:57:28 +02:00
Anton Korobeynikov
87ca0f8680 Fix ownership issues with sequences of partial_apply's in AutoDiff closure specialization pass (#80662)
Each partial_apply consumes its arguments, therefore we should never release intermediate ones in the sequence of closures.

Fixes #78847
2025-04-15 07:14:44 -07:00
Daniil Kovalev
5d0bfed9e8 [AutoDiff] Fix adjoints for loop-local active values (#78374)
Fixes #78264
2025-04-15 06:49:15 -07:00
Allan Shortlidge
b97ec5bbe5 Sema: Improve MemberImportVisibility diags for for-in loops.
Ensure that source locations are attached to the implicit calls to
`makeIterator()` and `next()` for diagnostics.

Partially resolves rdar://144535697.
2025-04-05 09:47:56 -07:00
Anthony Latsis
08d46d2542 Merge pull request #80473 from AnthonyLatsis/diag_type_attr
DiagnosticEngine: Support `TypeAttribute` diagnostic arguments
2025-04-05 12:25:45 +01:00
Anthony Latsis
99f63ed933 DiagnosticEngine: Support TypeAttribute diagnostic arguments 2025-04-03 01:52:38 +01:00
Erik Eckstein
4d1df28de0 ConstantFolding: add constant folding for some floating point intrinsics
* `sitofp` signed integer to floating point
* `rint` round floating point to integral
* `bitcast` between integer and floating point

Constant folding `bitcast`s also made it necessary to rewrite constant folding for Nan and inf values, because the old code explicitly checked for `bitcast` intrinsics.
Relying on constant folded `bitcast`s makes the new version much simpler.

It is important to constant fold these intrinsics already in SIL because it enables other optimizations.
2025-04-01 18:13:01 +02:00
Anton Korobeynikov
42e530f9ab Add tests 2025-02-24 15:20:46 -08:00
Daniil Kovalev
83a028d105 [AutoDiff] Allow closure differentiation when used as default arg val (#78373)
If the default argument generator (and, consequently, the function taking this default argument) has public visibility, it's OK to have a closure (which always has private visibility) as the default value of the argument.
2025-02-19 22:34:56 -08:00
Daniil Kovalev
1a42a0ce5f [AutoDiff] Support curry thunks differentiation in fragile funcs (#77615)
Inside fragile functions, we expect function derivatives to be public, which could be achieved by either explicitly marking the functions as differentiable or having a public explicit derivative defined for them. This is obviously not
possible for single and double curry thunks which are a special case of `AutoClosureExpr`.

Instead of looking at the thunk itself, we unwrap it and look at the function being wrapped. While the thunk itself and its differentiability witness will not have public visibility, it's not an issue for the case where the function being wrapped (and its witness) have public visibility.

Fixes #54819
Fixes #75776
2025-02-17 14:43:50 -08:00
Joe Groff
27386786a0 Merge pull request #79161 from jckarter/end-apply-coroutine-iterator-invalidation
IRGen: Fix DenseMap interior pointer invalidation bug in IRGenSILFunction::visitEndApply.
2025-02-06 09:39:16 -08:00
Anton Korobeynikov
1e7a1d91fc Emit reabstraction thunks for implicit conversions between T.TangentType and Optional<T>.TangentType (#78076) 2025-02-05 20:57:52 -08:00
Joe Groff
3d779cd789 IRGen: Fix DenseMap interior pointer invalidation bug in IRGenSILFunction::visitEndApply.
Fixes rdar://144216380.
2025-02-05 15:50:09 -08:00
Arnold Schwaighofer
4a2d8dc6a5 Disable test that will block releasing toolchains AutoDiff/validation-test/modify_accessor.swift
Until folks look at whats wrong.

This triggered a use-after-free in IRGen while visiting end_apply on the ASAN bot.

https://ci.swift.org/job/oss-swift-incremental-ASAN-RA-macos/7721/

Likely triggered by the changes in https://github.com/swiftlang/swift/pull/79127 (based on blame list)

rdar://144216380
2025-02-05 07:18:45 -08:00
Erik Eckstein
830565b0f0 - test changes 2025-01-30 17:10:03 -08:00
Michael Gottesman
6058b1d9bd [silgen] Change SILGen to emit ignored_user for emitIgnoredExpr and black hole initialization. 2025-01-22 21:12:36 -08:00