Commit Graph

1608 Commits

Author SHA1 Message Date
Mike Ash
0977920217 [Concurrency] Add tracing for major operations in the concurrency runtime.
Each trace point is declared as a function in the new `Tracing.h` header. These functions are called from the appropriate places in the concurrency runtime.

On Darwin, an implementation of these functions is provided which uses the `os/signpost.h` API to emit signpost events/intervals.

When the signpost API is not available, no-op stub implementations are provided. Implementations for other OSes can be provided by providing implementations of the trace functions for that OS.

rdar://81858487
2022-01-07 11:35:40 -05:00
Evan Wilde
bfcc809ac8 Merge branch 'main' into ewilde/concurrency/cleanup-run-async-main 2022-01-03 08:36:40 -08:00
Rokhini Prabhu
e35eba06d2 Remove old addChild and detachChild stuff from files
Radar-Id: rdar://problem/86347801
2021-12-31 03:23:52 -08:00
Rokhini Prabhu
1947102ebd Change the logic for adding new task status records to a task
This change has two parts to it:

1. Add in a new interface (addStatusRecordWithChecks) for adding task
status records that also takes in a function ref. This function ref will
be used to evaluate if current state of the parent task has any changes
that need to be propagated to the child task that has been created.

This is necessary to prevent the following race between task creation
and concurrent cancellation and escalation:

a. Parent task create child task. It does lazy relaxed loads on its own
   state while doing so and propagates this state to the child.
b. Child task is created but has not been attached to the parent
   task/task group.
c. Parent task gets cancelled by another thread.
d. Child task gets linked into the parent’s task status records but no
   reevaluation has happened to account for changes that might have happened to
   the parent after (a).

2. Move status record management functions from the
Runtime/Concurrency.h to TaskPrivate.h. Remove any corresponding
overrides that are no longer needed. Remove unused tryAddStatusRecord
method whose functionality is provided by addStatusRecordWithChecks.

Radar-Id: rdar://problem/86347801
2021-12-31 03:23:52 -08:00
Saleem Abdulrasool
d30e196c94 Concurrency: avoid unnecessary dependency on LLVMSupport
We do not have the `llvm/Config/config.h` header available in the forked
LLVMSupport library in our standard library packaging.  This removes
that dependency by using the standard macro `_POSIX_THREADS` to detect
if we should use pthreads.
2021-12-27 20:34:52 -08:00
Pavel Yaskevich
774622823c [Concurrency] Throwing continuation type should be typed as SwiftError 2021-12-22 15:00:49 -08:00
Konrad `ktoso` Malawski
a0693c4649 Merge pull request #40675 from xedin/fix-invalid-base-for-accessor-ref
[Distributed] Runtime: Fix retrieval of async pointer from incorrect …
2021-12-22 16:24:56 +09:00
Rokhini Prabhu
0f52bae8bc Merge pull request #40562 from apple/rokhinip/86346865-taskgroup-cancellAll-cancellationHandler
Cancellation of TaskGroup should not trigger cancel handler of parent task
2021-12-22 10:32:52 +08:00
Pavel Yaskevich
302b241625 [Distributed] Runtime: Fix retrieval of async pointer from incorrect base
`accessor` represents a record as a whole, which means that async pointer
to the entry point is located at `Function`.
2021-12-21 16:59:43 -08:00
Evan Wilde
1f198bcd93 Cleaning up _runAsyncMain a bit
I'm making two cleanups here. First, the closure going into
`_runAsyncMain` needs to be `@Sendable` or passing it to the task is not
safe. This will also result in a warning being emitted.
Second, I'm making this @usableFromInline and `internal`. This function
is around for legacy reasons, but it's part of the ABI, so we can't pull
it out entirely, but we don't want folks using it.
2021-12-21 11:42:09 -08:00
John McCall
5ce55f84a9 Rip out the concept of an "override job" from default actors.
This has been dead since before the first release.  We need something
like it, but we should probably do it on a clean foundation rather than
building on what's already there.

I've left the barest foundation for "messages" that can be dropped in
the queue but aren't real jobs.

