Commit Graph

227 Commits

Author SHA1 Message Date
Slava Pestov
5c5f01269f AST: Add withUnsafe[Throwing]Continuation built-ins
These lower as follows, where %fn is the passed-in function
value:

    %c = get_async_continuation_addr ...
    apply %fn(%c)
    await_async_continuation %c
2020-12-01 20:05:17 -05:00
Erik Eckstein
326e578bed [concurrency] SILGen: allow the Builtin.createAsyncTaskFuture to have a non-generic closure argument.
It fixes a crash in SILGen if Builtin.createAsyncTaskFuture is used in a non-generic context.
I found this by experiment - we don't use it currently in the stdlib. But it doesn't harm to fix this.
2020-12-01 08:42:56 +01: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
Doug Gregor
dab6fb7098 [Concurrency] Implement SIL generation for "async let".
Implement SIL generation for "async let" constructs, which involves:

1. Creating a child task future at the point of declaration of the "async let",
which runs the initializer in an async closure.
2. Entering a cleanup to destroy the child task.
3. Entering a cleanup to cancel the child task.
4. Waiting for the child task when any of the variables is reference.
5. Decomposing the result of the child task to write the results into the
appropriate variables.

Implements rdar://71123479.
2020-11-27 22:50:39 -08:00
Doug Gregor
069dfad638 [Concurrency] Add Builtin.createAsyncTaskFuture.
This new builtin allows the creation of a "future" task, which calls
down to swift_task_create_future to actually form the task.
2020-11-15 22:37:13 -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
Doug Gregor
4c2c2f32e9 [Concurrency] Implement a builtin createAsyncTask() to create a new task.
`Builtin.createAsyncTask` takes flags, an optional parent task, and an
async/throwing function to execute, and passes it along to the
`swift_task_create_f` entry point to create a new (potentially child)
task, returning the new task and its initial context.
2020-11-07 23:05:04 -08:00
Doug Gregor
c291eb596b [Concurrency] Add cancelAsyncTask() builtin.
Implement a new builtin, `cancelAsyncTask()`, to cancel the given
asynchronous task. This lowers down to a call into the runtime
operation `swift_task_cancel()`.

Use this builtin to implement Task.Handle.cancel().
2020-11-05 13:50:17 -08:00
Doug Gregor
81f5528199 [Concurrency] More cleanups for getCurrentAsyncTask builtin.
Michael has ghostwritten all of this to address his own comments.
Thank you!
2020-11-05 12:58:03 -08:00
Doug Gregor
ed9a548c9f [Concurrency] Return getCurrentAsyncTask() as owned.
Rather than produce an "unowned" result from `getCurrentAsyncTask()`,
take advantage of the fact that the task is effectively guaranteed in
the scope. Do so be returning it as "unowned", and push an
end_lifetime cleanup to end the lifetime. This eliminates unnecessary
ref-count traffic as well as introducing another use of unowned.

Approach is thanks to Michael Gottesman, bugs are mine.
2020-11-05 12:18:49 -08:00
Doug Gregor
9566d2e665 [Concurrency] Add a builtin to get the current task in an async function.
This introduces a new builtin, `getCurrentAsyncTask()`, that produces a
reference to the current task. This builtin can only be used within
`async` functions, and IR generation merely grabs the task argument
and packages it up.

