45 Commits

Author SHA1 Message Date
Michael Chiu
84ee0af416 CLongDouble should map to Float128 (which is yet supported) on arm64, and trivial copy ctor is yet available even on 14 2025-06-02 13:39:50 -04:00
Michael Chiu
7f0f2ac4dd Merge swiftlang#38335 2025-03-14 02:15:15 -04:00
Ben Barham
ef8825bfe6 Migrate llvm::Optional to std::optional
LLVM has removed llvm::Optional, move over to std::optional. Also
clang-format to fix up all the renamed #includes.
2024-02-21 11:20:06 -08:00
Anton Korobeynikov
4d391f0f8e Add Differentiable requirements to pattern substitutions / pattern generic signature (#68777)
Add `Differentiable` requirements to pattern substitutions / pattern generic signature when calculating constrained function type. Also, add requirements for differentiable results as well.

Fixes #65487
2023-10-04 14:48:03 -07:00
Anton Korobeynikov
03334a8f92 [AutoDiff] Generalize handling of semantic result parameters (#67230)
Introduce the notion of "semantic result parameter". Handle differentiation of inouts via semantic result parameter abstraction. Do not consider non-wrt semantic result parameters as semantic results

Fixes #67174
2023-08-03 09:33:11 -07:00
Anton Korobeynikov
eb82df6bc6 [AutoDiff] Support differentiable functions with multiple semantic results (#66873)
Add support for differentiable functions having multiple semantic results

Co-authored-by: Brad Larson <larson@sunsetlakesoftware.com>
2023-07-06 16:31:39 -07:00
Evan Wilde
250082df25 [NFC] Reformat all the LLVMs
Reformatting everything now that we have `llvm` namespaces. I've
separated this from the main commit to help manage merge-conflicts and
for making it a bit easier to read the mega-patch.
2023-06-27 09:03:52 -07:00
Evan Wilde
f3ff561c6f [NFC] add llvm namespace to Optional and None
This is phase-1 of switching from llvm::Optional to std::optional in the
next rebranch. llvm::Optional was removed from upstream LLVM, so we need
to migrate off rather soon. On Darwin, std::optional, and llvm::Optional
have the same layout, so we don't need to be as concerned about ABI
beyond the name mangling. `llvm::Optional` is only returned from one
function in
```
getStandardTypeSubst(StringRef TypeName,
                     bool allowConcurrencyManglings);
```
It's the return value, so it should not impact the mangling of the
function, and the layout is the same as `std::optional`, so it should be
mostly okay. This function doesn't appear to have users, and the ABI was
already broken 2 years ago for concurrency and no one seemed to notice
so this should be "okay".

I'm doing the migration incrementally so that folks working on main can
cherry-pick back to the release/5.9 branch. Once 5.9 is done and locked
away, then we can go through and finish the replacement. Since `None`
and `Optional` show up in contexts where they are not `llvm::None` and
`llvm::Optional`, I'm preparing the work now by going through and
removing the namespace unwrapping and making the `llvm` namespace
explicit. This should make it fairly mechanical to go through and
replace llvm::Optional with std::optional, and llvm::None with
std::nullopt. It's also a change that can be brought onto the
release/5.9 with minimal impact. This should be an NFC change.
2023-06-27 09:03:52 -07:00
Anthony Latsis
4cb63c8a0f [NFC] Migrate remnant Jira issue references to GitHub issues 2022-12-04 08:20:34 +03:00
Ben Barham
bd4b73755b [next] Update DenseMapInfo declarations
llvm-project 4c484f11d355e4293f7b245a9330f0a1e89630ac updated the
`DenseMapInfo` template to take a SFINAE template parameter.
2021-11-18 21:58:56 +10:00
Robert Widmann
a0615e9848 [NFC] Use GenericSIgnature::getGanonicalSignature Where Possible 2021-07-22 23:27:06 -07:00
Richard Wei
e494df2ee6 [AutoDiff] Add differentiability kind to differentiability witnesses and mangle them.
Differentiability witnesses are now keyed by the original function name, the differentiability kind, and the autodiff config.

Updated SIL syntax:
```
differentiability-kind ::= 'forward' | 'reverse' | 'normal' | 'linear'
sil-differentiability-witness ::=
    'sil_differentiability_witness'
    sil-linkage?
    '[' differentiability-kind ']'
    '[' 'parameters' sil-differentiability-witness-function-index-list ']'
    '[' 'results' sil-differentiability-witness-function-index-list ']'
    generic-parameter-clause?
    sil-function-name ':' sil-type
    sil-differentiability-witness-body?
sil-instruction ::=
    'differentiability_witness_function'
    '[' sil-differentiability-witness-function-kind ']'
    '[' differentiability-kind ']'
    '[' 'parameters' sil-differentiability-witness-function-index-list ']'
    '[' 'results' sil-differentiability-witness-function-index-list ']'
    generic-parameter-clause?
    sil-function-name ':' sil-type
```
```console
sil_differentiability_witness [reverse] [parameters 0 1] [results 0] <T where T: Differentiable> @foo : <T> $(T) -> T
differentiability_witness_function [vjp] [reverse] [parameters 0] [results 0] <T where T: Differentiable> @foo : $(T) -> T
```

New mangling:
```swift
  global ::= global generic-signature? 'WJ' DIFFERENTIABILITY-KIND INDEX-SUBSET 'p' INDEX-SUBSET 'r' // differentiability witness
```
```console
$s13test_mangling3fooyS2f_S2ftFWJrSpSr ---> reverse differentiability witness for test_mangling.foo(Swift.Float, Swift.Float, Swift.Float) -> Swift.Float with respect to parameters {0} and results {0}
```

Resolves rdar://74380324.
2021-02-17 18:27:42 -05:00
Richard Wei
af8942d940 [AutoDiff] Rename '@differentiable' to '@differentiable(reverse)'.
Compiler:
- Add `Forward` and `Reverse` to `DifferentiabilityKind`.
- Expand `DifferentiabilityMask` in `ExtInfo` to 3 bits so that it now holds all 4 cases of `DifferentiabilityKind`.
- Parse `@differentiable(reverse)` and `@differentiable(_forward)` declaration attributes and type attributes.
- Emit a warning for `@differentiable` without `reverse`.
- Emit an error for `@differentiable(_forward)`.
- Rename `@differentiable(linear)` to `@differentiable(_linear)`.
- Make `@differentiable(reverse)` type lowering go through today's `@differentiable` code path. We will specialize it to reverse-mode in a follow-up patch.

ABI:
- Add `Forward` and `Reverse` to `FunctionMetadataDifferentiabilityKind`.
- Extend `TargetFunctionTypeFlags` by 1 bit to store the highest bit of differentiability kind (linear). Note that there is a 2-bit gap in `DifferentiabilityMask` which is reserved for `AsyncMask` and `ConcurrentMask`; `AsyncMask` is ABI-stable so we cannot change that.

_Differentiation module:
- Replace all occurrences of `@differentiable` with `@differentiable(reverse)`.
- Delete `_transpose(of:)`.

Resolves rdar://69980056.
2021-02-07 14:09:46 -08:00
Richard Wei
ffe6064101 Mangle derivative functions and linear maps.
- `Mangle::ASTMangler::mangleAutoDiffDerivativeFunction()` and `Mangle::ASTMangler::mangleAutoDiffLinearMap()` accept original function declarations and return a mangled name for a derivative function or linear map. This is called during SILGen and TBDGen.
- `Mangle::DifferentiationMangler` handles differentiation function mangling in the differentiation transform. This part is necessary because we need to perform demangling on the original function and remangle it as part of a differentiation function mangling tree in order to get the correct substitutions in the mangled derivative generic signature.

A mangled differentiation function name includes:
- The original function.
- The differentiation function kind.
- The parameter indices for differentiation.
- The result indices for differentiation.
- The derivative generic signature.
2021-01-07 02:21:10 -08:00
Richard Wei
8d8614058b [AudoDiff] NFC: Replace 'SILAutoDiffIndices' with 'AutoDiffConfig'. (#35079)
Resolve rdar://71678394 / SR-13889.
2020-12-14 14:32:40 -08:00
Marc Rasi
7191c9c21d [AutoDiff] remove all-concrete gen sig from more places 2020-07-15 17:28:14 -07:00
Dan Zheng
f163072b2a [AutoDiff] Add TangentStoredPropertyRequest.
Add request that resolves the "tangent stored property" corresponding to an
original stored property in a `Differentiable`-conforming type.

Enables better non-differentiability differentiation transform diagnostics.
2020-06-22 10:10:56 -07:00
Dan Zheng
330dc01634 [AutoDiff upstream] NFC: garden doc comment. (#32264) 2020-06-09 16:39:30 -07:00
Dan Zheng
d3b6b89de6 [AutoDiff] Support multiple differentiability result indices in SIL. (#32206)
`DifferentiableFunctionInst` now stores result indices.
`SILAutoDiffIndices` now stores result indices instead of a source index.

`@differentiable` SIL function types may now have multiple differentiability
result indices and `@noDerivative` resutls.

`@differentiable` AST function types do not have `@noDerivative` results (yet),
so this functionality is not exposed to users.

Resolves TF-689 and TF-1256.

Infrastructural support for TF-983: supporting differentiation of `apply`
instructions with multiple active semantic results.
2020-06-05 16:25:17 -07:00
Dan Zheng
489b6e0860 [AutoDiff] Clean up derivative type calculation.
Remove all assertions from `AnyFunctionType::getAutoDiffDerivativeFunctionLinearMapType`.
All error cases are represented by `DerivativeFunctionTypeError` now.

Fix `DerivativeFunctionTypeError` error payloads and improve error case naming.
2020-05-12 13:39:12 -07:00
Dan Zheng
8500cf8341 [AutoDiff] Revamp derivative type calculation using llvm::Expected. (#31727)
Create `DerivativeFunctionTypeError` representing all potential derivative
function type calculation errors.

Make `AnyFunctionType::getAutoDiffDerivativeFunctionLinearMapType` return
`llvm::Expected<AnyFunctionType *>`. This is much safer and caller-friendly
than performing assertions.

Delete hacks in `@differentiable` and `@derivative` attribute type-checking
for verifying that `Differentiable.TangentVector` type witnesses are valid:
this is no longer necessary.

Robust fix for TF-521: invalid `Differentiable` conformances during
`@derivative` attribute type-checking.

Resolves SR-12793: bad interaction between `@differentiable` and `@derivative`
attribute type-checking and `Differentiable` derived conformances.
2020-05-12 06:09:41 -07:00
Michael Forster
fae87c96d7 Move interleave(...) to the llvm namespace
This simplifies fixing the master-next build. Upstream LLVM already
has a copy of this function, so on master-next we only need to delete
the Swift copy, reducing the potential for merge conflicts.
2020-04-17 11:20:50 +02:00
Dan Zheng
77d0d99f81 [AutoDiff] NFC: move isDifferentiableProgrammingEnabled.
Move `isDifferentiableProgrammingEnabled` to AutoDiff.h so it's more accessible.
2020-04-07 11:01:00 -07:00
Dan Zheng
04686a091f [AutoDiff] NFC: add ASTMangler entry points for AutoDiff-generated decls.
Add `ASTMangler::mangleAutoDiffGeneratedDeclaration`.
2020-04-07 11:00:46 -07:00
Dan Zheng
aa66cce808 [AutoDiff upstream] Add differentiation transform.
The differentiation transform does the following:
- Canonicalizes differentiability witnesses by filling in missing derivative
  function entries.
- Canonicalizes `differentiable_function` instructions by filling in missing
  derivative function operands.
- If necessary, performs automatic differentiation: generating derivative
  functions for original functions.
  - When encountering non-differentiability code, produces a diagnostic and
    errors out.

Partially resolves TF-1211: add the main canonicalization loop.

To incrementally stage changes, derivative functions are currently created
with empty bodies that fatal error with a nice message.

Derivative emitters will be upstreamed separately.
2020-04-02 15:43:57 -07:00
marcrasi
025cb9a501 autodiff builtins (#30624)
Define type signatures and SILGen for the following builtins:

```
/// Applies the {jvp|vjp} of `f` to `arg1`, ..., `argN`.
func applyDerivative_arityN_{jvp|vjp}(f, arg1, ..., argN) -> jvp/vjp return type

/// Applies the transpose of `f` to `arg`.
func applyTranspose_arityN(f, arg) -> transpose return type

/// Makes a differentiable function from the given `original`, `jvp`, and
/// `vjp` functions.
func differentiableFunction_arityN(original, jvp, vjp)

/// Makes a linear function from the given `original` and `transpose` functions.
func linearFunction_arityN(original, transpose)
```

Add SILGen FileCheck tests for all builtins.
2020-03-25 02:36:42 -07:00
Dan Zheng
603db8c954 [AutoDiff upstream] Add @differentiable function IRGen.
Lower `@differentiable` and `@differentiable(linear)` functions as structs of
function pointers.
2020-03-22 23:52:28 -07:00
Dan Zheng
11551e13d0 [AutoDiff] NFC: formatting. (#30573)
Run `clang-format` on changes in https://github.com/apple/swift/pull/30564.
2020-03-22 21:30:33 -07:00
Dan Zheng
723b2d2cbe [AutoDiff upstream] Add derivative function witness/vtable entry SILGen. (#30569)
`@differentiable` attribute on protocol requirements and non-final class
members now produces derivative function entries in witness tables and vtables.

This enables `witness_method` and `class_method` differentiation.

Existing type-checking rules:

- Witness declarations of `@differentiable` protocol requirements must have a
  `@differentiable` attribute with the same configuration (or a configuration
  with superset parameter indices).
  - Witness table derivative function entries are SILGen'd for `@differentiable`
    witness declarations.

- Class vtable derivative function entries are SILGen'd for non-final
  `@differentiable` class members.
  - These derivative entries can be overridden or inherited, just like other
    vtable entries.

Resolves TF-1212.
2020-03-22 16:59:01 -07:00
Dan Zheng
aab622e913 [AutoDiff upstream] Add derivative function SILDeclRefs. (#30564)
`@differentiable` attribute on protocol requirements and non-final class members
will produce derivative function entries in witness tables and vtables.

This patch adds an optional derivative function configuration
(`AutoDiffDerivativeFunctionIdentifier`) to `SILDeclRef` to represent these
derivative function entries.

Derivative function configurations consist of:
- A derivative function kind (JVP or VJP).
- Differentiability parameter indices.

Resolves TF-1209.
Enables TF-1212: upstream derivative function entries in witness tables/vtables.
2020-03-22 11:50:29 -07:00
Dan Zheng
24445dd2e2 [AutoDiff upstream] Add differentiability witness SILGen. (#30545)
Generate SIL differentiability witnesses from `@differentiable` and
`@derivative` declaration attributes.

Add SILGen utilities for:
- Emiting differentiability witnesses.
- Creating derivative function thunks, which are used as entries in
  differentiability witnesses.

When users register a custom derivative function, it is necessary to create a
thunk with the expected derivative type computed from the original function's
type. This is important for consistent typing and consistent differentiability
witness entry mangling.

See `SILGenModule::getOrCreateCustomDerivativeThunk` documentation for details.

Resolves TF-1138.
2020-03-21 02:05:04 -07:00
Dan Zheng
697c722a5f [AutoDiff] Type-checking support for inout parameter differentiation. (#29959)
Semantically, an `inout` parameter is both a parameter and a result.

`@differentiable` and `@derivative` attributes now support original functions
with one "semantic result": either a formal result or an `inout` parameter.

Derivative typing rules for functions with `inout` parameters are now defined.

The differential/pullback type of a function with `inout` differentiability
parameters also has `inout` parameters. This is ideal for performance.

Differential typing rules:
- Case 1: original function has no `inout` parameters.
  - Original:     `(T0, T1, ...) -> R`
  - Differential: `(T0.Tan, T1.Tan, ...) -> R.Tan`
- Case 2: original function has a non-wrt `inout` parameter.
  - Original:     `(T0, inout T1, ...) -> Void`
  - Differential: `(T0.Tan, ...) -> T1.Tan`
- Case 3: original function has a wrt `inout` parameter.
  - Original:     `(T0, inout T1, ...) -> Void`
  - Differential: `(T0.Tan, inout T1.Tan, ...) -> Void`

Pullback typing rules:
- Case 1: original function has no `inout` parameters.
  - Original: `(T0, T1, ...) -> R`
  - Pullback: `R.Tan -> (T0.Tan, T1.Tan, ...)`
- Case 2: original function has a non-wrt `inout` parameter.
  - Original: `(T0, inout T1, ...) -> Void`
  - Pullback: `(T1.Tan) -> (T0.Tan, ...)`
- Case 3: original function has a wrt `inout` parameter.
  - Original: `(T0, inout T1, ...) -> Void`
  - Pullback: `(inout T1.Tan) -> (T0.Tan, ...)`

Resolves TF-1164.
2020-02-21 09:47:53 -08:00
Dan Zheng
d7ab0c1547 [AutoDiff] Fix "'alignof' to an incomplete type" error in AutoDiff.h. (#29983)
Using `DenseMap<SILAutoDiffDerivativeFunctionKey, ...>` in a file that includes
AutoDiff.h but not Types.h produced the following error:
```
error: invalid application of 'alignof' to an incomplete type 'swift::SILFunctionType'
```

Fix the error by:
- Including TypeAlignments.h in AutoDiff.h.
- Adding an alignment forward declaration for `SILFunctionType` to TypeAlignments.h.
2020-02-20 22:31:09 -08:00
Dan Zheng
f5b40d6705 [AutoDiff upstream] Add SIL derivative function type caching. (#29953)
Upstream https://github.com/apple/swift/pull/29590:
cache `SILFunctionType::getAutoDiffDerivativeFunctionType` results.
2020-02-20 05:17:39 -08:00
Dan Zheng
a49428ca7c [AutoDiff upstream] Add differentiability_witness_function instruction. (#29765)
The `differentiability_witness_function` instruction looks up a
differentiability witness function (JVP, VJP, or transpose) for a referenced
function via SIL differentiability witnesses.

Add round-trip parsing/serialization and IRGen tests.

Notes:
- Differentiability witnesses for linear functions require more support.
  `differentiability_witness_function [transpose]` instructions do not yet
  have IRGen.
- Nothing currently generates `differentiability_witness_function` instructions.
  The differentiation transform does, but it hasn't been upstreamed yet.

Resolves TF-1141.
2020-02-13 16:55:46 -08:00
Dan Zheng
c2ac96f09f [AutoDiff upstream] Add SIL transpose function type calculation. (#29755)
Add `SILFunctionType::getAutoDiffTransposeFunctionType`.

It computes the transpose `SILFucntionType` for an original `SILFunctionType`,
given:

- Linearity parameter indices
- Transpose function generic signature (optional)
- Other auxiliary parameters

Add doc comments explaining typing rules, preconditions, and other details.
Add `isTranspose` flag to `autodiff::getConstrainedDerivativeGenericSignature`.

Partially resolves TF-1125.
Unblocks TF-1141: upstream `differentiability_witness_function` instruction.
2020-02-11 04:08:25 -08:00
Dan Zheng
849bd62a26 [AutoDiff upstream] Add SIL differentiability witnesses. (#29623)
SIL differentiability witnesses are a new top-level SIL construct mapping
"original" SIL functions to derivative SIL functions.

SIL differentiability witnesses have the following components:
- "Original" `SILFunction`.
- SIL linkage.
- Differentiability parameter indices (`IndexSubset`).
- Differentiability result indices (`IndexSubset`).
- Derivative `GenericSignature` representing differentiability generic
  requirements (optional).
- JVP derivative `SILFunction` (optional).
- VJP derivative `SILFunction` (optional).
- "Is serialized?" bit.

This patch adds the `SILDifferentiabilityWitness` data structure, with
documentation, parsing, and printing.

Resolves TF-911.

Todos:
- TF-1136: upstream `SILDifferentiabilityWitness` serialization.
- TF-1137: upstream `SILDifferentiabilityWitness` verification.
- TF-1138: upstream `SILDifferentiabilityWitness` SILGen from
  `@differentiable` and `@derivative` attributes.
- TF-20: robust mangling for `SILDifferentiabilityWitness` names.
2020-02-04 12:53:27 -08:00
Dan Zheng
0c0018fb9b [AutoDiff] Improve getConstrainedDerivativeGenericSignature helper. (#29620)
Move `getConstrainedDerivativeGenericSignature` under `autodiff` namespace.
Improve naming and documentation.
2020-02-03 17:40:49 -08:00
Dan Zheng
a98fe74044 [AutoDiff upstream] Add TangentSpace. (#29107)
`TangentSpace` represents the tangent space of a type.

- For `Differentiable`-conforming types:
  - The tangent space is the `TangentVector` associated type.
- For tuple types:
  - The tangent space is a tuple of the elements' tangent space types, for the
    elements that have a tangent space.
- Other types have no tangent space.

`TypeBase::getAutoDiffTangentSpace` gets the tangent space of a type.

`TangentSpace` is used to:
- Compute the derivative function type of a given original function type.
- Compute the type of tangent/adjoint values during automatic differentiation.

Progress towards TF-828: upstream `@differentiable` attribute type-checking.
2020-01-12 12:29:08 -08:00
Dan Zheng
fbfb67a218 [AutoDiff upstream] Define AutoDiffConfig. (#29099)
Define `AutoDiffConfig`: the configuration for a derivative function:
- Parameter indices.
- Result indices.
- Derivative generic signature (optional).

Progress towards TF-828: upstream `@differentiable` attribute type-checking.
2020-01-09 17:10:57 -08:00
Saleem Abdulrasool
dedde46df3 AST: explicitly indicate operator==
This is needed to build with VS2019:

```
swift\include\swift\AST\AutoDiff.h(172): error C2593: 'operator ==' is ambiguous
swift\include\swift\Basic\AnyValue.h(129): note: could be 'bool swift::operator ==(const swift::AnyValue &,const swift::AnyValue &)' [found using argument-dependent lookup]
swift\include\swift\AST\AutoDiff.h(172): note: or       'built-in C++ operator==(swift::AutoDiffDerivativeFunctionKind::innerty, swift::AutoDiffDerivativeFunctionKind::innerty)'
swift\include\swift\AST\AutoDiff.h(172): note: while trying to match the argument list '(const swift::AutoDiffDerivativeFunctionKind, const swift::AutoDiffDerivativeFunctionKind)'
```
2019-12-12 21:14:27 -08:00
Dan Zheng
bb1052ca3e [AutoDiff upstream] Upstream @derivative attribute type-checking. (#28738)
The `@derivative` attribute registers a function as a derivative of another
function-like declaration: a `func`, `init`, `subscript`, or `var` computed
property declaration.

The `@derivative` attribute also has an optional `wrt:` clause specifying the
parameters that are differentiated "with respect to", i.e. the differentiation
parameters. The differentiation parameters must conform to the `Differentiable`
protocol.

If the `wrt:` clause is unspecified, the differentiation parameters are inferred
to be all parameters that conform to `Differentiable`.

`@derivative` attribute type-checking verifies that the type of the derivative
function declaration is consistent with the type of the referenced original
declaration and the differentiation parameters.

The `@derivative` attribute is gated by the
`-enable-experimental-differentiable-programming` flag.

Resolves TF-829.
2019-12-12 18:18:18 -08:00
Dan Zheng
0585eb0e90 [AutoDiff upstream] Add @derivative(of:) attribute. (#28321)
The `@derivative(of:)` attribute registers a function as a derivative of another
function. This patch adds the `@derivative(of:)` attribute definition, syntax,
parsing, and printing.

Resolves TF-826.

Todos:
- Type-checking (TF-829).
- Serialization (TF-837).
2019-12-10 09:29:43 -08:00
Marc Rasi
6413f4341a [AutoDiff upstream] AST bits for @differentiable fn ty 2019-11-12 15:19:03 -08:00
Gogul Balakrishnan
5accda22b2 [AutoDiff upstream] Introduce @differentiable attribute to mark functions as differentiable. (#27506)
This PR introduces `@differentiable` attribute to mark functions as differentiable. This PR only contains changes related to parsing the attribute. Type checking and other changes will be added in subsequent patches.

See https://github.com/apple/swift/pull/27506/files#diff-f3216f4188fd5ed34e1007e5a9c2490f for examples and tests for the new attribute.
2019-11-11 13:58:34 -08:00