I've left the barest skeleton for "messages" rather than
2021-12-20 18:04:19 -05:00
Šimon Javora
6c0c39ec44 [Docs] withCheckedThrowingContinuation body fix
`withCheckedThrowingContinuation`'s `body` says that it takes an `UnsafeContinuation`... seems like a copy/paste error.
2021-12-20 12:28:26 +01:00
Rokhini Prabhu
835f274183 Make sure that cancelling a task group does not invoke cancellation
handler of parent task that created the group

Change comment in TaskGroup.swift to enforce that only parent task can
call cancelAll on the group

Add tests to verify mutating of task group in child tasks will fail

Radar-Id: rdar://problem/86346865
2021-12-17 18:35:39 -08:00
Pavel Yaskevich
9965df76d0 Merge pull request #40270 from xedin/thunks-for-dist-methods
[Distributed] Implement distributed method accessors
2021-12-17 16:53:42 -08:00
Doug Gregor
c4e8844fdb Merge pull request #40616 from DougGregor/concurrency-sendable-frozen-types 2021-12-17 16:47:40 -08:00
Doug Gregor
400404cf3a Explicit Sendable conformances for @frozen types
Task groups and `UnsafeCurrentTask` are non-`Sendable`.
`UnownedSerialExecutor` is always `Sendable`.

Fixes rdar://86496341.
2021-12-17 11:10:29 -08:00
Pavel Yaskevich
111ceb189a [Distributed] IRGen: Adjust distributed method accessor to store result into a provided buffer
Instead of trying to return result from distributed thunk directly,
modify accessor to store result into the caller-provided buffer.
Doing so helps us avoid boxing the result into `Any`.
2021-12-17 10:52:56 -08:00
Pavel Yaskevich
ed97120d7c [Distributed] Runtime: Implement _executeDistributedTarget
The implementation is as follows:

- Looks up distributed accessor by the given target name
- Extracts information required to setup async context from
  async function pointer stored in accessor record
- Allocates context and calls accessor
2021-12-17 10:52:56 -08:00
Pavel Yaskevich
5af5501437 [Distributed] Runtime: Prototype executeDistributedTarget function 2021-12-17 10:52:56 -08:00
John McCall
9221fcec67 Fix priority inversions when waiting on a task status lock.
Since locking the task status is a presumed-uncommon case, the
trade-offs inherent in the allocation patterns of AtomicWaitQueue
are very appropriate here, even more than they are for metadata
completion.

rdar://86100232
2021-12-16 03:07:45 -05:00
Alastair Houghton
0e5a620917 Merge pull request #40331 from al45tair/problem/84393438
[Runtime] Don't use threading APIs when building single threaded.
2021-12-14 22:19:20 +00:00
Rokhini
cb17173c22 Merge pull request #40520 from apple/rokhinip/synchronize-group-child-creation-and-cancellation
Synchronize adding a child task to a TaskGroup with parent task's TaskStatusRecord lock
2021-12-15 05:45:37 +08:00
Rokhini
7200e0c913 Remove double-log
Co-authored-by: Konrad `ktoso` Malawski <ktoso@apple.com>
2021-12-14 10:28:36 +08:00
Rokhini Prabhu
4bcaa2e7d9 There is no inherent synchronization in the TaskGroupStatusRecord so
when a task is adding adding new children to a task group, we need to
synchronize with the task status record lock of the parent task that has the
task group, to prevent races with concurrent cancellation and escalation.

Radar-Id: rdar://problem/86311782
2021-12-10 20:17:24 -08:00
Pavel Yaskevich
be594749e7 Merge pull request #40495 from xedin/improvements-to-async-signature
[Concurrency/Runtime] Implement function/continuation type generation…
2021-12-10 09:30:54 -08:00
Pavel Yaskevich
9a00b33378 [Concurrency/Runtime] Implement function/continuation type generation for AsyncSignature
`AsyncFunctionTypeImpl` has its `type` defaulted to `TaskContinuationFunction`
which is incorrect because it has to append arguments, result type and account
for throws bit.

