Commit Graph

100 Commits

Author SHA1 Message Date
Anton Korobeynikov
07ccee2b76 Remove stale debug code. (#64325) 2023-03-13 15:14:16 -07:00
Anton Korobeynikov
869fc1792e [AutoDiff] Ensure autodiff code does not ignore getSingleTerminatorOperands return value (#64200)
Also extend activity analysis to handle `try_apply` normal result properly. Add testcase from #63728
2023-03-08 10:10:22 -08:00
Anton Korobeynikov
9c227626b8 Enable propagation of @differentiable attribute from storage declarations to setters. (#63988)
Fixes #63169 and TF-129
2023-03-06 07:57:19 -08:00
Anton Korobeynikov
11de73639c [AutoDiff] Unwrap the top level of linear map tuple when it is possible (#63770)
This essentially passes the members of a linear map tuple as individual arguments. It yields few nice simplifications:

 * No linear map tuples at all for getters / setters
 * No tuple formation / deconstruction around pullbacks
 * Pullbacks with loops still use heap-allocated tuples
2023-02-19 18:46:49 -08:00
Anton Korobeynikov
d2e022d5b4 Remove linear map structs and use plain tuples instead. (#63444)
The changes are intentionally were made close to the original implementation w/o possible simplifications to ease the review

Fixes #63207, supersedes #63379 (and fixes #63234)
2023-02-08 07:42:54 -08:00
Anton Korobeynikov
6d657c90af [AutoDiff] Refine debug info emitted for adjoint buffers (#62779)
Single input variable might yield multiple adjoint buffers if control flow is involved. Therefore we cannot simply transfer debug info  from the input variable: it will be invalid as we will end with multiple locations for a single "source" variable, and, even worse, might end with conflicting debug info as different buffers might be optimized
differently.

We do:
  - Drop input argument number. This must be unique and we're not
  - Correct variable name
2023-01-06 14:34:16 -08:00
Erik Eckstein
ab1b343dad use new llvm::Optional API
`getValue` -> `value`
`getValueOr` -> `value_or`
`hasValue` -> `has_value`
`map` -> `transform`

The old API will be deprecated in the rebranch.
To avoid merge conflicts, use the new API already in the main branch.

rdar://102362022
2022-11-21 19:44:24 +01:00
Nate Chandler
ed623d7b64 [NFC] Shortened SIL [init] flag.
Instead of writing out [initalization] for some instructions, use [init]
everywhere.
2022-10-27 10:38:54 -07:00
Anton Korobeynikov
b926c18f9a Fix adjoint generation of store_borrow (#61431)
Apparently #60467 changed the semantics of store_borrow as it started to produce a value. This change was not documented in SIL spec and not all places were updated to new semantics.

Now the adjoint of store_borrow should be generated for the value of instruction itself, not the destination address
2022-10-05 04:06:57 -07:00
Josh Soref
730b16c569 Spelling siloptimizer
* access
* accessed
* accesses
* accessor
* acquiring
* across
* activated
* additive
* address
* addresses'
* aggregated
* analysis
* and
* appropriately
* archetype
* argument
* associated
* availability
* barriers
* because
* been
* beginning
* belongs
* beneficial
* blocks
* borrow
* builtin
* cannot
* canonical
* canonicalize
* clazz
* cleanup
* coalesceable
* coalesced
* comparisons
* completely
* component
* computed
* concrete
* conjunction
* conservatively
* constituent
* construct
* consuming
* containing
* covered
* creates
* critical
* dataflow
* declaration
* defined
* defining
* definition
* deinitialization
* deliberately
* dependencies
* dependent
* deserialized
* destroy
* deterministic
* deterministically
* devirtualizes
* diagnostic
* diagnostics
* differentiation
* disable
* discipline
* dominate
* dominates
* don't
* element
* eliminate
* eliminating
* elimination
* embedded
* encounter
* epilogue
* epsilon
* escape
* escaping
* essential
* evaluating
* evaluation
* evaluator
* executing
* existential
* existentials
* explicit
* expression
* extended
* extension
* extract
* for
* from
* function
* generic
* guarantee
* guaranteed
* happened
* heuristic
* however
* identifiable
* immediately
* implementation
* improper
* include
* infinite
* initialize
* initialized
* initializer
* inside
* instruction
* interference
* interferes
* interleaved
* internal
* intersection
* intractable
* intrinsic
* invalidates
* irreducible
* irrelevant
* language
* lifetime
* literal
* looks
* materialize
* meaning
* mergeable
* might
* mimics
* modification
* modifies
* multiple
* mutating
* necessarily
* necessary
* needsmultiplecopies
* nonetheless
* nothing
* occurred
* occurs
* optimization
* optimizing
* original
* outside
* overflow
* overlapping
* overridden
* owned
* ownership
* parallel
* parameter
* paths
* patterns
* pipeline
* plottable
* possible
* potentially
* practically
* preamble
* precede
* preceding
* predecessor
* preferable
* preparation
* probably
* projection
* properties
* property
* protocol
* reabstraction
* reachable
* recognized
* recursive
* recursively
* redundant
* reentrancy
* referenced
* registry
* reinitialization
* reload
* represent
* requires
* response
* responsible
* retrieving
* returned
* returning
* returns
* rewriting
* rewritten
* sample
* scenarios
* scope
* should
* sideeffects
* similar
* simplify
* simplifycfg
* somewhat
* spaghetti
* specialization
* specializations
* specialized
* specially
* statistically
* substitute
* substitution
* succeeds
* successful
* successfully
* successor
* superfluous
* surprisingly
* suspension
* swift
* targeted
* that
* that our
* the
* therefore
* this
* those
* threshold
* through
* transform
* transformation
* truncated
* ultimate
* unchecked
* uninitialized
* unlikely
* unmanaged
* unoptimized key
* updataflow
* usefulness
* utilities
* villain
* whenever
* writes

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>
2022-10-03 18:31:33 -04:00
Anthony Latsis
2843e0c871 Gardening: Migrate compiler sources to GitHub issues 2022-09-29 23:58:55 +03:00
Slava Pestov
9d96ed940f AST: Rename 'canonical wrt. generic signature' to 'reduced'
We had two notions of canonical types, one is the structural property
where it doesn't contain sugared types, the other one where it does
not contain reducible type parameters with respect to a generic
signature.

Rename the second one to a 'reduced type'.
2022-08-09 12:46:31 -04:00
Michael Gottesman
1e6187c4f4 [sil] Update all usages of old API SILValue::getOwnershipKind() in favor of new ValueBase::getOwnershipKind().
Andy some time ago already created the new API but didn't go through and update
the old occurences. I did that in this PR and then deprecated the old API. The
tree is clean, so I could just remove it, but I decided to be nicer to
downstream people by deprecating it first.
2022-07-26 11:46:23 -07:00
Anton Korobeynikov
11dd84e4b0 [AutoDiff] Ensure adjoint buffer of unchecked_take_enum_data_addr is zeroed after value is accumulated (#58457)
This is yet another optional-related bug. It could be triggered if `unchecked_take_enum_data_addr` is inside a loop. In such case the accumulated value of adjoint buffer would be re-used in the subsequent loop iterations producing wrong results.

Fixes #58353 (SR16094)
2022-04-27 12:03:15 -07:00
Anton Korobeynikov
d52dddc7c8 [AutoDiff] Fix adjoint propagation for active bb address arguments (#42393)
Fix adjoint propagation for active bb address arguments: ensure they are accumulated in the proper buffer.

Fixes second case of SR-16094
2022-04-16 14:12:25 -07:00
Anton Korobeynikov
4b7baf000c [AutoDiff] Properly collect inout parameter adjoints (#41559)
Apparently, the parameter index calculation in #37861 was not always correct in presence of other pullback parameters (e.g. captures and non-differentiated args). Collect all inout parameters and collect inout parameter adjoints correctly.

Resolves SR-15891
2022-02-25 14:09:59 -08:00
Philip Turner
78e580f8d3 Update PullbackCloner.cpp 2022-01-18 13:36:31 -05:00
Robert Widmann
e545d7f760 Lift getCanonicalTypeInContext up to GenericSignature 2021-09-20 15:43:07 -07:00
Min-Yih Hsu
343d842394 [SIL][DebugInfo] PATCH 3/3: Deprecate debug_value_addr SIL instruciton
This patch removes all references to DebugValueAddrInst class and
debug_value_addr instruction in textual SIL files.
2021-08-31 12:01:04 -07:00
Brad Larson
0f884b8b82 [AutoDiff] [SR-14218] Correctly propagate tangent vectors of inout parameters from functions with multiple basic blocks (#37861)
* Attempt at a patch for SR-14053 and SR-14218, based on Dan Zheng's initial fix.

* Incorporated Dan's cleanup suggestions.

* Converting a bool SmallVector to a SmallBitVector.

* Testing if Windows issues with this test are due to runtime support.

* Simplifying test case.
2021-06-24 08:03:14 -05:00
Pavel Prokofyev
f8baffafc8 [NFC][AutoDiff] Pass AutoDiffConfig by const ref. (#37074) 2021-04-27 13:40:18 -07:00
Richard Wei
7e2d23896f Merge pull request #36974 from integralpro/SR-14290
[AutoDiff] Use correct debug scope for pullback trampoline block.
2021-04-21 01:02:05 -07:00
Pavel Prokofyev
841618ea70 [AutoDiff] Use correct debug scope for pullback trampoline block.
Fixes:
[[SR-14290]: SIL verification fails when differentiating a function of [[Double]]](rdar://74876596)
[[SR-14298]: [AutoDiff] SIL verification failed: non-contiguous lexical scope at -Onone](rdar://75032457)
2021-04-20 12:10:54 -07:00
Azoy
9ed732f0ab Introduce isDecl and getDeclType
fix enum logic issue

fix tests

guard against null types
2021-04-20 02:22:16 -04:00
Slava Pestov
7ccc41a7b7 SIL: Preliminary support for 'apply [noasync]' calls
Refactor SILGen's ApplyOptions into an OptionSet, add a
DoesNotAwait flag to go with DoesNotThrow, and sink it
all down into SILInstruction.h.

Then, replace the isNonThrowing() flag in ApplyInst and
BeginApplyInst with getApplyOptions(), and plumb it
through to TryApplyInst as well.

Set the flag when SILGen emits a sync call to a reasync
function.

When set, this disables the SIL verifier check against
calling async functions from sync functions.

Finally, this allows us to add end-to-end tests for
rdar://problem/71098795.
2021-03-04 22:41:46 -05:00
Richard Wei
e3b480b0c9 [AutoDiff] Enable variable debugging support for pullback functions.
- Properly clone and use debug scopes for all instructions in pullback functions.
- Emit `debug_value` instructions for adjoint values.
- Add debug locations and variable info to adjoint buffer allocations.
- Add `TangentBuilder` (a `SILBuilder` subclass) to unify and simplify special emitter utilities for tangent vector code generation. More simplifications to come.

Pullback variable inspection example:
```console
(lldb) n
Process 50984 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = step over
    frame #0: 0x0000000100003497 main`pullback of foo(x=0) at main.swift:12:11
   9   	import _Differentiation
   10
   11  	func foo(_ x: Float) -> Float {
-> 12  	  let y = sin(x)
   13  	  let z = cos(y)
   14  	  let k = tanh(z) + cos(y)
   15  	  return k
Target 0: (main) stopped.
(lldb) fr v
(Float) x = 0
(Float) k = 1
(Float) z = 0.495846391
(Float) y = -0.689988375
```

Resolves rdar://68616528 / SR-13535.
2021-02-21 19:00:07 -05:00
Richard Wei
8d8614058b [AudoDiff] NFC: Replace 'SILAutoDiffIndices' with 'AutoDiffConfig'. (#35079)
Resolve rdar://71678394 / SR-13889.
2020-12-14 14:32:40 -08:00
Michael Gottesman
b13a8e9ba3 Merge pull request #34915 from gottesmm/forwarding-silinstruction
[ownership] Centralize all info about SILInstruction forwarding in the SILInstruction class hierarchy itself.
2020-12-01 21:33:27 -08:00
Michael Gottesman
8d479f1ff6 [autodiff] Change getTangentStoredProperty() to use a Projection instead of FieldIndexCacheBase.
This is NFCI.

THis is in preparation for making FieldIndexCacheBase a templated subclass.
2020-11-30 18:16:11 -08:00
Richard Wei
de2dbe57ed [AutoDiff] Bump-pointer allocate pullback structs in loops. (#34886)
In derivatives of loops, no longer allocate boxes for indirect case payloads. Instead, use a custom pullback context in the runtime which contains a bump-pointer allocator.

When a function contains a differentiated loop, the closure context is a `Builtin.NativeObject`, which contains a `swift::AutoDiffLinearMapContext` and a tail-allocated top-level linear map struct (which represents the linear map struct that was previously directly partial-applied into the pullback). In branching trace enums, the payloads of previously indirect cases will be allocated by `swift::AutoDiffLinearMapContext::allocate` and stored as a `Builtin.RawPointer`.
2020-11-30 15:49:38 -08:00
Michael Gottesman
25ebb5d763 [autodiff] When asserts are enabled, verify all autodiff compiler generated functions.
This ensures that any invalid SIL generated by these cloners is caught
immediately at the source when asserts are enabled improving productivity.
2020-11-29 23:44:31 -08:00
Richard Wei
35aa99bc1a [AutoDiff] Fix crasher on property getter in library evolution mode. (#34777)
`SILBuilder::createAllocStack` expects a debug variable when the location is a `VarDecl`. Since we are in pullbacks, there's no debug variables so we pass an empty one.

General support for debug-info-in-pullbacks will be added as part of SR-13535.

Also add a negative test for SR-13866.

Resolves SR-13865.
2020-11-17 14:35:19 -08:00
Michael Gottesman
c026e95cce [ownership] Extract out SILOwnershipKind from ValueOwnershipKind into its own type and rename Invalid -> Any.
This makes it easier to understand conceptually why a ValueOwnershipKind with
Any ownership is invalid and also allowed me to explicitly document the lattice
that relates ownership constraints/value ownership kinds.
2020-11-10 14:29:11 -08:00
Robert Widmann
6125d25cb4 [NFC] Silence Non-Exhaustive Switch Warnings on Windows 2020-10-14 13:26:09 -07:00
Andrew Trick
5ae231eaab Rename getFieldNo() to getFieldIndex().
Do I really need to justify this?
2020-09-24 22:44:13 -07:00
Dan Zheng
8d336a36ef [AutoDiff] NFC: gardening. (#33914) 2020-09-11 13:00:25 -07:00
Dan Zheng
5c3cb36a7c Merge pull request #33611 from dan-zheng/autodiff-fix-tangent-value-category
[AutoDiff] Fix PullbackCloner tangent value category mismatch issues.
2020-09-03 11:51:56 -07:00
Dan Zheng
7462c83a2a Change getAdjointBuffer to return SILValue instead of SILValue &.
Fixes a use-after-free crash.
2020-09-02 15:06:27 -07:00
Dan Zheng
ee8ad7bb8b [AutoDiff] NFC: silence no-asserts unused variable warning. (#33629) 2020-08-25 12:54:55 -07:00
Dan Zheng
48c048f34d [AutoDiff] Fix PullbackCloner tangent value category mismatch issues.
Fix SIL pullback function type calculation: remap original `unowned` results to
the correct pullback parameter convention depending on the `TangentVector` type
lowering.

Make `PullbackCloner` visitors for the following instructions check and handle
tangent value categories: `struct`, `struct_extract`, `tuple`, `destructure_tuple`.

Add differentiation tests for `Optional` struct and class stored properties,
exercising the instruction visitors above.

Resolves SR-13430.
2020-08-24 10:39:23 -07:00
Alex Efremov
a434ee8598 [AutoDiff] Fix PullbackCloner tangent value category mismatch crash (#33512)
Fix semantic member getter pullback generation crash due to tangent value category mismatch.

Resolves SR-13411.
2020-08-17 18:31:12 -07:00
Alex Efremov
40c448514a [AutoDiff] Support differentiation of non-active try_apply. (#33483)
Add differentiation support for non-active `try_apply` SIL instructions.

Notable pullback generation changes:
* Original basic blocks are now visited in a different order:
* starting from the original basic block, all its predecessors
* are visited in a breadth-first search order. This ensures that
* all successors of any block are visited before the block itself.

Resolves TF-433.
2020-08-15 10:22:28 -07:00
Dan Zheng
4391f4264e [AutoDiff] Fix Optional differentiation crash. (#33386)
Fix `Optional` differentiation crash for non-resilient `Wrapped` reference type.
Add `NonresilientTracked` type to `DifferentiationUnittest` for testing.

Resolves SR-13377.
2020-08-11 09:14:12 -07:00
Alex Efremov
ccca08b7f7 [AutoDiff] Add reverse-mode switch_enum support for Optional. (#33218)
Pullback generation now supports `switch_enum` and `switch_enum_addr`
instructions for `Optional`-typed operands.

Currently, the logic is special-cased to `Optional`, but may be generalized in
the future to support enums following general rules.
2020-08-07 17:56:15 -07:00
Dan Zheng
6d47061622 [AutoDiff] NFC: fix typo. (#33361) 2020-08-07 13:13:36 -07:00
Slava Pestov
0ef12ec8aa SIL: Replace some calls to getDeclaredType() with getDeclaredInterfaceType() 2020-07-31 13:39:02 -04:00
Dan Zheng
9fe0ed24be [AutoDiff] Fix class differentiation. (#33151)
Fix pullback generation for `unchecked_ref_cast` and `upcast` instructions
for class types with an address tangent value category.

Upstream end-to-end class differentiation tests.
2020-07-30 11:22:42 -07:00
Dan Zheng
df830bc120 [AutoDiff] NFC: Reimplement VJPCloner using pimpl pattern.
`VJPCloner.h` is now tiny: `VJPCloner` exposes only a `bool run()` entry point.

All of the implementation is moved to `VJPCloner::Implementation` in
`VJPCloner.cpp`. Methods can be defined directly in `VJPCloner.cpp` without
separate declarations.
2020-07-10 13:16:44 -07:00
Dan Zheng
7fccbadce4 [AutoDiff] NFC: Reimplement PullbackCloner using pimpl pattern. (#32778)
Reimplement `PullbackCloner` using the pointer-to-implementation pattern.

`PullbackCloner.h` is now tiny: `PullbackCloner` exposes only a `bool run()`
entry point.

All of the implementation is moved to `PullbackCloner::Implementation` in
`PullbackCloner.cpp`.

Benefits of this approach:

- A main benefit is that methods can be defined directly in `PullbackCloner.cpp`
  without needing to separately declare them in `PullbackCloner.h`.
  - There is now no code duplication between `PullbackCloner.h` and
    `PullbackCloner.cpp`.
  - Consequently, method documentation is easier to read because it appears
    directly on method definitions, instead of on method declarations in a
    separate file. This is important for documentation of `PullbackCloner`
    instruction visitor methods, which explain pullback transformation rules.
- Incremental recompilation may be faster since `PullbackCloner.h` changes less
  often.

Partially resolves SR-13182.
2020-07-09 07:18:14 -07:00
Dan Zheng
ec5da7427b [AutoDiff] NFC: garden differentiation transform. (#32770)
Rename "emitters" to "cloners", for consistency:
- `JVPEmitter` -> `JVPCloner`
- `VJPEmitter` -> `VJPCloner`
- `PullbackEmitter` -> `PullbackCloner`

Improve `PullbackCloner` documentation.
- Document previously undocumented methods.
- Update outdated documentation.
  - For adjoint value accumulation helpers: rename "buffer access" occurrences to
    "address". Pullback generation no logner uses buffer accesses (`begin_apply`).
2020-07-08 19:26:36 -07:00