-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathTask.cpp
1910 lines (1639 loc) · 70 KB
/
Task.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- Task.cpp - Task object and management ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Object management routines for asynchronous task objects.
//
//===----------------------------------------------------------------------===//
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#endif
#include "../CompatibilityOverride/CompatibilityOverride.h"
#include "Debug.h"
#include "Error.h"
#include "TaskGroupPrivate.h"
#include "TaskLocal.h"
#include "TaskPrivate.h"
#include "Tracing.h"
#include "swift/ABI/Metadata.h"
#include "swift/ABI/Task.h"
#include "swift/ABI/TaskOptions.h"
#include "swift/Basic/Casting.h"
#include "swift/Basic/Lazy.h"
#include "swift/Runtime/Concurrency.h"
#include "swift/Runtime/EnvironmentVariables.h"
#include "swift/Runtime/HeapObject.h"
#include "swift/Runtime/Heap.h"
#include "swift/Threading/Mutex.h"
#include <atomic>
#include <new>
#include <unordered_set>
#if SWIFT_CONCURRENCY_ENABLE_DISPATCH
#include <dispatch/dispatch.h>
#endif
#if !defined(_WIN32) && !defined(__wasi__) && __has_include(<dlfcn.h>)
#include <dlfcn.h>
#endif
#if defined(SWIFT_CONCURRENCY_BACK_DEPLOYMENT)
#include <Availability.h>
#include <TargetConditionals.h>
#if TARGET_OS_WATCH
// Bitcode compilation for the watch device precludes defining the following asm
// symbols, so we don't use them... but simulators are okay.
#if TARGET_OS_SIMULATOR
asm("\n .globl _swift_async_extendedFramePointerFlags" \
"\n _swift_async_extendedFramePointerFlags = 0x0");
#endif
#else
asm("\n .globl _swift_async_extendedFramePointerFlags" \
"\n _swift_async_extendedFramePointerFlags = 0x0");
#endif
#else
#ifdef __APPLE__
#if __POINTER_WIDTH__ == 64
asm("\n .globl _swift_async_extendedFramePointerFlags" \
"\n _swift_async_extendedFramePointerFlags = 0x1000000000000000");
#elif __ARM64_ARCH_8_32__
asm("\n .globl _swift_async_extendedFramePointerFlags" \
"\n _swift_async_extendedFramePointerFlags = 0x10000000");
#else
asm("\n .globl _swift_async_extendedFramePointerFlags" \
"\n _swift_async_extendedFramePointerFlags = 0x0");
#endif
#endif // __APPLE__
#endif // !defined(SWIFT_CONCURRENCY_BACK_DEPLOYMENT)
using namespace swift;
using FutureFragment = AsyncTask::FutureFragment;
using TaskGroup = swift::TaskGroup;
Metadata swift::TaskAllocatorSlabMetadata;
const void *const swift::_swift_concurrency_debug_asyncTaskSlabMetadata =
&TaskAllocatorSlabMetadata;
bool swift::_swift_concurrency_debug_supportsPriorityEscalation =
SWIFT_CONCURRENCY_ENABLE_PRIORITY_ESCALATION;
uint32_t swift::_swift_concurrency_debug_internal_layout_version = 1;
void FutureFragment::destroy() {
auto queueHead = waitQueue.load(std::memory_order_acquire);
switch (queueHead.getStatus()) {
case Status::Executing:
swift_unreachable("destroying a task that never completed");
case Status::Success:
resultType.vw_destroy(getStoragePtr());
break;
case Status::Error:
#if SWIFT_CONCURRENCY_EMBEDDED
swift_unreachable("untyped error used in embedded Swift");
#else
swift_errorRelease(getError());
#endif
break;
}
}
FutureFragment::Status AsyncTask::waitFuture(AsyncTask *waitingTask,
AsyncContext *waitingTaskContext,
TaskContinuationFunction *resumeFn,
AsyncContext *callerContext,
OpaqueValue *result) {
using Status = FutureFragment::Status;
using WaitQueueItem = FutureFragment::WaitQueueItem;
assert(isFuture());
auto fragment = futureFragment();
// NOTE: this acquire synchronizes with `completeFuture`.
auto queueHead = fragment->waitQueue.load(std::memory_order_acquire);
bool contextInitialized = false;
while (true) {
switch (queueHead.getStatus()) {
case Status::Error:
case Status::Success:
SWIFT_TASK_DEBUG_LOG("task %p waiting on task %p, completed immediately",
waitingTask, this);
_swift_tsan_acquire(static_cast<Job *>(this));
if (contextInitialized) waitingTask->flagAsRunning();
// The task is done; we don't need to wait.
return queueHead.getStatus();
case Status::Executing:
SWIFT_TASK_DEBUG_LOG("task %p waiting on task %p, going to sleep",
waitingTask, this);
_swift_tsan_release(static_cast<Job *>(waitingTask));
concurrency::trace::task_wait(
waitingTask, this, static_cast<uintptr_t>(queueHead.getStatus()));
// Task is not complete. We'll need to add ourselves to the queue.
break;
}
if (!contextInitialized) {
contextInitialized = true;
auto context =
reinterpret_cast<TaskFutureWaitAsyncContext *>(waitingTaskContext);
context->errorResult = nullptr;
context->successResultPointer = result;
context->ResumeParent = resumeFn;
context->Parent = callerContext;
waitingTask->flagAsSuspendedOnTask(this);
}
#if SWIFT_CONCURRENCY_TASK_TO_THREAD_MODEL
// In the task to thread model, we will execute the task that we are waiting
// on, on the current thread itself. As a result, do not bother adding the
// waitingTask to any thread queue. Instead, we will clear the old task, run
// the new one and then reattempt to continue running the old task
auto oldTask = _swift_task_clearCurrent();
assert(oldTask == waitingTask);
SWIFT_TASK_DEBUG_LOG("[RunInline] Switching away from running %p to now running %p", oldTask, this);
// Run the new task on the same thread now - this should run the new task to
// completion. All swift tasks in task-to-thread model run on generic
// executor
swift_job_run(this, SerialExecutorRef::generic());
SWIFT_TASK_DEBUG_LOG("[RunInline] Switching back from running %p to now running %p", this, oldTask);
// We now are back in the context of the waiting task and need to reevaluate
// our state
_swift_task_setCurrent(oldTask);
queueHead = fragment->waitQueue.load(std::memory_order_acquire);
continue;
#else
// Put the waiting task at the beginning of the wait queue.
// NOTE: this acquire-release synchronizes with `completeFuture`.
waitingTask->getNextWaitingTask() = queueHead.getTask();
auto newQueueHead = WaitQueueItem::get(Status::Executing, waitingTask);
if (fragment->waitQueue.compare_exchange_weak(
queueHead, newQueueHead,
/*success*/ std::memory_order_release,
/*failure*/ std::memory_order_acquire)) {
_swift_task_clearCurrent();
return FutureFragment::Status::Executing;
}
#endif /* SWIFT_CONCURRENCY_TASK_TO_THREAD_MODEL */
}
}
// Implemented in Swift because we need to obtain the user-defined flags on the executor ref.
//
// We could inline this with effort, though.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
extern "C" SWIFT_CC(swift)
TaskExecutorRef _task_taskExecutor_getTaskExecutorRef(
HeapObject *executor, const Metadata *selfType,
const TaskExecutorWitnessTable *wtable);
#pragma clang diagnostic pop
TaskExecutorRef
InitialTaskExecutorOwnedPreferenceTaskOptionRecord::getExecutorRefFromUnownedTaskExecutor() const {
if (!Identity) return TaskExecutorRef::undefined();
TaskExecutorRef executorRef = _task_taskExecutor_getTaskExecutorRef(
Identity,
/*selfType=*/swift_getObjectType(Identity),
/*wtable=*/WitnessTable);
return executorRef;
}
void NullaryContinuationJob::process(Job *_job) {
auto *job = cast<NullaryContinuationJob>(_job);
auto *continuation = job->Continuation;
swift_cxx_deleteObject(job);
auto *context =
static_cast<ContinuationAsyncContext*>(continuation->ResumeContext);
context->setErrorResult(nullptr);
swift_continuation_resume(continuation);
}
void AsyncTask::completeFuture(AsyncContext *context) {
using Status = FutureFragment::Status;
using WaitQueueItem = FutureFragment::WaitQueueItem;
SWIFT_TASK_DEBUG_LOG("complete future = %p", this);
assert(isFuture());
auto fragment = futureFragment();
// If an error was thrown, save it in the future fragment.
auto asyncContextPrefix = reinterpret_cast<FutureAsyncContextPrefix *>(
reinterpret_cast<char *>(context) - sizeof(FutureAsyncContextPrefix));
bool hadErrorResult = false;
auto errorObject = asyncContextPrefix->errorResult;
fragment->getError() = errorObject;
if (errorObject) {
hadErrorResult = true;
}
_swift_tsan_release(static_cast<Job *>(this));
// Update the status to signal completion.
auto newQueueHead = WaitQueueItem::get(
hadErrorResult ? Status::Error : Status::Success,
nullptr
);
// NOTE: this acquire-release synchronizes with `waitFuture`.
auto queueHead = fragment->waitQueue.exchange(
newQueueHead, std::memory_order_acq_rel);
assert(queueHead.getStatus() == Status::Executing);
// If this is task group child, notify the parent group about the completion.
if (hasGroupChildFragment()) {
// then we must offer into the parent group that we completed,
// so it may `next()` poll completed child tasks in completion order.
auto group = groupChildFragment()->getGroup();
group->offer(this, context);
}
// Schedule every waiting task on the executor.
auto waitingTask = queueHead.getTask();
if (!waitingTask) {
SWIFT_TASK_DEBUG_LOG("task %p had no waiting tasks", this);
} else {
#if SWIFT_CONCURRENCY_TASK_TO_THREAD_MODEL
assert(false && "Task should have no waiters in task-to-thread model");
#endif
}
while (waitingTask) {
// Find the next waiting task before we invalidate it by resuming
// the task.
auto nextWaitingTask = waitingTask->getNextWaitingTask();
SWIFT_TASK_DEBUG_LOG("waking task %p from future of task %p", waitingTask,
this);
// Fill in the return context.
auto waitingContext =
static_cast<TaskFutureWaitAsyncContext *>(waitingTask->ResumeContext);
if (hadErrorResult) {
#if SWIFT_CONCURRENCY_EMBEDDED
swift_unreachable("untyped error used in embedded Swift");
#else
waitingContext->fillWithError(fragment);
#endif
} else {
waitingContext->fillWithSuccess(fragment);
}
_swift_tsan_acquire(static_cast<Job *>(waitingTask));
concurrency::trace::task_resume(waitingTask);
// Enqueue the waiter on the global executor.
// TODO: allow waiters to fill in a suggested executor
waitingTask->flagAsAndEnqueueOnExecutor(SerialExecutorRef::generic());
// Move to the next task.
waitingTask = nextWaitingTask;
}
}
SWIFT_CC(swift)
static void destroyJob(SWIFT_CONTEXT HeapObject *obj) {
assert(false && "A non-task job should never be destroyed as heap metadata.");
}
AsyncTask::~AsyncTask() {
flagAsDestroyed();
// For a future, destroy the result.
if (isFuture()) {
futureFragment()->destroy();
}
Private.destroy();
concurrency::trace::task_destroy(this);
}
void AsyncTask::setTaskId() {
static std::atomic<uint64_t> NextId(1);
// We want the 32-bit Job::Id to be non-zero, so loop if we happen upon zero.
uint64_t Fetched;
do {
Fetched = NextId.fetch_add(1, std::memory_order_relaxed);
Id = Fetched & 0xffffffff;
} while (Id == 0);
_private().Id = (Fetched >> 32) & 0xffffffff;
}
uint64_t AsyncTask::getTaskId() {
// Reconstitute a full 64-bit task ID from the 32-bit job ID and the upper
// 32 bits held in _private().
return ((uint64_t)_private().Id << 32) | (uint64_t)Id;
}
SWIFT_CC(swift)
static void destroyTask(SWIFT_CONTEXT HeapObject *obj) {
auto task = static_cast<AsyncTask*>(obj);
task->~AsyncTask();
// The task execution itself should always hold a reference to it, so
// if we get here, we know the task has finished running, which means
// swift_task_complete should have been run, which will have torn down
// the task-local allocator. There's actually nothing else to clean up
// here.
SWIFT_TASK_DEBUG_LOG("Destroyed task %p", task);
free(task);
}
#if !SWIFT_CONCURRENCY_EMBEDDED
static SerialExecutorRef executorForEnqueuedJob(Job *job) {
#if !SWIFT_CONCURRENCY_ENABLE_DISPATCH
return SerialExecutorRef::generic();
#else
void *jobQueue = job->SchedulerPrivate[Job::DispatchQueueIndex];
if (jobQueue == DISPATCH_QUEUE_GLOBAL_EXECUTOR) {
return SerialExecutorRef::generic();
}
if (jobQueue == (void *)dispatch_get_main_queue()) {
return swift_task_getMainExecutor();
}
return SerialExecutorRef::generic();
#endif
}
static void jobInvoke(void *obj, void *unused, uint32_t flags) {
(void)unused;
Job *job = reinterpret_cast<Job *>(obj);
swift_job_run(job, executorForEnqueuedJob(job));
}
// Magic constant to identify Swift Job vtables to Dispatch.
static const unsigned long dispatchSwiftObjectType = 1;
static FullMetadata<DispatchClassMetadata> jobHeapMetadata = {
{
{
/*type layout*/ nullptr,
},
{
&destroyJob
},
{
/*value witness table*/ nullptr
}
},
{
MetadataKind::Job,
dispatchSwiftObjectType,
jobInvoke
}
};
/// Heap metadata for an asynchronous task.
static FullMetadata<DispatchClassMetadata> taskHeapMetadata = {
{
{
/*type layout*/ nullptr
},
{
&destroyTask
},
{
/*value witness table*/ nullptr
}
},
{
MetadataKind::Task,
dispatchSwiftObjectType,
jobInvoke
}
};
const void *const swift::_swift_concurrency_debug_jobMetadata =
static_cast<Metadata *>(&jobHeapMetadata);
const void *const swift::_swift_concurrency_debug_asyncTaskMetadata =
static_cast<Metadata *>(&taskHeapMetadata);
const size_t swift::_swift_concurrency_debug_asyncTaskSize = sizeof(AsyncTask);
const HeapMetadata *swift::jobHeapMetadataPtr =
static_cast<HeapMetadata *>(&jobHeapMetadata);
const HeapMetadata *swift::taskHeapMetadataPtr =
static_cast<HeapMetadata *>(&taskHeapMetadata);
#else // SWIFT_CONCURRENCY_EMBEDDED
// This matches the embedded class metadata layout in IRGen and in
// EmbeddedRuntime.swift.
typedef struct EmbeddedClassMetadata {
void *superclass;
HeapObjectDestroyer *__ptrauth_swift_heap_object_destructor destroy;
void *ivar_destroyer;
} EmbeddedHeapObject;
static EmbeddedClassMetadata jobHeapMetadata = {
0, &destroyJob, 0,
};
static EmbeddedClassMetadata taskHeapMetadata = {
0, &destroyTask, 0,
};
const void *const swift::_swift_concurrency_debug_jobMetadata =
(Metadata *)(&jobHeapMetadata);
const void *const swift::_swift_concurrency_debug_asyncTaskMetadata =
(Metadata *)(&taskHeapMetadata);
const HeapMetadata *swift::jobHeapMetadataPtr =
(HeapMetadata *)(&jobHeapMetadata);
const HeapMetadata *swift::taskHeapMetadataPtr =
(HeapMetadata *)(&taskHeapMetadata);
#endif
static void completeTaskImpl(AsyncTask *task,
AsyncContext *context,
SwiftError *error) {
assert(task && "completing task, but there is no active task registered");
// Store the error result.
auto asyncContextPrefix = reinterpret_cast<AsyncContextPrefix *>(
reinterpret_cast<char *>(context) - sizeof(AsyncContextPrefix));
asyncContextPrefix->errorResult = error;
task->Private.complete(task);
SWIFT_TASK_DEBUG_LOG("task %p completed", task);
// Complete the future.
// Warning: This deallocates the task in case it's an async let task.
// The task must not be accessed afterwards.
if (task->isFuture()) {
task->completeFuture(context);
}
// TODO: set something in the status?
// if (task->hasChildFragment()) {
// TODO: notify the parent somehow?
// TODO: remove this task from the child-task chain?
// }
}
/// The function that we put in the context of a simple task
/// to handle the final return.
SWIFT_CC(swiftasync)
static void completeTask(SWIFT_ASYNC_CONTEXT AsyncContext *context,
SWIFT_CONTEXT SwiftError *error) {
// Set that there's no longer a running task in the current thread.
auto task = _swift_task_clearCurrent();
assert(task && "completing task, but there is no active task registered");
completeTaskImpl(task, context, error);
}
/// The function that we put in the context of a simple task
/// to handle the final return.
SWIFT_CC(swiftasync)
static void completeTaskAndRelease(SWIFT_ASYNC_CONTEXT AsyncContext *context,
SWIFT_CONTEXT SwiftError *error) {
// Set that there's no longer a running task in the current thread.
auto task = _swift_task_clearCurrent();
assert(task && "completing task, but there is no active task registered");
completeTaskImpl(task, context, error);
// Release the task, balancing the retain that a running task has on itself.
// If it was a group child task, it will remain until the group returns it.
swift_release(task);
}
/// The function that we put in the context of a simple task
/// to handle the final return from a closure.
SWIFT_CC(swiftasync)
static void completeTaskWithClosure(SWIFT_ASYNC_CONTEXT AsyncContext *context,
SWIFT_CONTEXT SwiftError *error) {
// Release the closure context.
auto asyncContextPrefix = reinterpret_cast<AsyncContextPrefix *>(
reinterpret_cast<char *>(context) - sizeof(AsyncContextPrefix));
swift_release((HeapObject *)asyncContextPrefix->closureContext);
// Clean up the rest of the task.
return completeTaskAndRelease(context, error);
}
/// The function that we put in the context of an inline task to handle the
/// final return.
///
/// Because inline tasks can't produce errors, this function doesn't have an
/// error parameter.
///
/// Because inline tasks' closures are noescaping, their closure contexts are
/// stack allocated; so this function doesn't release them.
SWIFT_CC(swiftasync)
static void completeInlineTask(SWIFT_ASYNC_CONTEXT AsyncContext *context) {
// Set that there's no longer a running task in the current thread.
auto task = _swift_task_clearCurrent();
assert(task && "completing task, but there is no active task registered");
completeTaskImpl(task, context, /*error=*/nullptr);
}
SWIFT_CC(swiftasync)
static void non_future_adapter(SWIFT_ASYNC_CONTEXT AsyncContext *_context) {
auto asyncContextPrefix = reinterpret_cast<AsyncContextPrefix *>(
reinterpret_cast<char *>(_context) - sizeof(AsyncContextPrefix));
return asyncContextPrefix->asyncEntryPoint(
_context, asyncContextPrefix->closureContext);
}
SWIFT_CC(swiftasync)
static void future_adapter(SWIFT_ASYNC_CONTEXT AsyncContext *_context) {
auto asyncContextPrefix = reinterpret_cast<FutureAsyncContextPrefix *>(
reinterpret_cast<char *>(_context) - sizeof(FutureAsyncContextPrefix));
return asyncContextPrefix->asyncEntryPoint(
asyncContextPrefix->indirectResult, _context,
asyncContextPrefix->closureContext);
}
SWIFT_CC(swiftasync)
static void task_wait_throwing_resume_adapter(SWIFT_ASYNC_CONTEXT AsyncContext *_context) {
auto context = static_cast<TaskFutureWaitAsyncContext *>(_context);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-function-type-mismatch"
auto resumeWithError =
reinterpret_cast<AsyncVoidClosureEntryPoint *>(context->ResumeParent);
#pragma clang diagnostic pop
return resumeWithError(context->Parent, context->errorResult);
}
SWIFT_CC(swiftasync)
static void
task_future_wait_resume_adapter(SWIFT_ASYNC_CONTEXT AsyncContext *_context) {
return _context->ResumeParent(_context->Parent);
}
const void *const swift::_swift_concurrency_debug_non_future_adapter =
reinterpret_cast<void *>(non_future_adapter);
const void *const swift::_swift_concurrency_debug_future_adapter =
reinterpret_cast<void *>(future_adapter);
const void
*const swift::_swift_concurrency_debug_task_wait_throwing_resume_adapter =
reinterpret_cast<void *>(task_wait_throwing_resume_adapter);
const void
*const swift::_swift_concurrency_debug_task_future_wait_resume_adapter =
reinterpret_cast<void *>(task_future_wait_resume_adapter);
const void *AsyncTask::getResumeFunctionForLogging(bool isStarting) {
const void *result = reinterpret_cast<const void *>(ResumeTask);
if (ResumeTask == non_future_adapter) {
auto asyncContextPrefix = reinterpret_cast<AsyncContextPrefix *>(
reinterpret_cast<char *>(ResumeContext) - sizeof(AsyncContextPrefix));
result =
reinterpret_cast<const void *>(asyncContextPrefix->asyncEntryPoint);
} else if (ResumeTask == future_adapter) {
auto asyncContextPrefix = reinterpret_cast<FutureAsyncContextPrefix *>(
reinterpret_cast<char *>(ResumeContext) -
sizeof(FutureAsyncContextPrefix));
result =
reinterpret_cast<const void *>(asyncContextPrefix->asyncEntryPoint);
}
// Future contexts may not be valid if the task was already running before.
if (isStarting) {
if (ResumeTask == task_wait_throwing_resume_adapter) {
auto context = static_cast<TaskFutureWaitAsyncContext *>(ResumeContext);
result = reinterpret_cast<const void *>(context->ResumeParent);
} else if (ResumeTask == task_future_wait_resume_adapter) {
result = reinterpret_cast<const void *>(ResumeContext->ResumeParent);
}
}
return __ptrauth_swift_runtime_function_entry_strip(result);
}
JobPriority swift::swift_task_currentPriority(AsyncTask *task) {
// This is racey but this is to be used in an API is inherently racey anyways.
auto oldStatus = task->_private()._status().load(std::memory_order_relaxed);
return oldStatus.getStoredPriority();
}
JobPriority swift::swift_task_basePriority(AsyncTask *task) {
JobPriority pri = task->_private().BasePriority;
SWIFT_TASK_DEBUG_LOG("Task %p has base priority = %zu", task, pri);
return pri;
}
JobPriority swift::swift_concurrency_jobPriority(Job *job) {
return job->getPriority();
}
static inline bool isUnspecified(JobPriority priority) {
return priority == JobPriority::Unspecified;
}
static inline bool taskIsStructured(JobFlags jobFlags) {
return jobFlags.task_isAsyncLetTask() || jobFlags.task_isGroupChildTask();
}
static inline bool taskIsUnstructured(TaskCreateFlags createFlags, JobFlags jobFlags) {
return !taskIsStructured(jobFlags) && !createFlags.isInlineTask();
}
static inline bool taskIsDetached(TaskCreateFlags createFlags, JobFlags jobFlags) {
return taskIsUnstructured(createFlags, jobFlags) && !createFlags.copyTaskLocals();
}
static std::pair<size_t, size_t> amountToAllocateForHeaderAndTask(
const AsyncTask *parent, const TaskGroup *group,
ResultTypeInfo futureResultType, size_t initialContextSize) {
// Figure out the size of the header.
size_t headerSize = sizeof(AsyncTask);
if (parent) {
headerSize += sizeof(AsyncTask::ChildFragment);
}
if (group) {
headerSize += sizeof(AsyncTask::GroupChildFragment);
}
if (!futureResultType.isNull()) {
headerSize += FutureFragment::fragmentSize(headerSize, futureResultType);
// Add the future async context prefix.
headerSize += sizeof(FutureAsyncContextPrefix);
} else {
// Add the async context prefix.
headerSize += sizeof(AsyncContextPrefix);
}
headerSize = llvm::alignTo(headerSize, llvm::Align(alignof(AsyncContext)));
// Allocate the initial context together with the job.
// This means that we never get rid of this allocation.
size_t amountToAllocate = headerSize + initialContextSize;
assert(amountToAllocate % MaximumAlignment == 0);
return {headerSize, amountToAllocate};
}
/// Implementation of task creation.
SWIFT_CC(swift)
static AsyncTaskAndContext
swift_task_create_commonImpl(size_t rawTaskCreateFlags,
TaskOptionRecord *options,
const Metadata *futureResultTypeMetadata,
TaskContinuationFunction *function,
void *closureContext, size_t initialContextSize) {
TaskCreateFlags taskCreateFlags(rawTaskCreateFlags);
JobFlags jobFlags(JobKind::Task, JobPriority::Unspecified);
// Propagate task-creation flags to job flags as appropriate.
jobFlags.task_setIsChildTask(taskCreateFlags.isChildTask());
ResultTypeInfo futureResultType;
#if !SWIFT_CONCURRENCY_EMBEDDED
futureResultType.metadata = futureResultTypeMetadata;
#endif
// Collect the options we know about.
SerialExecutorRef serialExecutor = SerialExecutorRef::generic();
TaskExecutorRef taskExecutor = TaskExecutorRef::undefined();
const char* taskName = nullptr;
bool taskExecutorIsOwned = false;
TaskGroup *group = nullptr;
AsyncLet *asyncLet = nullptr;
bool hasAsyncLetResultBuffer = false;
RunInlineTaskOptionRecord *runInlineOption = nullptr;
for (auto option = options; option; option = option->getParent()) {
switch (option->getKind()) {
case TaskOptionRecordKind::InitialSerialExecutor:
serialExecutor = cast<InitialSerialExecutorTaskOptionRecord>(option)
->getExecutorRef();
break;
case TaskOptionRecordKind::InitialTaskExecutorUnowned:
taskExecutor = cast<InitialTaskExecutorRefPreferenceTaskOptionRecord>(option)
->getExecutorRef();
taskExecutorIsOwned = false;
jobFlags.task_setHasInitialTaskExecutorPreference(true);
break;
case TaskOptionRecordKind::InitialTaskExecutorOwned:
#if SWIFT_CONCURRENCY_EMBEDDED
swift_unreachable("owned TaskExecutor cannot be used in embedded Swift");
#else
taskExecutor = cast<InitialTaskExecutorOwnedPreferenceTaskOptionRecord>(option)
->getExecutorRefFromUnownedTaskExecutor();
taskExecutorIsOwned = true;
jobFlags.task_setHasInitialTaskExecutorPreference(true);
#endif
break;
case TaskOptionRecordKind::InitialTaskName:
taskName = cast<InitialTaskNameTaskOptionRecord>(option)
->getTaskName();
jobFlags.task_setHasInitialTaskName(true);
break;
case TaskOptionRecordKind::TaskGroup:
group = cast<TaskGroupTaskOptionRecord>(option)->getGroup();
assert(group && "Missing group");
jobFlags.task_setIsGroupChildTask(true);
break;
case TaskOptionRecordKind::AsyncLet:
asyncLet = cast<AsyncLetTaskOptionRecord>(option)->getAsyncLet();
assert(asyncLet && "Missing async let storage");
jobFlags.task_setIsAsyncLetTask(true);
jobFlags.task_setIsChildTask(true);
break;
case TaskOptionRecordKind::AsyncLetWithBuffer: {
auto *aletRecord = cast<AsyncLetWithBufferTaskOptionRecord>(option);
asyncLet = aletRecord->getAsyncLet();
// TODO: Actually digest the result buffer into the async let task
// context, so that we can emplace the eventual result there instead
// of in a FutureFragment.
hasAsyncLetResultBuffer = true;
assert(asyncLet && "Missing async let storage");
jobFlags.task_setIsAsyncLetTask(true);
jobFlags.task_setIsChildTask(true);
break;
}
case TaskOptionRecordKind::RunInline: {
runInlineOption = cast<RunInlineTaskOptionRecord>(option);
// TODO (rokhinip): We seem to be creating runInline tasks like detached
// tasks but they need to maintain the voucher and priority of calling
// thread and therefore need to behave a bit more like SC child tasks.
break;
}
case TaskOptionRecordKind::ResultTypeInfo: {
#if SWIFT_CONCURRENCY_EMBEDDED
auto *typeInfo = cast<ResultTypeInfoTaskOptionRecord>(option);
futureResultType = {
.size = typeInfo->size,
.alignMask = typeInfo->alignMask,
.initializeWithCopy = typeInfo->initializeWithCopy,
.storeEnumTagSinglePayload = typeInfo->storeEnumTagSinglePayload,
.destroy = typeInfo->destroy,
};
break;
#else
swift_unreachable("ResultTypeInfo in non-embedded");
#endif
}
}
}
#if SWIFT_CONCURRENCY_EMBEDDED
assert(!futureResultType.isNull());
#endif
if (!futureResultType.isNull()) {
jobFlags.task_setIsFuture(true);
assert(initialContextSize >= sizeof(FutureAsyncContext));
}
AsyncTask *currentTask = swift_task_getCurrent();
AsyncTask *parent = jobFlags.task_isChildTask() ? currentTask : nullptr;
if (group) {
assert(parent && "a task created in a group must be a child task");
// Add to the task group, if requested.
if (taskCreateFlags.addPendingGroupTaskUnconditionally()) {
assert(group && "Missing group");
swift_taskGroup_addPending(group, /*unconditionally=*/true);
}
}
// Start with user specified priority at creation time (if any)
JobPriority basePriority = (taskCreateFlags.getRequestedPriority());
if (taskCreateFlags.isInlineTask()) {
SWIFT_TASK_DEBUG_LOG("Creating an inline task from %p", currentTask);
// We'll take the current priority and set it as base and escalated
// priority of the task. No UI->IN downgrade needed.
basePriority = swift_task_getCurrentThreadPriority();
} else if (taskIsDetached(taskCreateFlags, jobFlags)) {
SWIFT_TASK_DEBUG_LOG("Creating a detached task from %p", currentTask);
// Case 1: No priority specified
// Base priority = UN
// Escalated priority = UN
// Case 2: Priority specified
// Base priority = user specified priority
// Escalated priority = UN
//
// Task will be created with max priority = max(base priority, UN) = base
// priority. We shouldn't need to do any additional manipulations here since
// basePriority should already be the right value
} else if (taskIsUnstructured(taskCreateFlags, jobFlags)) {
SWIFT_TASK_DEBUG_LOG("Creating an unstructured task from %p%s", currentTask,
taskCreateFlags.isSynchronousStartTask() ? " [start synchronously]" : "");
if (isUnspecified(basePriority)) {
// Case 1: No priority specified
// Base priority = Base priority of parent with a UI -> IN downgrade
// Escalated priority = UN
if (currentTask) {
basePriority = currentTask->_private().BasePriority;
} else {
basePriority = swift_task_getCurrentThreadPriority();
}
basePriority = withUserInteractivePriorityDowngrade(basePriority);
} else {
// Case 2: User specified a priority
// Base priority = user specified priority
// Escalated priority = UN
}
// Task will be created with max priority = max(base priority, UN) = base
// priority
} else {
// Is a structured concurrency child task. Must have a parent.
assert((asyncLet || group) && parent);
SWIFT_TASK_DEBUG_LOG("Creating an structured concurrency task from %p", currentTask);
if (isUnspecified(basePriority)) {
// Case 1: No priority specified
// Base priority = Base priority of parent with a UI -> IN downgrade
// Escalated priority = Escalated priority of parent with a UI -> IN
// downgrade
JobPriority parentBasePri = parent->_private().BasePriority;
basePriority = withUserInteractivePriorityDowngrade(parentBasePri);
} else {
// Case 2: User priority specified
// Base priority = User specified priority
// Escalated priority = Escalated priority of parent with a UI -> IN
// downgrade
}
// Task will be created with escalated priority = base priority. We will
// update the escalated priority with the right rules in
// updateNewChildWithParentAndGroupState when we link the child into
// the parent task/task group since we'll have the right
// synchronization then.
}
if (isUnspecified(basePriority)) {
basePriority = JobPriority::Default;
}
SWIFT_TASK_DEBUG_LOG("Task's base priority = %#zx", basePriority);
size_t headerSize, amountToAllocate;
std::tie(headerSize, amountToAllocate) = amountToAllocateForHeaderAndTask(
parent, group, futureResultType, initialContextSize);
unsigned initialSlabSize = 512;
void *allocation = nullptr;
if (asyncLet) {
assert(parent);
// If there isn't enough room in the fixed async let allocation to
// set up the initial context, then we'll have to allocate more space
// from the parent.
if (asyncLet->getSizeOfPreallocatedSpace() < amountToAllocate) {
hasAsyncLetResultBuffer = false;
}
// DEPRECATED. This is separated from the above condition because we
// also have to handle an older async let ABI that did not provide
// space for the initial slab in the compiler-generated preallocation.
if (!hasAsyncLetResultBuffer) {
allocation = _swift_task_alloc_specific(parent,
amountToAllocate + initialSlabSize);
} else {
allocation = asyncLet->getPreallocatedSpace();
assert(asyncLet->getSizeOfPreallocatedSpace() >= amountToAllocate
&& "async let does not preallocate enough space for child task");
initialSlabSize = asyncLet->getSizeOfPreallocatedSpace()
- amountToAllocate;
}
} else if (runInlineOption && runInlineOption->getAllocation()) {
// NOTE: If the space required for the task and initial context was
// greater than SWIFT_TASK_RUN_INLINE_INITIAL_CONTEXT_BYTES,
// getAllocation will return nullptr and we'll fall back to malloc to
// allocate the buffer.
//
// This was already checked in swift_task_run_inline.
size_t runInlineBufferBytes = runInlineOption->getAllocationBytes();
assert(amountToAllocate <= runInlineBufferBytes);
allocation = runInlineOption->getAllocation();
initialSlabSize = runInlineBufferBytes - amountToAllocate;
} else {
allocation = malloc(amountToAllocate);
}
SWIFT_TASK_DEBUG_LOG("allocate task %p, parent = %p, slab %u", allocation,
parent, initialSlabSize);
AsyncContext *initialContext =
reinterpret_cast<AsyncContext*>(
reinterpret_cast<char*>(allocation) + headerSize);
// We can't just use `function` because it uses the new async function entry
// ABI -- passing parameters, closure context, indirect result addresses
// directly -- but AsyncTask->ResumeTask expects the signature to be
// `void (*, *, swiftasync *)`.
// Instead we use an adapter. This adaptor should use the storage prefixed to
// the async context to get at the parameters.
// See e.g. FutureAsyncContextPrefix.
if (futureResultType.isNull() || taskCreateFlags.isDiscardingTask()) {
auto asyncContextPrefix = reinterpret_cast<AsyncContextPrefix *>(
reinterpret_cast<char *>(allocation) + headerSize -
sizeof(AsyncContextPrefix));
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-function-type-mismatch"
asyncContextPrefix->asyncEntryPoint =
reinterpret_cast<AsyncVoidClosureEntryPoint *>(function);
#pragma clang diagnostic pop
asyncContextPrefix->closureContext = closureContext;
function = non_future_adapter;
assert(sizeof(AsyncContextPrefix) == 3 * sizeof(void *));
} else {
auto asyncContextPrefix = reinterpret_cast<FutureAsyncContextPrefix *>(
reinterpret_cast<char *>(allocation) + headerSize -
sizeof(FutureAsyncContextPrefix));
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-function-type-mismatch"
asyncContextPrefix->asyncEntryPoint =
reinterpret_cast<AsyncGenericClosureEntryPoint *>(function);
#pragma clang diagnostic pop
function = future_adapter;
asyncContextPrefix->closureContext = closureContext;
assert(sizeof(FutureAsyncContextPrefix) == 4 * sizeof(void *));
}
// Only attempt to inherit parent's executor preference if we didn't set one
// explicitly, which we've recorded in the flag by noticing a task create