The type of this function is `() -> Builtin.NativeObject`, because we
don't currently have a Swift-level representation of tasks, and can
probably handle everything through builtins or runtime calls.
2020-11-05 10:43:33 -08: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
Erik Eckstein
8f2632939a Builtins to support copy-on-write SIL instructions
* Builtin.COWBufferForReading -> ref_element_addr [immutable] / ref_tail_addr [immutable]
* Builtin.beginCOWmutation -> begin_cow_mutation
* Builtin.endCOWmutation -> end_cow_mutation
2020-05-14 08:39:54 +02:00
marcrasi
77fd034a0b Merge pull request #30711 from rxwei/differential-operators
[AutoDiff upstream] Add differential operators and some utilities.
2020-04-01 10:11:35 -07:00
Richard Wei
57d228b39e [AutoDiff upstream] Add differential operators and some utilities.
* Add all [differential operators](https://github.com/apple/swift/blob/master/docs/DifferentiableProgramming.md#list-of-differential-operators).
* Add `withoutDerivative(at:)`, used for efficiently stopping the derivative propagation at a value and causing the derivative at the value to be zero.
* Add utility `differentiableFunction(from:)`, used for creating a `@differentiable` function from an original function and a derivative function.

Mostly work done by @marcrasi and @dan-zheng.
Partially resolves TF-843.

TODO:
* Add `AnyDerivative`.
* Add `Array.differentiableMap(_:)` and `differentiableReduce(_:_:)`.
2020-03-30 14:15:35 -07:00
Anthony Latsis
c63b737e92 Collapse all indirect equivalents to ValueDecl::getBaseIdentifier 2020-03-29 00:36:01 +03:00
Anthony Latsis
d0ae3ee580 [AST] Replace FuncDecl::getName & EnumElementDecl::getName with ValueDecl::getBaseIdentifier 2020-03-29 00:35:51 +03: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
Michael Gottesman
60a09dd63c [builtin] Change ConvertStrongToUnownedUnsafe and ConvertUnownedUnsafeToGuaranteed to take non-optional arguments. 2020-02-12 13:30:06 -08:00
Michael Gottesman
f7f98887d4 [builtin] Add a new SIL builtin convertUnownedUnsafeToGuaranteed()
(BaseT, @inout @unowned(unsafe) T) -> @guaranteed T

The reason for the weird signature is that currently the Builtin infrastructure
does not handle results well. Also, note that we are not actually performing a
call here. We are SILGening directly so we can create a guaranteed result.

The intended semantics is that one passes in a base value that guarantees the
lifetime of the unowned(unsafe) value. The builtin then:

1. Borrows the base.
2. Loads the trivial unowned (unsafe), converts that value to a guaranteed ref
   after unsafely unwrapping the optional.
3. Uses mark dependence to tie the lifetimes of the guaranteed base to the
   guaranteed ref.

I also updated my small UnsafeValue.swift test to make sure we get the codegen
we expect.
2020-02-07 13:08:34 -08:00
Michael Gottesman
1137c00196 [builtin] Add a new SIL builtin convertStrongToUnownedUnsafe()
The signature is:

(T, @inout @unowned(unsafe) Optional<T>) -> ()

The reason for the weird signature is that currently the Builtin infrastructure
does not handle results well.

The semantics of this builtin is that it enables one to store the first argument
into an unowned unsafe address without any reference counting operations. It
does this just by SILGening the relevant code. The optimizer chews through this
code well, so we get the expected behavior.

I also included a small proof of concept to validate that this builtin works as
expected.
2020-02-07 13:07:05 -08:00
Slava Pestov
3997aa5754 SIL: Remove SILBuilder::tryCreateUncheckedRefCast() 2020-01-03 15:37:19 -05:00
Michael Gottesman
f4dfbe94e5 [ownership] Require all operands of ref_tail_addr to have guaranteed ownership.
This ensures that the optimizer has a summary of where the ref_tail_addr will no
longer be used. This is important when analyzing the lifetime of the base of the
ref_tail_addr.

I also cleaned up a little the description around the specification for this in
OperandOwnership. Now all instructions that are "INTERIOR_POINTER_PROJECTIONS"
have their own section/macro as a form of self documenting.
2019-12-31 19:50:16 -08:00
Jordan Rose
853caa66d4 [AST] Split FileUnit and its subclasses out of Module.h
Most of AST, Parse, and Sema deal with FileUnits regularly, but SIL
and IRGen certainly don't. Split FileUnit out into its own header to
cut down on recompilation times when something changes.

No functionality change.
2019-09-17 17:54:41 -07:00
Erik Eckstein
340b0ed001 Support the old single-parameter Builtin.condfail
We have to be source compatible to be able to parse old swiftinterface files where the old Builtin.condfail is used in inlineable functions.

rdar://problem/53176692
2019-07-17 17:41:59 +02:00
Erik Eckstein
b40ce6b34f SIL: add a failure message operand to Builtin.condfail
The SIL generation for this builtin also changes: instead of generating the cond_fail instructions upfront, let the optimizer generate it, if the operand is a static string literal.
In worst case, if the second operand is not a static string literal, the Builtin.condfail is lowered at the end of the optimization pipeline with a default message: "unknown program error".
2019-07-16 14:44:09 +02:00
Erik Eckstein
237a3ef77f SIL: Extend cond_fail by a second operand, which is a static string literal, indicating the failure reason. 2019-07-16 12:31:10 +02:00
Brent Royal-Gordon
d5a2912a26 Revert "Better runtime failure messages (not yet enabled by default)" 2019-07-15 13:42:40 -07:00
Erik Eckstein
3fd7eea96c SIL: add a failure message operand to Builtin.condfail
The SIL generation for this builtin also changes: instead of generating the cond_fail instructions upfront, let the optimizer generate it, if the operand is a static string literal.
In worst case, if the second operand is not a static string literal, the Builtin.condfail is lowered at the end of the optimization pipeline with a default message: "unknown program error".
2019-07-12 14:03:13 +02:00
Erik Eckstein
e2d313ef68 SIL: Extend cond_fail by a second operand, which is a static string literal, indicating the failure reason. 2019-07-12 14:03:13 +02:00
Ravi Kandhadai
5430aa0b17 [Builtin][SILGen][IRGen] Create a new builtin "globalStringTablePointer":
String -> Builtin.RawPointer that given a string constructed from a
literal, returns the address of the string literal in the global string
table of the compiled binary as a pointer.
2019-07-03 16:47:34 -07:00
Slava Pestov
1467f554f5 AST: Remove ArgumentShuffleExpr 2019-03-31 01:36:19 -04:00
Slava Pestov
50b24429c9 SILGen: Stop using "scalar" PreparedArguments except for ArgumentShuffleExpr
For anything else, we can decompose the argument list on the spot.

Note that builtins that are implemented as EarlyEmitters now take a
the argument list as a PreparedArguments instead of a single Expr.

Since the PreparedArguments can still be a scalar with an
ArgumentShuffleExpr, we have to jump through some hoops to turn
it into a list of argument Exprs. This will all go away soon.
2019-03-28 23:23:58 -04:00
Slava Pestov
d470e9df4d AST: Split off ArgumentShuffleExpr from TupleShuffleExpr
Right now we use TupleShuffleExpr for two completely different things:

- Tuple conversions, where elements can be re-ordered and labels can be
  introduced/eliminated
- Complex argument lists, involving default arguments or varargs

The first case does not allow default arguments or varargs, and the
second case does not allow re-ordering or introduction/elimination
of labels. Furthermore, the first case has a representation limitation
that prevents us from expressing tuple conversions that change the
type of tuple elements.

For all these reasons, it is better if we use two separate Expr kinds
for these purposes. For now, just make an identical copy of
TupleShuffleExpr and call it ArgumentShuffleExpr. In CSApply, use
ArgumentShuffleExpr when forming the arguments to a call, and keep
using TupleShuffleExpr for tuple conversions. Each usage of
TupleShuffleExpr has been audited to see if it should instead look at
ArgumentShuffleExpr.

In sequent commits I plan on redesigning TupleShuffleExpr to correctly
represent all tuple conversions without any unnecessary baggage.

Longer term, we actually want to change the representation of CallExpr
to directly store an argument list; then instead of a single child
expression that must be a ParenExpr, TupleExpr or ArgumentShuffleExpr,
all CallExprs will have a uniform representation and ArgumentShuffleExpr
will go away altogether. This should reduce memory usage and radically
simplify parts of SILGen.
2019-03-21 02:18:41 -04:00
Slava Pestov
8915f96e3e SIL: Replace SILType::isTrivial(SILModule) with isTrivial(SILFunction) 2019-03-12 01:16:04 -04:00
Slava Pestov
c791c4a137 SIL: SILUndef must be aware of the resilience expansion
The ownership kind is Any for trivial types, or Owned otherwise, but
whether a type is trivial or not will soon depend on the resilience
expansion.

This means that a SILModule now uniques two SILUndefs per type instead
of one, and serialization uses two distinct sentinel IDs for this
purpose as well.

For now, the resilience expansion is not actually used here, so this
change is NFC, other than changing the module format.
2019-03-12 00:30:35 -04:00
Slava Pestov
903721cdc5 SIL: Remove SILType::getMetatypeInstanceType() 2019-03-01 02:07:16 -05:00
Joe Groff
89979137fc Push ArchetypeType's API down to subclasses.
And clean up code that conditionally works only with certain kinds of archetype along the way.
2018-12-12 19:45:40 -08:00
Erik Eckstein
a60eafe472 Require Builtin.valueToBridgeObject to have a builtin integer as argument
Previously it was used with an UInt struct argument. But this is bad because UInt is a type defined in the stdlib.
2018-10-25 10:18:23 -07:00
John McCall
3a7c649d3e Mark some builtins as taking an owned argument.
The goal here is for the SILGen of these builtins to receive an owned
value so that it will perform an owned->owned conversion and therefore
produce a +1 result, as generally expected.  Without this, SILGen will
perform a borrowed->borrowed conversion, and the copy of the result (if
it even happens) may happen after the argument's borrow scope has ended.
2018-10-20 00:24:38 -04:00
Joe Groff
93b5de61e7 Implement the final approved syntax for SE-227 identity key paths.
`\.self` is the final chosen syntax. Implement support for this syntax, and remove the stopgap builtin and `WritableKeyPath._identity` property that were in place before.
2018-09-19 11:45:13 -07:00
John McCall
6d4c724101 Distinguish different kinds of l-value reads in SILGen.
This is NFC for now, but I plan to build on this to (1) immediately
remove some unnecessary materialization and loads of the base value
and (2) to allow clients to load a borrowed value.
2018-08-30 19:42:53 -04:00
Erik Eckstein
7c06d4f8ab Remove the pinning built-ins.
They are not used anymore after removing the pinning adressors.
2018-08-23 12:47:56 -07:00
Joe Groff
44b55ae197 Runtime support for identity key paths.
Make sure the implementation can handle a key path with zero components by removing inappropriate assumptions that the number of components is always non-empty. Identity key paths also need some special behavior:

- Appending an identity key path should be an identity operation for the other operand
- Identity key paths have a `MemoryLayout.offset(of:)` zero
- Identity key paths interop with KVC as key paths to `@"self"`

To be able to exercise and test this behavior, add a `Builtin.identityKeyPath()` function and `WritableKeyPath._identity` accessor in lieu of finalized syntax.
2018-08-20 14:00:46 -07:00
Doug Gregor
b08a6f56b4 [AST] Drop resilience expansion from TypeBase::getReferenceCounting().
We’re not using this parameter, and don’t expect to do so in the future,
so remove it. Also fold away TypeBase::usesNativeReferenceCounting()
and irgen::getReferenceCountingForType(), both of which are trivial.
2018-08-14 09:10:49 -07:00
Ben Cohen
2b04e9f105 Suppress a number of warnings in no-assert builds (#17721)
* Supress a number of warnings about things used only in asserts

* Re-use a couple of variables instead of supressing the warning
2018-07-04 07:15:14 -07:00
Andrew Trick
fe326266cc [exclusivity] Add a [builtin] flag to begin_[unpaired_]access.
This flag supports promoting KeyPath access violations to an error in
Swift 4+, while building the standard library in Swift 3 mode. This is
only necessary as long as the standard library continues to build in
Swift 3 mode. Once the standard library build migrates, it can all be
ripped out.

<rdar://problem/40115738> [Exclusivity] Enforce Keypath access as an error, not a warning in 4.2.
2018-05-09 21:42:37 -07:00
David Zarzycki
8c0c55539f [SIL] NFC: Rename misleading getSwiftRValueType() to getASTType()
Reference storage types are not RValues. Also, use more SILType helper
methods to avoid line wrap.
2018-05-04 08:14:38 -04:00
Doug Gregor
408aaa5332 [SIL] Use SubstitutionMap in BuiltinInst. 2018-05-03 08:48:55 -07:00
Doug Gregor
d2cf60c465 Revert "[SIL] Replace more SubstitutionLists with SubstitutionMap" 2018-05-03 08:35:20 -07:00