Commit Graph

254 Commits

Author SHA1 Message Date
Konrad `ktoso` Malawski
b9369bf0b7 [Concurrency] Fix default actor isolation issue in face of TaskExecutor preference (#74658)
* [Concurrency] Fix task excutor handling of default actor isolation

The task executor API did not properly account for taking the default
actor locking into account when running code on it, we just took the job
and ran it without checking with the serial executor at all, which
resulted in potential concurrent executions inside the actor --
violating actor isolation.

Here we change the TaskExecutor enqueue API to accept the "target"
serial executor, which in practice will be either generic or a specific
default actor, and coordinate with it when we perform a
runSynchronously.

The SE proposal needs to be amended to showcase this new API, however
without this change we are introducing races so we must do this before
the API is stable.

* Remove _swift_task_enqueueOnTaskExecutor as we don't use it anymore

* no need for the new protocol requirement

* remove the enqueue(_ job: UnownedJob, isolatedTo unownedSerialExecutor: UnownedSerialExecutor)

Thankfully we dont need it after all

* Don't add swift_defaultActor_enqueue_withTaskExecutor and centralize the task executor getting to enqueue()

* move around extern definitions
2024-07-01 16:42:27 +09:00
Konrad `ktoso` Malawski
2ec717b115 [Concurrency] TaskExecutor ownership fixes (#74000) 2024-06-14 22:56:33 +09:00
Konrad `ktoso` Malawski
14b8546392 [Concurrency] Don't add new task locals copy runtime func 2024-06-03 13:55:02 +09:00
Konrad `ktoso` Malawski
0c44645832 [Concurrency] Implement defensive copying in task groups, rather than crashing (#73978) 2024-05-31 11:27:03 -07:00
John McCall
d3e7b5116f In the task-to-thread model of UnsafeContinuation, destroy the
condvar before we try to tail-call.  This is necessary because the
swiftasync tail-call handling is (reasonably) reluctant to reorder
cleanups so that locals are destroyed before the call, and of course it
cannot destroy them after it and still emit a tail call.

Old versions of clang handled these tailcalls differently and failed
to diagnose this, but I'm pretty sure they just ended up not doing a
tail call rather than actually doing anything reasonable.

Fixes rdar://125363169
2024-05-28 22:04:50 -04:00
Mike Ash
0f226b6667 [Concurrency] Refine getResumeFunctionForLogging to avoid reading invalid future contexts.
When using a future adapter, the resume context may not be valid after the task starts running. Only peer through the adapter when we're starting to run.

rdar://126298035
2024-05-21 16:22:40 -04:00
Konrad `ktoso` Malawski
dfcf1054dd [Concurrency] Remove _unsafeInheritExecutor from public APIs, use #isolation (#72578) 2024-04-05 03:57:54 -07:00
John McCall
14dcab6bcd Restore (TaskOptionRecordKind)0 to set the initial serial executor.
This has been the behavior of the runtime since the initial release.
Initially, it was thought that task executors would provide similar
functionality, so they naturally took over the enumerator.  After that
changed, we forgot to change it back.  Fortunately, we haven't released
any versions of Swift with the task executors feature yet, so it's not
too late to fix this.
2024-03-08 00:15:10 -05:00
Allan Shortlidge
64d0f72d98 NFC: Address a warning in swift_task_asyncMainDrainQueueImpl().
The function is marked `noreturn` but the compiler was not able to reason
statically about whether this constraint is met. From code inspection it's
clear that the call to `swift_task_donateThreadToGlobalExecutorUntil()` does
not return, so `swift_unreachable()` can be used to suppress the warning.
2024-01-19 15:43:35 -08:00
Konrad `ktoso` Malawski
828f589be4 Initial Task Executor implementation Task(on:), addTask(on:) etc. (#68793)
Co-authored-by: John McCall <rjmccall@gmail.com>
2023-12-12 17:14:24 +09:00
Konrad `ktoso` Malawski
5546f4da7b Rename ExecutorRef to SerialExecutorRef 2023-11-01 18:39:44 +09:00
Kuba Mracek
90e1d2006f [embedded] Add support for actors and async let into the embedded Concurrency runtime 2023-10-09 22:43:50 -07:00
Kuba Mracek
df5879746c [embedded] Use async main in the test 2023-10-06 20:32:21 -07:00
Kuba Mracek
afa1427bca [embedded] Fix build breakage in swift_task_run_inline related to ResultTypeInfo 2023-10-06 20:04:03 -07:00
Kuba Mracek
744f558e9c [embedded] Don't allow ResultTypeInfoTaskOptionRecord parsing outside embedded Swift 2023-10-06 20:04:03 -07:00
Kuba Mracek
b9fe308567 [embedded] Remove unintentional whitespace change 2023-10-06 20:04:03 -07:00
Kuba Mracek
a1f0782c0c [embedded] Add null checks of futureResultType back (allow non-future tasks) 2023-10-06 20:04:03 -07:00
Kuba Mracek
5d8c55eacb [embedded] Initial Swift Concurrency for embedded Swift 2023-10-06 20:04:03 -07:00
Yuta Saito
0ceab44032 [DiscardingTG] Fix runtime signature mismatch for statically known -> Void closure
Since https://github.com/apple/swift/pull/65613, DiscardingTG started to
accept `() -> Void` instead of `() -> T`, but it also changed the number
of arguments accepted by the closure from 3 to 2. So it should use
`non_future_adapter` instead of `future_adapter` to avoid runtime signature
mismatch.
2023-05-30 18:15:12 +00:00
Konrad `ktoso` Malawski
cad608eb81 [Discarding] Don't leak retained "first error" task when retaining it 2023-05-24 18:03:28 +02:00
Evan Wilde
c18c37b6ba Use isCurrentExecutor check in startOnMainActorImpl
startOnMainActor checked the current executor directly, which in some
cases came back as a `nullptr`. This happens with older API which don't
know to set the current executor. `swift_task_isCurrentExecutor` knows
how to check for the current dispatch queue and the main thread though,
so switching the main-executor check to use that API instead.
2023-04-18 16:38:29 -07:00
Evan Wilde
1bd1c468a0 Concurrency: Task.startOnMainActor
This patch adds an SPI to run the first partial function of a MainActor
asynchronous function on the MainActor synchronously. This is
effectively like the asynchronous program entrypoint behavior. The first
partial function is run synchronously. Following continuations are
enqueued for execution like any other asynchronous function.
2023-03-06 13:33:22 -08:00
Evan Wilde
841fda5dbe Add asyncMainDrainQueue hook
The swift_task_asyncMainDrainQueue function acts as the entrypoint into
driving the main queues, ultimately running the whole program and acting
as the backing driver of the main actor. Making the function hookable
means that custom concurrency runtimes can implement their own async
entrypoints, allowing async top-level code and async-main to "just
work".
2023-03-01 22:16:23 -08:00
Evan Wilde
ec7a926148 Fix asyncMainDrainQueue noreturn warning
The async main drain queue function is noreturn, but was emitting a
warning due to the override compatibility returning the result of the
overridden function in the wrapper override function. To work around
this, I've added the `OVERRIDE_TASK_NORETURN` macro, which provides an
override point for noreturn functions in the concurrency library that
doesn't return the result from the wrapped function, avoiding the
warning. In the event that the function is not set, the macro is set to
the normal `OVERRIDE` with the return type set to `void`.
2023-03-01 17:08:41 -08:00
Rokhini Prabhu
7dd16da3b1 Merge pull request #63916 from apple/rokhinip/105930505-updateStatusRecord-and-friends
Improve functionality available for manipulating status records.
2023-02-28 13:42:36 -08:00
Konrad `ktoso` Malawski
a2783b2e8d [Concurrency] UnownedJob.priority and description for TaskPriority 2023-02-28 16:17:48 +09:00
Rokhini Prabhu
d0aa55670a Provide an updateStatusRecord function which allows clients to update a
status record that is already registered with the task. Provide more
versatile removeStatusRecord functions and update clients to use them

Radar-Id: rdar://problem/101864092
2023-02-25 16:55:38 -08:00
Dario Rexin
a8d4d57f11 [IRGen] Generate compressed representation of value witnesses (#63813)
rdar://105837040

* WIP: Store layout string in type metadata

* WIP: More cases working

* WIP: Layout strings almost working

* Add layout string pointer to struct metadata

* Fetch bytecode layout strings from metadata in runtime

* More efficient bytecode layout

* Add support for interpreted generics in layout strings

* Layout string instantiation, take and more

* Remove duplicate information from layout strings

* Include size of previous object in next objects offset to reduce number of increments at runtime

* Add support for existentials

* Build type layout strings with StructBuilder to support target sizes and metadata pointers

* Add support for resilient types

* Properly cache layout strings in compiler

* Generic resilient types working

* Non-generic resilient types working

* Instantiate resilient type in layout when possible

* Fix a few issues around alignment and signing

* Disable generics, fix static alignment

* Fix MultiPayloadEnum size when no extra tag is necessary

* Fixes after rebase

* Cleanup

* Fix most tests

* Fix objcImplementattion and non-Darwin builds

* Fix BytecodeLayouts on non-Darwin

* Fix Linux build

* Fix sizes in linux tests

* Sign layout string pointers

* Use nullptr instead of debug value
2023-02-24 15:40:28 -08:00
Rokhini Prabhu
3c0f4f79fe Provide a convenience for addStatusRecord for clients who have already
done the load or who need the oldStatus information after adding the
status record.

Change some of the memory barrier logic since we can take advantage of
load-through HW address dependency.

Radar-Id: rdar://problem/105634683
2023-02-20 23:14:47 -08:00
Rokhini Prabhu
e052ccef31 Create the notion of a TaskDependencyStatusRecord which tracks what a
task is blocked on. We can use this information to then perform live
priority escalation to a task future.

Radar-Id: rdar://problem/88093007
2023-02-08 17:29:55 -08:00
Rokhini Prabhu
2e6baf279d Add support to addStatusRecord and removeStatusRecord so that the flags
field of an ActiveTaskStatus can also be modified while the
TaskStatusRecord list is being modified. Make the StatusRecordLock
reentrant.

Radar-Id: rdar://problem/88093007
2023-02-08 17:29:05 -08:00
Rokhini Prabhu
4152834319 Don't destroy the task private storage until task is destroyed since
other threads/tasks which have a reference to the task might need to
access parts of it even if the task itself is completed.

Radar-Id: rdar://problem/88093007
2023-02-07 14:34:29 -08:00
Kavon Farvardin
ce3da795aa completeFuture should have acquire-release for the exchange
When a completed task updates the queue head to announce
that it's been completed, it only did an acquire exchange.

By also having it also do a release, we will ensure that
prior writes done by the completed task, before the task is
marked completed, will be correctly ordered as happening
before any subsequent reads by tasks waiting on that
completion status.

Co-authored-by: John McCall <rjmccall@apple.com>
2023-01-11 14:11:47 -08:00
Erik Eckstein
77fd3a7004 runtime: fix a wrong fall-through caused by an assert(false)
Replace the `assert(false)` with `swift_unreachable`.
This is more robust in release builds where the `assert(false)` is a no-op and would result in a wrong fall-though to the next switch case.
Fixes a warning in release builds.
2022-11-14 20:40:56 +01:00
Rokhini Prabhu
b2f51dd3de Implement continuations in task-to-thread model.
This is done using a condition variable upon which the awaiting thread
will block if the continuation has not be resumed by the point of await.
The resuming thread will signal this condition variable, thereby
unblocking the awaiting thread.

Rdar://99977665
2022-11-09 15:58:53 -08:00
Mike Ash
afc5116ef0 [Concurrency] Add an environment variable to validate unchecked continuation usage.
When enabled, we track all active unchecked continuations in a global set, and fatal error if one is called twice.

rdar://97390481
2022-09-16 13:50:59 -04:00
Rokhini Prabhu
a606892155 Task group children should be executed on parent task at time of await 2022-09-01 10:02:25 -07:00
Rokhini Prabhu
cb6ffe831b In task-to-thread model, make sure that when we are waiting on an
async-let task, we run it in the context of the parent task.
2022-09-01 10:02:25 -07:00
Rokhini Prabhu
f2099c50cd Make sure that current thread's priority propagates to a runInline task 2022-09-01 10:02:25 -07:00
Nate Chandler
34c08b8344 [TaskToThread] Add Task.runInline.
The new intrinsic, exposed via static functions on Task<T, Never> and
Task<T, Error> (rethrowing), begins an asynchronous context within a
synchronous caller's context.  This is only available for use under the
task-to-thread concurrency model, and even then only under SPI.
2022-07-08 08:44:18 -07:00
Nate Chandler
59f6cbc385 [NFC] Extracted function for header/context size.
So that this functionality is available elsewhere, extract it from
swift_task_create_commonImpl into a reusable static functions.
2022-07-06 11:51:16 -07:00
Nate Chandler
da45a67192 [NFC] Removed unused argument.
Previously getAsyncClosureEntryPointAndContextSize took both a pointer
for a function and a closure context.  That was a relic of a temporary
ABI where async function pointers were not used in all cases.  Now that
that ABI is long gone, async function pointers are always used.
Consequently, the closure context argument was unused.  Here, the
closure context argument is removed.
2022-07-06 11:51:16 -07:00
John McCall
ef80a315f8 When waiting on a task, escalate it before enqueuing the waiting task.
As soon as the waiting task is successfully enqueued on the blocking
task, both tasks have to be considered invalidated because the
blocking task can concurrently complete and resume its waiters:

- The waiting task ensures that the blocking task is valid while
  it's waiting.  However, that's measured from the perspective of
  the waiting task, not from the perspective of the thread that was
  previously executing it.  As soon as the waiting task is resumed,
  the wait call completes and the validity guarantee on the blocking
  task disappears, so the blocking task must be treated as
  invalidated.

- The waiting task ensures that it is valid as long as it isn't
  complete.  Since it's trying to wait, it must not be complete.
  However, as soon we resume it, it can complete, so the waiting
  task must also be treated as invalidated.

This is one of those things that's not really easy to test, and the
need for a fix is pretty urgent, so I'm submitting this patch without
a test.  I'll try to land a race test that demonstrates the bug in
the next few days.

@kavon deserves all the credit here for some truly heroic debugging
and finally recognizing the flaw in the code; I'm just popping in
at the last minute to sheepishly patch the bug.

Fixes rdar://92666987
2022-06-10 23:39:59 -04:00
Alastair Houghton
0e9318cec5 [Threading] Put everything through git clang-format.
Just formatting changes.

rdar://90776105
2022-06-07 07:39:53 +01:00
Alastair Houghton
e305a7dcf6 [Concurrency][Windows] Add a couple of includes for Windows.
Actor.cpp does need <io.h> still, and Task.cpp should have been including
<windows.h>

rdar://90776105
2022-06-07 07:39:52 +01:00
Alastair Houghton
f5bdb858e0 [Threading] Create new threading library and use it.
Moved all the threading code to one place.  Added explicit support for
Darwin, Linux, Pthreads, C11 threads and Win32 threads, including new
implementations of Once for Linux, Pthreads, C11 and Win32.

rdar://90776105
2022-06-07 07:39:51 +01:00
Alex Hoppen
4aa2bbbf06 Revert "Merge pull request #42447 from al45tair/eng/PR-90776105"
This reverts commit 8bcb71140f, reversing
changes made to c4dd271d36.
2022-06-02 18:03:23 +02:00
Alastair Houghton
b5bd267ff1 [Threading] Put everything through git clang-format.
Just formatting changes.

rdar://90776105
2022-05-24 14:57:41 +01:00
Alastair Houghton
1fc36cf1f9 [Concurrency][Windows] Add a couple of includes for Windows.
Actor.cpp does need <io.h> still, and Task.cpp should have been including
<windows.h>

rdar://90776105
2022-05-24 14:57:41 +01:00
Alastair Houghton
63a09007a1 [Threading] Create new threading library and use it.
Moved all the threading code to one place.  Added explicit support for
Darwin, Linux, Pthreads, C11 threads and Win32 threads, including new
implementations of Once for Linux, Pthreads, C11 and Win32.

rdar://90776105
2022-05-24 14:57:39 +01:00