These changes expand `AsyncSignature` with `ContinuationType` and expand `FunctionType`
to include all of the appropriate information.
2021-12-09 16:52:53 -08:00
Alex Martini
5d6c179df1 Add missing 'else' to guard statements.
Fixes <rdar://84895831>.
2021-12-07 12:09:14 -08:00
najacque
57ad1f1c7d Merge pull request #40115 from amartini51/concurrency_docs_to_main
Cherry-pick concurrency docs
2021-12-07 11:59:56 -08:00
Berik Visschers
7fb3624ee7 Fix typo UnsafeContination -> UnsafeContinuation 2021-12-04 01:35:10 +01:00
Kuba (Brecka) Mracek
7e33575c6b Re-import LLVMSupport from llvm-project and enforce header includes only being used from the Swift fork when building stdlib (#40173)
* Enforce using headers from Swift's LLVMSupport fork and not llvm-project when building stdlib

* [LLVMSupport] Re-import LLVMSupport .cpp and .h files from 9ff3a9759b7c2f146e7f46e4aebc60453c577c5a from apple/llvm-project

Done via the following commands, while having llvm-project checked out at 9ff3a9759b7c2f146e7f46e4aebc60453c577c5a, a
commit on the stable/20210726 branch of apple/llvm-project, <9ff3a9759b>:

for i in swift/stdlib/public/LLVMSupport/*.cpp ; do cp llvm-project/llvm/lib/Support/$(basename $i) $i ; done
for i in swift/stdlib/include/llvm/ADT/*.h; do cp llvm-project/llvm/include/llvm/ADT/$(basename $i) $i ; done
for i in swift/stdlib/include/llvm/Support/*.h; do cp llvm-project/llvm/include/llvm/Support/$(basename $i) $i ; done
cp llvm-project/llvm/include/llvm/ADT/ScopeExit.h swift/stdlib/include/llvm/ADT/ScopeExit.h
cp llvm-project/llvm/include/llvm/ADT/Twine.h swift/stdlib/include/llvm/ADT/Twine.h
cp llvm-project/llvm/include/llvm/Support/raw_ostream.h swift/stdlib/include/llvm/Support/raw_ostream.h

* [LLVMSupport] Re-namespace the LLVMSupport fork after re-forking by re-applying b72788c27a

More precisely:

1) git cherry-pick b72788c27a
2) manually resolve the conflict in AlignOf.h by keeping the HEAD's version of the chunk and discarding the cherry-pick's change
3) git add AlignOf.h
4) git status | grep "deleted by us" | awk '{print($4)}' | xargs git rm
5) git cherry-pick --continue

Original namespacing commit message:

> This adds the `__swift::__runtime` inline namespace to the LLVMSupport
> interfaces.  This avoids an ODR violation when LLVM and Swift are in the
> same address space.  It also will aid in the process of pruning the
> LLVMSupport library by ensuring that accidental leakage of the llvm
> namespace does not allow us to remove symbols which we rely on.

* [LLVMSupport] Re-apply "pruning" on re-forked LLVMSupport from bb102707ed

This re-applies the "pruning" commit from bb102707ed, which did the following:
- Remove many whole files,
- Remove "epoch tracking" and "reverse iteration" support from ADT containers
- Remove "ABI break checking" support from STLExtras
- Remove float parsing functions from StringExtras.h
- Remove APInt/APSInt dependencies from StringRef.h + StringRef.cpp (edit distance, int parsing)
- Remove some variants of error handling and dependency of dbgs() from ErrorHandling.h and ErrorHandling.cpp

We don't need to do the whole-file-removal step, because that's already done, but the rest is re-applied by doing:

1) git cherry-pick bb102707ed
2) manually resolving conflict in ADT/DenseMap.h by keeping HEAD's version of the chunk and removing epoch tracking from it
3) manually resolving conflict in ADT/STLExtras.h by keeping HEAD's version of the chunk and removing ABI check checking from it
4) manually resolving conflict in ADT/StringExtras.h by deleting the whole chunk (removing APInt/APSInt dependent functions)
5) manually resolving conflict in ErrorHandling.cpp by force-applying the cherry-pick's version (removing write() calls and OOM callback)
6) manually resolving the three conflicts in CMakeLists.txt files by keeping HEAD's version completely
7) git add stdlib/include/llvm/{ADT/StringSwitch.h,ADT/Twine.h,Support/raw_ostream.h}

Original commit description:

> Reduce LLVMSupport to the subset required for the runtime.  This reduces
> the TCB and the overheads of the runtime.  The inline namespace's
> preservation ensures that ODR violations do not occur.

* [LLVMSupport] Re-apply all post-import modifications on LLVMSupport that the Swift's fork has

Since the previous commits re-imported "vanilla" versions of LLVMSupport, we need to re-apply all modifications that the Swift's fork has made since the last import. More precisely:

1) git diff 7b70120440cd39d67a595a7d0ea4e828ecc6ee44..origin/main -- stdlib/include/llvm stdlib/public/LLVMSupport | git apply -3 --exclude "stdlib/include/llvm/Support/DataTypes.h" --exclude "stdlib/include/llvm/Config/llvm-config.h.cmake"
2) manually resolve conflict in STLExtras.h by applying the "__swift::__runtime" prefix to HEAD's version
3) manually resolve conflicts in StringSwitch.h by keeping HEAD's version (removing the Unicode BOM marker at the beginning of the file, keeping LLVM's version of the string functions)
4) manually resolve conflict in SwapByteOrder.h by adding the `defined(__wasi__)` part into the #if

* [LLVMSupport] Drop remaining dependencies on APSInt.h, Error.h, DataTypes.h and STLForwardCompat.h

Most cases can drop the #includes without any changes, in some cases there are
straighforward replacements (climits, cstdint). For STLForwardCompat.h, we need
to bring in parts of STLForwardCompat.h from llvm-project.

* [LLVMSupport] Remove raw_ostream.h and drop dependencies to it from the runtime

* [LLVMSupport] Simplify error reporting in SmallVector and avoid using std::string when producing fatal errors messages

Co-authored-by: Saleem Abdulrasool <compnerd@compnerd.org>
2021-12-02 17:21:51 -08:00
Alastair Houghton
e08fd330f1 [Runtime] Tidy up locking/unlocking conditionals.
Rather than conditionalising all the calls to mutex.lock() and mutex.unlock(),
centralise the logic.

rdar://84393438
2021-12-02 15:02:06 +00:00
swift-ci
83e3ae8111 Merge pull request #40265 from mikeash/task-id-64-bit 2021-12-01 10:37:36 -08:00
Saleem Abdulrasool
de1c3e6580 Concurrency: report errors on failures on Windows
The usage of libdispatch in Concurrency is dynamic - it does not
explicitly link against libdispatch and thus cannot directly invoke
`dispatch_main`.  While linking against dispatch would be ideal, this
should improve the current path.
2021-11-30 08:19:53 -08:00
Alastair Houghton
2d335062e2 [Runtime] Don't use threading related APIs when building single threaded.
Mostly this consists of #if-ing out code that we don't need when running
single threaded.

rdar://84393438
2021-11-30 16:18:26 +00:00
Saleem Abdulrasool
910fbee14e gardening: make c++98-compat-extra-semi an error
This cleans up 90 instances of this warning and reduces the build spew
when building on Linux.  This helps identify actual issues when
building which can get lost in the stream of warning messages.  It also
helps restore the ability to build the compiler with gcc.
2021-11-27 11:40:17 -08:00
Mike Ash
bac6965946 [Concurrency] Make task IDs 64-bit.
The 32-bit identifier in Job is locked down at this point, so we expand the ID by storing the top 32 bits separately inside AsyncTask::PrivateStorage.

rdar://85167409
2021-11-19 15:24:35 -05:00
Saleem Abdulrasool
306662fd29 Concurrency: fix UB in DefaultActor initialization
This fixes a latent UB instance in the `DefaultActor` implementation
that has haunted the Windows target.  The shared constructor for the
type caused an errant typo that happened to compile which introduced
UB but happened to work for the non-Windows cases.  This happened to
work for the other targets as `swift::atomic` had a `std::atomic` at
on most configurations, and the C delegate for the Actor initializer
happened to overlap and initialize the memory properly.  The Windows
case used an inline pointer width value but would be attempted to be
initialized as a `std::atomic`.  Relying on the overlap is unsafe to
assume, and we should use the type's own constructor which delegates
appropriately.
2021-11-19 10:34:41 -08:00
swift-ci
37ea254cc1 Merge pull request #40220 from DougGregor/predates-concurrency 2021-11-19 01:14:42 -08:00
swift-ci
a41f1b0b58 Merge pull request #40252 from kavon/main-taskgroup-bug 2021-11-18 19:59:12 -08:00
Kavon Farvardin
69e80a1201 use compare_exchange_strong to protect agianst spurious failures
A `compare_exchange_weak` can spuriously return false, regardless of
whether a concurrent access happened. This was causing a null-pointer
dereference in TaskGroupImpl::poll in a narrow circumstance.

The dereference failure only appears when using the `arm64`
slice of the runtime library, since Clang will use `ldxr/stxr` for
synchronization on such targets. The weak form does not retry on a
spurious failure, but the strong version will.

resolves rdar://84192672
2021-11-18 16:37:04 -08:00
Doug Gregor
089cc4f101 Remove last use of @_unsafeSendable in the concurrency library 2021-11-18 11:20:53 -08:00
Mike Ash
cf3c131e7c [Reflection] Add API for inspecting async task allocation slabs.
We remove the existing `swift_reflection_iterateAsyncTaskAllocations` API that attempts to provide all necessary information about a tasks's allocations starting from the task. Instead, we split it into two pieces: `swift_reflection_asyncTaskSlabPointer` to get the first slab for a task, and `+swift_reflection_asyncTaskSlabAllocations` to get the allocations in a slab, and a pointer to the next slab.

We also add a dummy metadata pointer to the beginning of each slab. This allows tools to identify slab allocations on the heap without needing to locate every single async task object. They can then use `swift_reflection_asyncTaskSlabAllocations` on such allocations to find out about the contents.

rdar://82549631
2021-11-18 14:15:25 -05:00
Evan Wilde
05fa143a88 Merge pull request #40221 from etcwilde/ewilde/include-missing-api-in-swinterface
Include missing `_getMainExecutor` and `_asyncMainDrainQueue` in concurrency swiftinterface
2021-11-18 09:48:15 -08:00
John McCall
84623ceac4 Teach default actors to execute jobs in priority order.
rdar://76473589
2021-11-18 00:32:58 -05:00
Evan Wilde
1c852f9179 Adding @usableFromInline to needed API
getMainExecutor and asyncMainDrainQueue function declarations are needed
to compile programs with the asyn-main function. The functions are
declared internal, so they don't show up in the swift interface files.
2021-11-16 21:36:58 -08:00
John McCall
26ea1fe6e9 Miscellaneous improvements to the cooperative executor:
- Switch to using ListMerger for priority insertion.
- Move ready delayed jobs to the back to the queue instead of
  running them immediately, before anything currently in the queue.
- Respect priorities in delayed jobs.
- Use the proper std::chrono facilities for managing deadlines
  instead of doing all the math on nanoseconds since the epoch.
- Take advantage of the second word of queue-private storage to
  avoid allocating a separate job when a deadline fits there.
2021-11-16 03:21:49 -05:00
John McCall
c45f2c4334 [NFC] Introduce a typedef for job delay in nanoseconds. 2021-11-16 01:50:52 -05:00
swift-ci
4fbf7a5d55 Merge pull request #40192 from DougGregor/unchecked-continuation-conditional-sendable 2021-11-15 19:15:13 -08:00
Doug Gregor
5a99ae485e Make (Unsafe|Checked)Continuation's Sendable conformance conditional.
Make the continuation type's conformances to the `Sendable` protocol
conditional on the sendability of the result yielded when the
resumption is performed. This ensures that one cannot silently escape
a continuation's result out of a task or actor, closing a safety hole
in Sendable checking.

Fixes rdar://85419546.
2021-11-15 16:41:07 -08:00
John McCall
0bd0f772d8 NFC: move the global executor implementations into their own files 2021-11-15 18:29:08 -05:00