Commit Graph

118 Commits

Author SHA1 Message Date
John McCall
db3967f41d Future-proof the layout of AsyncTask. 2021-05-20 15:30:48 -04:00
Mike Ash
e4a1d2bbed [Concurrency] Expose Job's metadata as a debug variable 2021-05-13 15:57:03 -04:00
Fred Riss
bbda706393 [Concurrency] Add a unique Task ID to AsyncTask
This commit changes JobFlags storage to be 32bits, but leaves the runtime
API expressed in terms of size_t. This allows us to pack an Id in the
32bits we freed up.

The offset of this Id in the AsyncTask is an ABI constant. This way
introspection tools can extract the currently running task identifier
without any need for special APIs.
2021-05-11 08:28:17 -07:00
Konrad `ktoso` Malawski
6cbb792f92 [TaskLocals] Propagate task-locals through async{} 2021-05-11 11:06:17 +09:00
Dario Rexin
efe6973293 [Concurrency] Reduce overhead of Task.yield and Task.sleep (#37090)
* [Concurrency] Reduce overhead of Task.yield and Task.sleep

Instead of creating a new task, we create a simple job that wraps a Builtin.RawUnsafeContinuation and resumes the continuation when it is executed. The job instance is allocated on the task local allocator, meaning we don't malloc anything.

* Update stdlib/public/Concurrency/Task.swift

Co-authored-by: Konrad `ktoso` Malawski <konrad.malawski@project13.pl>

Co-authored-by: Konrad `ktoso` Malawski <konrad.malawski@project13.pl>
2021-05-10 11:51:20 -07:00
Doug Gregor
220e29d674 Reinstate "async let", with "spawn let" as an alias. 2021-05-07 00:13:56 -07:00
Max Desiatov
7be99e4cbf Merge pull request #37084 from kateinoigakukun/katei/share-fatalerror-concurrency
Rename duplicated `swift::fatalError` in `swiftRuntime` and `swift_Concurrency`.

Both `swiftRuntime` and `swift_Concurrency` had `swift::fatalError` implementation, but it causes symbol conflict with the `-static-stdlib` flag.

This patch removes one of the implementations in `swift_Concurrency` to avoid conflicts. Also added a test case to ensure that linking the Concurrency module with `-static-stdlib` works.

This issue was found by SwiftWasm test cases.
2021-05-06 09:46:15 +01:00
John McCall
cc2863c136 Merge pull request #36878 from rjmccall/custom-executors
Introduce basic support for custom executors
2021-04-30 13:54:02 -04:00
swift-ci
e152c14c0a Merge pull request #37162 from DougGregor/spawn-let 2021-04-30 02:19:16 -07:00
John McCall
186c53000d Introduce basic support for custom executors.
- Introduce an UnownedSerialExecutor type into the concurrency library.
- Create a SerialExecutor protocol which allows an executor type to
  change how it executes jobs.
- Add an unownedExecutor requirement to the Actor protocol.
- Change the ABI for ExecutorRef so that it stores a SerialExecutor
  witness table pointer in the implementation field.  This effectively
  makes ExecutorRef an `unowned(unsafe) SerialExecutor`, except that
  default actors are represented without a witness table pointer (just
  a bit-pattern).
- Synthesize the unownedExecutor method for default actors (i.e. actors
  that don't provide an unownedExecutor property).
- Make synthesized unownedExecutor properties `final`, and give them
  a semantics attribute specifying that they're for default actors.
- Split `Builtin.buildSerialExecutorRef` into a few more precise
  builtins.  We're not using the main-actor one yet, though.

Pitch thread:
  https://forums.swift.org/t/support-custom-executors-in-swift-concurrency/44425
2021-04-30 03:11:56 -04:00
Doug Gregor
5d8174da57 [Concurrency] Introduce spawn let 2021-04-29 22:42:40 -07:00
Konrad `ktoso` Malawski
6f3dac190a [TaskLocals] remove TaskLocalInheritance, we'll introduce when needed 2021-04-29 15:48:22 +09:00
Yuta Saito
709359cfab Rename duplicated swift::fatalError definition in swiftRuntime and swift_Concurrency
Both swiftRuntime and swift_Concurrency had swift::fatalError
implementation, but it causes symbol conflict when -static-stdlib.

This patch renames one of the impl in swift_Concurrency to avoid
conflict.
2021-04-28 23:52:18 +09:00
Erik Eckstein
075ad87a40 Concurrency: allocate an async-let task with its parent's stack allocator.
Also, do this for the initial slab for the task's allocator itself.
This avoids memory allocations for async-lets.
In case the async-task's memory demand does not exceed the initial slab size, it is now completely malloc-free.

The refcount bits of an async-let task are initialized to "immortal" so that ARC operations don't have an effect on the task.
2021-04-26 13:07:32 +02:00
Erik Eckstein
93367ed587 concurrency: make the startAsyncLet closure no-escaping
The closure does not escape the startAsyncLet - endAsyncLet scope. Even though it's (potentially) running on a different thread.

The substantial change in the runtime is to not call swift_release on the closure context if it's a non-escaping closure.
2021-04-20 21:57:19 +02:00
Konrad `ktoso` Malawski
d3c5ebc9b7 [AsyncLet] reimplemented with new ABI and builtins 2021-04-19 10:06:23 +09:00
Konrad `ktoso` Malawski
ba615029c7 [Concurrency] Store child record when async let child task spawned 2021-04-19 10:06:23 +09:00
Arnold Schwaighofer
ae2a4cca14 Merge pull request #36842 from aschwaighofer/fix_withCancellationHandler_arm64e_windows
Fix with cancellation handler arm64e windows
2021-04-10 14:10:12 -07:00
Arnold Schwaighofer
141634aae7 Fix withCancellationHandler on arm64e 2021-04-09 05:30:24 -07:00
John McCall
efeb818161 Clean up the TaskGroup ABI:
- stop storing the parent task in the TaskGroup at the .swift level
- make sure that swift_taskGroup_isCancelled is implied by the parent
  task being cancelled
- make the TaskGroup structs frozen
- make the withTaskGroup functions inlinable
- remove swift_taskGroup_create
- teach IRGen to allocate memory for the task group
- don't deallocate the task group in swift_taskGroup_destroy

To achieve the allocation change, introduce paired create/destroy builtins.

Furthermore, remove the _swiftRetain and _swiftRelease functions and
several calls to them.  Replace them with uses of the appropriate builtins.
I should probably change the builtins to return retained, since they're
working with a managed type, but I'll do that in a separate commit.
2021-04-09 03:06:31 -04:00
John McCall
be8d2c83fa Give up default actors in swift_job_run if we switch to them.
Previously, if this happened, we simply left the actor in a running
state, causing any further jobs submitted to it to never be executed.
I can only speculate why this wasn't showing up in testing.

Also, change swift_job_run so that it prevents switching if the executor
passed in is not generic.  This is an entrypoint for arbitrary executors
and generally should not allow unexpected switching (if someday custom
executors participate in that scheme).  This infrastructure will also
be useful for implementing the `async let` semantics of running
synchronously until the task reaches a suspension point.

Finally, improve the #if'ed logging code throughout the task/actor runtime.
2021-04-08 12:57:12 -04:00
Nate Chandler
d3e0e7af07 [ptrauth] Signed AsyncFunctionPointers as data.
Previously, AsyncFunctionPointer constants were signed as code.  That
was incorrect considering that these constants are in fact data.  Here,
that is fixed.

rdar://76118522
2021-04-05 18:24:41 -07:00
Konrad `ktoso` Malawski
6e746304e1 [Concurrency] Update Task and Group APIs based on Review 1 2021-04-03 09:52:03 +09:00
Mike Ash
e98fc3e304 Merge pull request #36572 from mikeash/async-task-dispatch-integration2
[Concurrency] Make Job objects work as Dispatch objects.
2021-03-31 09:42:58 -04:00
John McCall
98711fd628 Revise the continuation ABI.
The immediate desire is to minimize the set of ABI dependencies
on the layout of an ExecutorRef.  In addition to that, however,
I wanted to generally reduce the code size impact of an unsafe
continuation since it now requires accessing thread-local state,
and I wanted resumption to not have to create unnecessary type
metadata for the value type just to do the initialization.

Therefore, I've introduced a swift_continuation_init function
which handles the default initialization of a continuation
and returns a reference to the current task.  I've also moved
the initialization of the normal continuation result into the
caller (out of the runtime), and I've moved the resumption-side
cmpxchg into the runtime (and prior to the task being enqueued).
2021-03-28 12:58:16 -04:00
Mike Ash
0989524338 [Concurrency] Make Job objects work as Dispatch objects.
Fill out the metadata for Job to have a Dispatch-compatible vtable. When available, use the dispatch_enqueue_onto_queue_4Swift to enqueue Jobs directly onto queues. Otherwise, keep using dispatch_async_f as we have been.

rdar://75227953
2021-03-26 18:31:00 -04:00
Joe Groff
4150b31954 Fix calling convention for withCompletionHandler runtime calls.
rdar://75370240
2021-03-25 14:45:47 -07:00
Mike Ash
c4e4e44f71 Merge pull request #36390 from mikeash/concurrency-compatibility-overrides
[Concurrency] Add compatibility overrides to Concurrency library.
2021-03-24 13:07:07 -04:00
Evan Wilde
8f974c1a79 Merge pull request #36524 from etcwilde/ewilde/fix-after-main-crash
[Concurrency] Make asyncMainDrainQueue noreturn
2021-03-22 23:00:33 -07:00
Mike Ash
6aab257c33 [Concurrency] Add compatibility overrides to Concurrency library.
Take the existing CompatibilityOverride mechanism and generalize it so it can be used in both the runtime and Concurrency libraries. The mechanism is preprocessor-heavy, so this requires some tricks. Use the SWIFT_TARGET_LIBRARY_NAME define to distinguish the libraries, and use a different .def file and mach-o section name accordingly.

We want the global/main executor functions to be a little more flexible. Instead of using the override mechanism, we expose function pointers that can be set by the compatibility library, or by any other code that wants to use a custom implementation.

rdar://73726764
2021-03-22 11:09:06 -04:00
Evan Wilde
b0b4cb67a1 Make asyncMainDrainQueue noreturn
CFRunLoopRun returns once it finishes, though the kernel may clean us up
before we get there. We effectively have a race condition between the
kernel cleaning us up and returning from a never returning function.

Small programs likely get cleaned up before reaching the ud2 instruction
emitted after the never returning function in swift, so they don't
notice, but programs of a sufficient size do. At that size, the program
will crash after what the programmer expects to be the end of their
program.
2021-03-19 12:33:26 -07:00
Arnold Schwaighofer
cf55973973 Remove unused ResumeParentExecutor 2021-03-18 09:05:45 -07:00
Arnold Schwaighofer
3bdd5cb99a IRGen: async error ABI
Throwing functions pass the error result in `swiftself` to the resume
partial function.
Therefore, `() async -> ()` to `() async throws -> ()` is not ABI compatible.

TODO: go through remaining failing IRGen async tests and replace the
illegal convert_functions.
2021-03-17 17:17:12 -07:00
Arnold Schwaighofer
f75fbb7594 IRGen: Async ABI passing parameter and results directly
The error is still passed in the async context. I will fix this in a
follow-up.
2021-03-17 07:41:01 -07:00
John McCall
6c879d6fd3 Change the async ABI to not pass the active task and executor.
Most of the async runtime functions have been changed to not
expect the task and executor to be passed in.  When knowing the
task and executor is necessary, there are runtime functions
available to recover them.

The biggest change I had to make to a runtime function signature
was to swift_task_switch, which has been altered to expect to be
passed the context and resumption function instead of requiring
the caller to park the task.  This has the pleasant consequence
of allowing the implementation to very quickly turn around when
it recognizes that the current executor is satisfactory.  It does
mean that on arm64e we have to sign the continuation function
pointer as an argument and then potentially resign it when
assigning into the task's resume slot.

rdar://70546948
2021-03-16 22:52:54 -04:00
swift-ci
549923513a Merge pull request #36216 from apple/tsan-swift-concurrency2 2021-03-16 19:11:20 -07:00
Nate Chandler
ee63777332 [IRGen] Fix ABI for thick async functions.
Previously, thick async functions were represented sometimes as a pair
of (AsyncFunctionPointer, nullptr)--when the thick function was produced
via a thin_to_thick_function, e.g.--and sometimes as a pair of
(FunctionPointer, ThickContext)--when the thick function was produced by
a partial_apply--with the size stored in the slot of the ThickContext.

That optimized for the wrong case: partial applies of dynamic async
functions; in that case, there is no appropriate AsyncFunctionPointer to
form when lowering the partial_apply instruction.  The far more common
case is to know exactly which function is being partially applied.  In
that case, we can form the appropriate AsyncFunctionPointer.

Furthermore, the previous representation made calling a thick function
more complex: it was always necessary to check whether the context was
in fact null and then proceed along two different paths depending.

Here, that behavior is corrected by creating a thunk in a mandatory
IRGen SIL pass in the case that the function that is being partially
applied is dynamic.  That new thunk is then partially applied in place
of the original partial_apply of the dynamic function.
2021-03-15 13:37:40 -07:00
Julian Lettner
99bcd87af6 Use swift_once instead of C++ static initializers 2021-03-12 14:52:56 -08:00
Mike Ash
bedca5ed61 Merge pull request #36139 from mikeash/async-task-dispatch-integration
[Concurrency] Make Job/AsyncTask minimally compatible with dispatch object layout
2021-03-11 18:04:04 -05:00
Mike Ash
bd62fdb2db [Concurrency] Make Job/AsyncTask minimally compatible with dispatch object layout
Create a TargetDispatchClassMetadata for Swift metadata that also has a dispatch-compatible vtable. Dispatch leaves room for ObjC class metadata so the two regions don't overlap. (The vtable currently consists of a single dummy entry; this will be filled out later.)

Rearrange the Job and AsyncTask hierarchy so that AsyncTask inherits only from Job, which in turn inherits from HeapObject. This gives all Job instances a dispatch-compatible isa field. It also gives them a refcount word, which is wasted on instances that aren't AsyncTask instances. Maybe we can find some use for that space in the future.

rdar://75227953
2021-03-10 10:04:30 -05:00
Joe Groff
872afda50b Merge pull request #36298 from jckarter/created-task-closure-context-leak
SIL: Clean up ownership handling in `createAsyncTask` builtins.
2021-03-09 14:17:13 -08:00
Joe Groff
d9798c0868 Concurrency: Redo non-_f variants of swift_task_create to accept closures as is.
In their previous form, the non-`_f` variants of these entry points were unused, and IRGen
lowered the `createAsyncTask` builtins to use the `_f` variants with a large amount of caller-side
codegen to manually unpack closure values. Amid all this, it also failed to make anyone responsible
for releasing the closure context after the task completed, causing every task creation to leak.
Redo the `swift_task_create_*` entry points to accept the two words of an async closure value
directly, and unpack the closure to get its invocation entry point and initial context size
inside the runtime. (Also get rid of the non-future `swift_task_create` variant, since it's unused
and it's subtly different in a lot of hairy ways from the future forms. Better to add it later
when it's needed than to have a broken unexercised version now.)
2021-03-08 16:54:19 -08:00
Joe Groff
016496384e Concurrency: Remove currently-unused non-_f variants of swift_task_create
I'm about to replace these with new variations that correctly handle spawning a task with
a closure as its initial entry point, without leaking or requiring large amounts of caller-side
code generation.
2021-03-05 12:01:06 -08:00
Konrad `ktoso` Malawski
aedbbe615d [TaskGroup] Towards ABI stability of groups 2021-03-02 20:25:22 +09:00
Konrad `ktoso` Malawski
fcb1c01a36 [TaskLocal] Use the task-local stack discipline allocator 2021-03-02 11:14:41 +09:00
Julian Lettner
a3ccdd29d8 Teach TSan about Swift Task and Actor model
I have identified the following conceptual synchronization points at
which task data and computation can cross thread boundaries.  We need to
model these in TSan to avoid false positives:

Awaiting an async task (`AsyncTask::waitFuture`), which has two cases:
1) The task has completed (`AsyncTask::completeFuture`).  Everything
   that happened during task execution "happened before" before the
   point where we access its result.  We synchronize on the *awaited*
   task.
2) The task is still executing: the current execution is suspended and
   the waiting task is put into the list of "waiters".  Once the awaited
   task completes, the waiters will be scheduled.  In this case, we
   synchronize on the *waiting* task.

Note: there is a similar relationship for task groups which I still have
to investigate.  I will follow-up with an additional patch and tests.

Actor job execution (`swift::runJobInExecutorContext`):
Job scheduling (`swift::swift_task_enqueue`) precedes/happens before job
execution.  Also all job executions (switching actors or suspend/resume)
are serially ordered.

Note: the happens-before edge for schedule->execute isn't strictly
needed in most cases since scheduling calls through to libdispatch's
`dispatch_async_f`, which we already intercept and model in TSan.
However, I am trying to model Swift Task semantics to increase the
chance of things to continue to work in case the "task backend" is
switched out.

rdar://74256733
2021-03-01 13:41:55 -08:00
Konrad `ktoso` Malawski
d7169edc21 [TaskLocals] Cleanly separate locals impl from Task, no need for fragment 2021-03-02 00:54:47 +09:00
Konrad `ktoso` Malawski
de5fdcd2f8 [TaskGroup] fix missing retain in scheduling next() immediately on offer 2021-02-24 18:45:33 +09:00
Konrad `ktoso` Malawski
6f4fca8721 Merge branch 'main' into wip-no-escape-group 2021-02-24 08:59:53 +09:00
John McCall
2012195cd5 Alter the runtime interface for awaiting futures and task groups.
First, just call an async -> T function instead of forcing the caller
to piece together which case we're in and perform its own copy.  This
ensures that the task is actually kept alive properly.

Second, now that we no longer implicitly depend on the waiting tasks
being run synchronously, go ahead and schedule them to run on the
global executor.

This solves some problems which were blocking the work on TLS-ifying
the task/executor state.
2021-02-21 23:48:13 -05:00