Commit Graph

676 Commits

Author SHA1 Message Date
Anton Korobeynikov
f5cce4784f Make autdiff more robust in presence of unreachable blocks (#71356)
Unreachable blocks possess some challenges to autodiff since in reverse pass (pullback generation) we need to execute the function backwards, pushing the values from return BB back to entry block. As a result, unreachable blocks might become reachable from the return BB and this might cause all kind of issues.
2024-02-03 08:33:36 -08:00
Slava Pestov
8db0af48bd Merge pull request #71352 from slavapestov/remove-redundant-requirements
Remove -warn-redundant-requirements flag
2024-02-03 08:28:02 -05:00
Slava Pestov
ea15d9f9b2 Stop passing -warn-redundant-requirements in tests 2024-02-02 14:57:19 -05:00
Kavon Farvardin
b8a04f63e7 Test: prefer -enable-builtin-module
Many tests that use `-parse-stdlib` only do so because they want access
to the Builtin module. Now that we have the flag and ability to import
it, use that instead.
2024-02-01 10:39:02 -08:00
Slava Pestov
28f26216ee Sema: Refactor evaluateMembersRequest() to not call TypeChecker::checkConformance() 2024-01-31 21:56:57 -05:00
Erik Eckstein
c89df9ec98 Mandatory optimizations: constant fold boolean literals before the DefiniteInitialization pass
Add a new mandatory BooleanLiteralFolding pass which constant folds conditional branches with boolean literals as operands.

```
  %1 = integer_literal -1
  %2 = apply %bool_init(%1)   // Bool.init(_builtinBooleanLiteral:)
  %3 = struct_extract %2, #Bool._value
  cond_br %3, bb1, bb2
```
->
```
  ...
  br bb1
```

This pass is intended to run before DefiniteInitialization, where mandatory inlining and constant folding didn't run, yet (which would perform this kind of optimization).
This optimization is required to let DefiniteInitialization handle boolean literals correctly.
For example in infinite loops:

```
   init() {
     while true {           // DI need to know that there is no loop exit from this while-statement
       if some_condition {
         member_field = init_value
         break
       }
     }
   }
```
2024-01-10 16:15:57 +01:00
Jaap Wijnen
dfe1e691a8 [AutoDiff] Add missing vjp, jvp functions to existing FloatingPoint initializers (#70688)
Adds derivatives to already existing initializers that allow converting between floating point type. For example converting a Float to a Double.

Co-authored-by: Jaap Wijnen <jaap@passivelogic.com>
2024-01-05 13:29:04 -08:00
nate-chandler
680c737ddb Merge pull request #64789 from nate-chandler/more-move-values
[SILGen] Used move_value for more lexical values.
2023-12-15 07:07:54 -08:00
Nate Chandler
10ce0c6b16 [SILGen] Used move_value for lexical lets.
Instead of using begin_borrow [lexical] + copy_value.
2023-12-14 13:35:26 -08:00
Meghana Gupta
e685b24481 [NFC] Update AutoDiff test 2023-12-06 08:29:50 -08:00
Meghana Gupta
86b651330b Revert "Merge pull request #69807 from apple/revert-69450-uninarrayfix"
This reverts commit cabb5e109f, reversing
changes made to 09688abb02.
2023-12-06 08:29:50 -08:00
nate-chandler
126022f6e9 Merge pull request #70054 from nate-chandler/rdar118059326
[SIL] Key consume checking off var_decl attr.
2023-11-28 11:47:04 -08:00
Nate Chandler
9bb0187be1 [SILGen] Add begin_borrow [var_decl] lifetimes. 2023-11-28 07:26:09 -08:00
Kshitij
97a5a83ae6 [sil-optimizer] Add FP comparison support in constant folder 2023-11-27 11:32:28 -08:00
Mishal Shah
e8de333daf Revert "Add a mark_dependence while emitting SIL for uninitialized array allocation " 2023-11-12 09:43:13 -08:00
Meghana Gupta
192bb2eed2 Merge pull request #69450 from meg-gupta/uninarrayfix
Add a mark_dependence while emitting SIL for uninitialized array allocation
2023-10-31 22:07:14 -07:00
Meghana Gupta
baebc7d00b Handle mark_dependence in Differentiation 2023-10-31 11:07:36 -07:00
Kshitij
12e3a6ecfb [AutoDiff] Modify inlining logic to award inlining benefits to VJPs
Similar to #69029 but for VJPs.
2023-10-27 06:43:59 -10:00
finagolfin
75bfa4422a [android][test] Fix five tests that are failing on the community Android CI (#69189)
Update the Android doc with info about the latest LTS NDK not working.
2023-10-16 10:44:56 -07:00
eeckstein
0ada2e2cac Merge pull request #69029 from jkshtj/main
[Autodiff] Modify inliner logic to award inlining benefits to linear …
2023-10-12 18:38:25 +02:00
Kshitij
f973aa1423 [Autodiff] Modify inliner logic to award inlining benefits to linear maps w/ control-flow
For linear maps containing control-flow, closures (representing the pullbacks
of intermediate values) may be passed as arguments, however, they may be
hidden behind a branch-tracing enum (tracing execution flow of the original
function).

Such linear maps did not use to get inlining benefits as the compiler
could not see that the intermediate pullback closures were actually part
of the input.

This change modifies the inliner logic to correctly award inlining
benefits to linear maps containing control-flow, by checking if a
"callee" in the linear map actually traces back to an input closure that
was received as part of a branch-tracing enum input argument.

Fixes #68945
2023-10-08 14:37:13 -07: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
Erik Eckstein
ea36185c88 tests: fix AutoDiff/stdlib/callee_differential_not_leaked_in_func_with_loops.swift for 32 bit architectures
It failed because the constant overflows a signed 32 bit integer.

And sorry, little insects, I didn't mean it that way.
2023-09-27 09:34:10 +02:00
Alex Lorenz
6ecea1ac09 Merge pull request #68481 from hyp/eng/no-nocapture
[IRGen][interop] do not add 'nocapture' to not bitwise takable types
2023-09-26 07:52:05 -07:00
Alex Lorenz
4858cb6225 [IRGen][interop] do not add 'nocapture' to not bitwise takable types
The use of 'nocapture' for parameters and return values is incorrect for C++ types, as they can actually capture a pointer into its own value (e.g. std::string in libstdc++)

rdar://115062687
2023-09-25 17:43:34 -07:00
Andrew Savonichev
2f7b42ceaf [AutoDiff] Handle init_enum_data_addr and inject_enum_addr for Optional (#68300)
Optional's `init_enum_data_addr` and `inject_enum_addr` instructions are generated in presence of non-loadable Optional values. The compiler used to treat these instructions as inactive, and this resulted in silent run-time
issues described in #64223.

The patch marks `init_enum_data_addr` as "active" if its Optional operand is also active, and in PullbackCloner we differentiate through it and the related `inject_enum_addr`.

However, we only determine this relation in simple cases when both instructions are in the same block. There is no def-use relation between them (both take the same Optional operand), so if there is more than one set of instructions
operating on the same Optional, or there is some control flow, we currently bail out.

In PullbackCloner, we walk over instructions in reverse order and start from `inject_enum_addr` and its `Optional<Wrapped>.TangentVector` operand. Assuming that is is already initialized, we emit an `unchecked_take_enum_data_addr` and set it as the adjoint buffer of `init_enum_data_addr`. The Optional value is
invalidated, and we have to destroy the enum data address later when we reach `init_enum_data_addr`.
2023-09-22 01:07:16 -07:00
Anton Korobeynikov
d66cfa916a Fix quite subtle but nasty bug in linear map tuple types computation: (#68413)
We need a lowered type for branch trace enum in order to compute linear map tuple type. However, the lowering of branch trace enum type depends on the types of its elements (the payloads are linear map tuples of predecessor BB).

As lowered types are cached, we cannot populate branch trace enum entries in the end as we did before: we already used wrong lowered types for linear map tuples.

Traverse basic blocks in reverse post-order traverse order building linear map tuples and branch tracing enums in one go, ensuring that we've done with predecessor BBs before processing the BB itself.
2023-09-19 13:24:33 -07:00
Hamish Knight
2f9dbbad9e [test] Require asserts for pullback_generation_nested_addelement_adjoints.swift
It looks like `--debug-only` requires an asserts build
2023-09-13 12:30:03 +01:00
Kshitij Jain
d971f125d9 [AutoDiff] Handle materializing adjoints with non-differentiable fields (#67319) 2023-09-12 14:22:41 -07:00
Becca Royal-Gordon
8770c7f826 Rework ASTDumper (#68438)
This PR refactors the ASTDumper to make it more structured, less mistake-prone, and more amenable to future changes. For example:

```cpp
  // Before:
  void visitUnresolvedDotExpr(UnresolvedDotExpr *E) {
    printCommon(E, "unresolved_dot_expr")
      << " field '" << E->getName() << "'";
    PrintWithColorRAII(OS, ExprModifierColor)
      << " function_ref=" << getFunctionRefKindStr(E->getFunctionRefKind());
    if (E->getBase()) {
      OS << '\n';
      printRec(E->getBase());
    }
    PrintWithColorRAII(OS, ParenthesisColor) << ')';
  }

  // After:
  void visitUnresolvedDotExpr(UnresolvedDotExpr *E, StringRef label) {
    printCommon(E, "unresolved_dot_expr", label);

    printFieldQuoted(E->getName(), "field");
    printField(E->getFunctionRefKind(), "function_ref", ExprModifierColor);

    if (E->getBase()) {
      printRec(E->getBase());
    }

    printFoot();
  }
```

* Values are printed through calls to base class methods, rather than direct access to the underlying `raw_ostream`.
    * These methods tend to reduce the chances of bugs like missing/extra spaces or newlines, too much/too little indentation, etc.
    * More values are quoted, and unprintable/non-ASCII characters in quoted values are escaped before printing.
* Infrastructure to label child nodes now exists.
    * Some weird breaks from the normal "style", like `PatternBindingDecl`'s original and processed initializers, have been brought into line.
* Some types that previously used ad-hoc dumping functions, like conformances and substitution maps, are now structured similarly to the dumper classes.
* I've fixed the odd dumping bug along the way. For example, distributed actors were only marked `actor`, not `distributed actor`.

This PR doesn't change the overall style of AST dumps; they're still pseudo-S-expressions. But the logic that implements this style is now isolated into a relatively small base class, making it feasible to introduce e.g. JSON dumping in the future.
2023-09-11 23:56:38 -07:00
Anton Korobeynikov
118fd86012 Ensure we can fold apply of a differentiable_function_inst. Also fixes one small potential issue while there. (#65605)
Fixes #65489 #67992
2023-09-05 15:22:02 -07:00
Andrew Savonichev
fc640dbc02 [AutoDiff] Emit a diagnostic for non-differentiable active values (#67697)
For some values we cannot compute types for differentiation (for example,
tangent vector type), so it is better to diagnose them earlier. Otherwise we hit
assertions when generating code for such invalid values.

The LIT test is a reduced reproducer from the issue #66996. Before the patch the
compiler crashed while trying to get a tangent vector type for the following
value (partial_apply):

    %54 = function_ref @$s4null1o2ffSdAA1FV_tFSdyKXEfu0_ :
      $@convention(thin) @substituted <τ_0_0> (@inout_aliasable Double)
      -> (@out τ_0_0, @error any Error) for <Double>

    %55 = partial_apply [callee_guaranteed] %54(%2) :
      $@convention(thin) @substituted <τ_0_0> (@inout_aliasable Double)
      -> (@out τ_0_0, @error any Error) for <Double>

Now we emit a diagnostic instead.

The patch resolves issues #66996 and #63331
2023-09-01 10:48:45 -07:00
Kshitij Jain
d5a3e2e630 [AutoDiff] Fixes memory leaks in autodiff linear map context allocation builtins (#67944)
When the differentiating a function containing loops, we allocate a linear map context object on the heap. This context object may store non-trivial objects, such as closures, that need to be released explicitly. Fix the autodiff linear map context allocation builtins to correctly release such objects and not just free the memory they occupy.
2023-08-24 13:57:10 -07:00
Nishith Shah
8e2e625543 [Diagnostics] Use imperative msg for protocol conformance & switch-case fixits
This commit changes fixit messages from a question/suggestion to an
imperative message for protocol conformances and switch-case. Addresses
https://github.com/apple/swift/issues/67510.
2023-08-13 22:34:26 -07:00
Andrew Trick
61c12e4be0 Fix LoadableByAddress to use @in_guaranteed for unowned values
LoadableByAddress was accidentally changing ownership of
direct_unowned values to @in (owned). This generates unsupported SIL
for on-stack partial applies, which now breaks SIL verification.

This also resulted in extra copies of values inside of closure
contexts. Before calling the original function, the value would need to
be copied onto the stack and the context would be destroyed. Now, we
simply pass a pointer directly from the closure context.  See
IRGen/indirect_argument.sil+huge_partial_application.

I'm pretty sure fixing this has no effect on the mangling of public symbols.
2023-08-12 21:21:18 -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
Nate Chandler
e5d87f75a8 [SIL] Add source formal type to checked_cast_br.
It is necessary for opaque values where for casts that will newly start
out as checked_cast_brs and be lowered to checked_cast_addr_brs, since
the latter has the source formal type, IRGen relies on being able to
access it, and there's no way in general to obtain the source formal
type from the source lowered type.
2023-07-27 15:04:15 -07:00
Andrew Savonichev
5abb580b3d [AutoDiff] Fix return type of subset parameters thunk function (#67487)
The patch resolves #67402.

When the original function has a tuple result type, we should append
thunkedLinearMap as the last element of the tuple to match the function
declaration. Before this patch, the compiler used to wrap the original result
tuple and thunkedLinearMap into another tuple, and caused the verifier error.

Before the patch:

  return %{{.*}} : $((Float, Double), @callee_guaranteed (Float) -> X.TangentVector)

After the patch:

  return %{{.*}} : $(Float, Double, @callee_guaranteed (Float) -> X.TangentVector)
2023-07-25 11:36:00 -07:00
Becca Royal-Gordon
b4855aee1f Adopt ValueDecl in autodiff diagnostics 2023-07-19 13:08:12 -07:00
Kshitij Jain
8b73c98286 Fixes https://github.com/apple/swift/issues/59100 (#67162)
The above referenced issue was causing a compiler crash when writing
differentiable protocols and corresponding implementers, without importing
the `_Differentiation` module.

Changes in this CR fix the issue by marking any `@differentiable`
attributes as invalid, if the `_Differentiation` module has not been
imported. This ignores the `@differentiable` attributes when the
protocol witnesses are being verified. Witness verification was previously
leading to an error (due to missing `@differentiable` attribute on the protocol
requirement implementer), and the corresponding diagnostic emission code was
then leading to a crash, because it was expecting the `_Differentiation`
module to be present.
2023-07-07 07:32:55 -05: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
Andrew Savonichev
b6acb6fbef [AutoDiff] Check @noDerivative for function type comparison (#67121)
As described in the issue #62922, the compiler should not allow to discard @noDerivative attribute and keep @differentiable. The patch adds a diagnostic for this case.

Resolves #62922.
2023-07-06 15:21:30 -07:00
Arnold Schwaighofer
fc766a39d3 Fix some more tests 2023-06-29 16:16:56 -07:00
Arnold Schwaighofer
0b6db0afc4 Fix test/AutoDiff directory 2023-06-20 12:47:56 -07:00
Arnold Schwaighofer
c1a93e0bde Move tests over to use the %use_no_opaque_pointers option 2023-06-14 10:49:48 -07:00
Anton Korobeynikov
0b7d8ab78c [AutoDiff] Remove 'readnone' attribute from autoDiffCreateLinearMapContext. (#66203)
It certainly has side effects and returned value every time is different.
This way we ensure multiple calls are not CSE'd or LICM'ed.

Fixes #65989
2023-05-29 23:56:33 -07:00
Mishal Shah
a0fe8c2f26 Disable differentiable_protocol_requirements.swift 2023-05-18 11:27:09 -07:00
Nate Chandler
594e690a00 [Test] Added new redundancy warnings.
Now that `InferredGenericSignatureRequest` creates
`StructuralRequirement`s from of the generic signature with valid source
locations, additional redundancy warnings are produced.  Update tests
with the new warnings.
2023-05-17 15:16:23 -07:00
Erik Eckstein
82734b6ac2 Swift Optimizer: simplification for apply, try_apply, begin_apply and partial_apply
* move the apply of partial_apply transformation from simplify-apply to simplify-partial_apply
* delete dead partial_apply instructions
* devirtualize apply, try_apply and begin_apply
2023-05-11 08:11:44 +02:00
Yuta Saito
c349d9aa23 Merge pull request #65530 from kateinoigakukun/katei/pr-repair-wasm-ci
[WebAssembly][Test] Disable some tests to make the CI green.
2023-05-03 23:12:40 +09:00