1 /*
2  * kmp_tasking.cpp -- OpenMP 3.0 tasking support.
3  */
4 
5 //===----------------------------------------------------------------------===//
6 //
7 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
8 // See https://llvm.org/LICENSE.txt for license information.
9 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "kmp.h"
14 #include "kmp_i18n.h"
15 #include "kmp_itt.h"
16 #include "kmp_stats.h"
17 #include "kmp_wait_release.h"
18 #include "kmp_taskdeps.h"
19 
20 #if OMPT_SUPPORT
21 #include "ompt-specific.h"
22 #endif
23 
24 #include "tsan_annotations.h"
25 
26 /* forward declaration */
27 static void __kmp_enable_tasking(kmp_task_team_t *task_team,
28                                  kmp_info_t *this_thr);
29 static void __kmp_alloc_task_deque(kmp_info_t *thread,
30                                    kmp_thread_data_t *thread_data);
31 static int __kmp_realloc_task_threads_data(kmp_info_t *thread,
32                                            kmp_task_team_t *task_team);
33 static void __kmp_bottom_half_finish_proxy(kmp_int32 gtid, kmp_task_t *ptask);
34 
35 #ifdef BUILD_TIED_TASK_STACK
36 
37 //  __kmp_trace_task_stack: print the tied tasks from the task stack in order
38 //  from top do bottom
39 //
40 //  gtid: global thread identifier for thread containing stack
41 //  thread_data: thread data for task team thread containing stack
42 //  threshold: value above which the trace statement triggers
43 //  location: string identifying call site of this function (for trace)
44 static void __kmp_trace_task_stack(kmp_int32 gtid,
45                                    kmp_thread_data_t *thread_data,
46                                    int threshold, char *location) {
47   kmp_task_stack_t *task_stack = &thread_data->td.td_susp_tied_tasks;
48   kmp_taskdata_t **stack_top = task_stack->ts_top;
49   kmp_int32 entries = task_stack->ts_entries;
50   kmp_taskdata_t *tied_task;
51 
52   KA_TRACE(
53       threshold,
54       ("__kmp_trace_task_stack(start): location = %s, gtid = %d, entries = %d, "
55        "first_block = %p, stack_top = %p \n",
56        location, gtid, entries, task_stack->ts_first_block, stack_top));
57 
58   KMP_DEBUG_ASSERT(stack_top != NULL);
59   KMP_DEBUG_ASSERT(entries > 0);
60 
61   while (entries != 0) {
62     KMP_DEBUG_ASSERT(stack_top != &task_stack->ts_first_block.sb_block[0]);
63     // fix up ts_top if we need to pop from previous block
64     if (entries & TASK_STACK_INDEX_MASK == 0) {
65       kmp_stack_block_t *stack_block = (kmp_stack_block_t *)(stack_top);
66 
67       stack_block = stack_block->sb_prev;
68       stack_top = &stack_block->sb_block[TASK_STACK_BLOCK_SIZE];
69     }
70 
71     // finish bookkeeping
72     stack_top--;
73     entries--;
74 
75     tied_task = *stack_top;
76 
77     KMP_DEBUG_ASSERT(tied_task != NULL);
78     KMP_DEBUG_ASSERT(tied_task->td_flags.tasktype == TASK_TIED);
79 
80     KA_TRACE(threshold,
81              ("__kmp_trace_task_stack(%s):             gtid=%d, entry=%d, "
82               "stack_top=%p, tied_task=%p\n",
83               location, gtid, entries, stack_top, tied_task));
84   }
85   KMP_DEBUG_ASSERT(stack_top == &task_stack->ts_first_block.sb_block[0]);
86 
87   KA_TRACE(threshold,
88            ("__kmp_trace_task_stack(exit): location = %s, gtid = %d\n",
89             location, gtid));
90 }
91 
92 //  __kmp_init_task_stack: initialize the task stack for the first time
93 //  after a thread_data structure is created.
94 //  It should not be necessary to do this again (assuming the stack works).
95 //
96 //  gtid: global thread identifier of calling thread
97 //  thread_data: thread data for task team thread containing stack
98 static void __kmp_init_task_stack(kmp_int32 gtid,
99                                   kmp_thread_data_t *thread_data) {
100   kmp_task_stack_t *task_stack = &thread_data->td.td_susp_tied_tasks;
101   kmp_stack_block_t *first_block;
102 
103   // set up the first block of the stack
104   first_block = &task_stack->ts_first_block;
105   task_stack->ts_top = (kmp_taskdata_t **)first_block;
106   memset((void *)first_block, '\0',
107          TASK_STACK_BLOCK_SIZE * sizeof(kmp_taskdata_t *));
108 
109   // initialize the stack to be empty
110   task_stack->ts_entries = TASK_STACK_EMPTY;
111   first_block->sb_next = NULL;
112   first_block->sb_prev = NULL;
113 }
114 
115 //  __kmp_free_task_stack: free the task stack when thread_data is destroyed.
116 //
117 //  gtid: global thread identifier for calling thread
118 //  thread_data: thread info for thread containing stack
119 static void __kmp_free_task_stack(kmp_int32 gtid,
120                                   kmp_thread_data_t *thread_data) {
121   kmp_task_stack_t *task_stack = &thread_data->td.td_susp_tied_tasks;
122   kmp_stack_block_t *stack_block = &task_stack->ts_first_block;
123 
124   KMP_DEBUG_ASSERT(task_stack->ts_entries == TASK_STACK_EMPTY);
125   // free from the second block of the stack
126   while (stack_block != NULL) {
127     kmp_stack_block_t *next_block = (stack_block) ? stack_block->sb_next : NULL;
128 
129     stack_block->sb_next = NULL;
130     stack_block->sb_prev = NULL;
131     if (stack_block != &task_stack->ts_first_block) {
132       __kmp_thread_free(thread,
133                         stack_block); // free the block, if not the first
134     }
135     stack_block = next_block;
136   }
137   // initialize the stack to be empty
138   task_stack->ts_entries = 0;
139   task_stack->ts_top = NULL;
140 }
141 
142 //  __kmp_push_task_stack: Push the tied task onto the task stack.
143 //     Grow the stack if necessary by allocating another block.
144 //
145 //  gtid: global thread identifier for calling thread
146 //  thread: thread info for thread containing stack
147 //  tied_task: the task to push on the stack
148 static void __kmp_push_task_stack(kmp_int32 gtid, kmp_info_t *thread,
149                                   kmp_taskdata_t *tied_task) {
150   // GEH - need to consider what to do if tt_threads_data not allocated yet
151   kmp_thread_data_t *thread_data =
152       &thread->th.th_task_team->tt.tt_threads_data[__kmp_tid_from_gtid(gtid)];
153   kmp_task_stack_t *task_stack = &thread_data->td.td_susp_tied_tasks;
154 
155   if (tied_task->td_flags.team_serial || tied_task->td_flags.tasking_ser) {
156     return; // Don't push anything on stack if team or team tasks are serialized
157   }
158 
159   KMP_DEBUG_ASSERT(tied_task->td_flags.tasktype == TASK_TIED);
160   KMP_DEBUG_ASSERT(task_stack->ts_top != NULL);
161 
162   KA_TRACE(20,
163            ("__kmp_push_task_stack(enter): GTID: %d; THREAD: %p; TASK: %p\n",
164             gtid, thread, tied_task));
165   // Store entry
166   *(task_stack->ts_top) = tied_task;
167 
168   // Do bookkeeping for next push
169   task_stack->ts_top++;
170   task_stack->ts_entries++;
171 
172   if (task_stack->ts_entries & TASK_STACK_INDEX_MASK == 0) {
173     // Find beginning of this task block
174     kmp_stack_block_t *stack_block =
175         (kmp_stack_block_t *)(task_stack->ts_top - TASK_STACK_BLOCK_SIZE);
176 
177     // Check if we already have a block
178     if (stack_block->sb_next !=
179         NULL) { // reset ts_top to beginning of next block
180       task_stack->ts_top = &stack_block->sb_next->sb_block[0];
181     } else { // Alloc new block and link it up
182       kmp_stack_block_t *new_block = (kmp_stack_block_t *)__kmp_thread_calloc(
183           thread, sizeof(kmp_stack_block_t));
184 
185       task_stack->ts_top = &new_block->sb_block[0];
186       stack_block->sb_next = new_block;
187       new_block->sb_prev = stack_block;
188       new_block->sb_next = NULL;
189 
190       KA_TRACE(
191           30,
192           ("__kmp_push_task_stack(): GTID: %d; TASK: %p; Alloc new block: %p\n",
193            gtid, tied_task, new_block));
194     }
195   }
196   KA_TRACE(20, ("__kmp_push_task_stack(exit): GTID: %d; TASK: %p\n", gtid,
197                 tied_task));
198 }
199 
200 //  __kmp_pop_task_stack: Pop the tied task from the task stack.  Don't return
201 //  the task, just check to make sure it matches the ending task passed in.
202 //
203 //  gtid: global thread identifier for the calling thread
204 //  thread: thread info structure containing stack
205 //  tied_task: the task popped off the stack
206 //  ending_task: the task that is ending (should match popped task)
207 static void __kmp_pop_task_stack(kmp_int32 gtid, kmp_info_t *thread,
208                                  kmp_taskdata_t *ending_task) {
209   // GEH - need to consider what to do if tt_threads_data not allocated yet
210   kmp_thread_data_t *thread_data =
211       &thread->th.th_task_team->tt_threads_data[__kmp_tid_from_gtid(gtid)];
212   kmp_task_stack_t *task_stack = &thread_data->td.td_susp_tied_tasks;
213   kmp_taskdata_t *tied_task;
214 
215   if (ending_task->td_flags.team_serial || ending_task->td_flags.tasking_ser) {
216     // Don't pop anything from stack if team or team tasks are serialized
217     return;
218   }
219 
220   KMP_DEBUG_ASSERT(task_stack->ts_top != NULL);
221   KMP_DEBUG_ASSERT(task_stack->ts_entries > 0);
222 
223   KA_TRACE(20, ("__kmp_pop_task_stack(enter): GTID: %d; THREAD: %p\n", gtid,
224                 thread));
225 
226   // fix up ts_top if we need to pop from previous block
227   if (task_stack->ts_entries & TASK_STACK_INDEX_MASK == 0) {
228     kmp_stack_block_t *stack_block = (kmp_stack_block_t *)(task_stack->ts_top);
229 
230     stack_block = stack_block->sb_prev;
231     task_stack->ts_top = &stack_block->sb_block[TASK_STACK_BLOCK_SIZE];
232   }
233 
234   // finish bookkeeping
235   task_stack->ts_top--;
236   task_stack->ts_entries--;
237 
238   tied_task = *(task_stack->ts_top);
239 
240   KMP_DEBUG_ASSERT(tied_task != NULL);
241   KMP_DEBUG_ASSERT(tied_task->td_flags.tasktype == TASK_TIED);
242   KMP_DEBUG_ASSERT(tied_task == ending_task); // If we built the stack correctly
243 
244   KA_TRACE(20, ("__kmp_pop_task_stack(exit): GTID: %d; TASK: %p\n", gtid,
245                 tied_task));
246   return;
247 }
248 #endif /* BUILD_TIED_TASK_STACK */
249 
250 // returns 1 if new task is allowed to execute, 0 otherwise
251 // checks Task Scheduling constraint (if requested) and
252 // mutexinoutset dependencies if any
253 static bool __kmp_task_is_allowed(int gtid, const kmp_int32 is_constrained,
254                                   const kmp_taskdata_t *tasknew,
255                                   const kmp_taskdata_t *taskcurr) {
256   if (is_constrained && (tasknew->td_flags.tiedness == TASK_TIED)) {
257     // Check if the candidate obeys the Task Scheduling Constraints (TSC)
258     // only descendant of all deferred tied tasks can be scheduled, checking
259     // the last one is enough, as it in turn is the descendant of all others
260     kmp_taskdata_t *current = taskcurr->td_last_tied;
261     KMP_DEBUG_ASSERT(current != NULL);
262     // check if the task is not suspended on barrier
263     if (current->td_flags.tasktype == TASK_EXPLICIT ||
264         current->td_taskwait_thread > 0) { // <= 0 on barrier
265       kmp_int32 level = current->td_level;
266       kmp_taskdata_t *parent = tasknew->td_parent;
267       while (parent != current && parent->td_level > level) {
268         // check generation up to the level of the current task
269         parent = parent->td_parent;
270         KMP_DEBUG_ASSERT(parent != NULL);
271       }
272       if (parent != current)
273         return false;
274     }
275   }
276   // Check mutexinoutset dependencies, acquire locks
277   kmp_depnode_t *node = tasknew->td_depnode;
278   if (UNLIKELY(node && (node->dn.mtx_num_locks > 0))) {
279     for (int i = 0; i < node->dn.mtx_num_locks; ++i) {
280       KMP_DEBUG_ASSERT(node->dn.mtx_locks[i] != NULL);
281       if (__kmp_test_lock(node->dn.mtx_locks[i], gtid))
282         continue;
283       // could not get the lock, release previous locks
284       for (int j = i - 1; j >= 0; --j)
285         __kmp_release_lock(node->dn.mtx_locks[j], gtid);
286       return false;
287     }
288     // negative num_locks means all locks acquired successfully
289     node->dn.mtx_num_locks = -node->dn.mtx_num_locks;
290   }
291   return true;
292 }
293 
294 // __kmp_realloc_task_deque:
295 // Re-allocates a task deque for a particular thread, copies the content from
296 // the old deque and adjusts the necessary data structures relating to the
297 // deque. This operation must be done with the deque_lock being held
298 static void __kmp_realloc_task_deque(kmp_info_t *thread,
299                                      kmp_thread_data_t *thread_data) {
300   kmp_int32 size = TASK_DEQUE_SIZE(thread_data->td);
301   KMP_DEBUG_ASSERT(TCR_4(thread_data->td.td_deque_ntasks) == size);
302   kmp_int32 new_size = 2 * size;
303 
304   KE_TRACE(10, ("__kmp_realloc_task_deque: T#%d reallocating deque[from %d to "
305                 "%d] for thread_data %p\n",
306                 __kmp_gtid_from_thread(thread), size, new_size, thread_data));
307 
308   kmp_taskdata_t **new_deque =
309       (kmp_taskdata_t **)__kmp_allocate(new_size * sizeof(kmp_taskdata_t *));
310 
311   int i, j;
312   for (i = thread_data->td.td_deque_head, j = 0; j < size;
313        i = (i + 1) & TASK_DEQUE_MASK(thread_data->td), j++)
314     new_deque[j] = thread_data->td.td_deque[i];
315 
316   __kmp_free(thread_data->td.td_deque);
317 
318   thread_data->td.td_deque_head = 0;
319   thread_data->td.td_deque_tail = size;
320   thread_data->td.td_deque = new_deque;
321   thread_data->td.td_deque_size = new_size;
322 }
323 
324 //  __kmp_push_task: Add a task to the thread's deque
325 static kmp_int32 __kmp_push_task(kmp_int32 gtid, kmp_task_t *task) {
326   kmp_info_t *thread = __kmp_threads[gtid];
327   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(task);
328 
329   // We don't need to map to shadow gtid if it is already hidden helper thread
330   if (taskdata->td_flags.hidden_helper && !KMP_HIDDEN_HELPER_THREAD(gtid)) {
331     gtid = KMP_GTID_TO_SHADOW_GTID(gtid);
332     thread = __kmp_threads[gtid];
333   }
334 
335   kmp_task_team_t *task_team = thread->th.th_task_team;
336   kmp_int32 tid = __kmp_tid_from_gtid(gtid);
337   kmp_thread_data_t *thread_data;
338 
339   KA_TRACE(20,
340            ("__kmp_push_task: T#%d trying to push task %p.\n", gtid, taskdata));
341 
342   if (UNLIKELY(taskdata->td_flags.tiedness == TASK_UNTIED)) {
343     // untied task needs to increment counter so that the task structure is not
344     // freed prematurely
345     kmp_int32 counter = 1 + KMP_ATOMIC_INC(&taskdata->td_untied_count);
346     KMP_DEBUG_USE_VAR(counter);
347     KA_TRACE(
348         20,
349         ("__kmp_push_task: T#%d untied_count (%d) incremented for task %p\n",
350          gtid, counter, taskdata));
351   }
352 
353   // The first check avoids building task_team thread data if serialized
354   if (UNLIKELY(taskdata->td_flags.task_serial)) {
355     KA_TRACE(20, ("__kmp_push_task: T#%d team serialized; returning "
356                   "TASK_NOT_PUSHED for task %p\n",
357                   gtid, taskdata));
358     return TASK_NOT_PUSHED;
359   }
360 
361   // Now that serialized tasks have returned, we can assume that we are not in
362   // immediate exec mode
363   KMP_DEBUG_ASSERT(__kmp_tasking_mode != tskm_immediate_exec);
364   if (UNLIKELY(!KMP_TASKING_ENABLED(task_team))) {
365     __kmp_enable_tasking(task_team, thread);
366   }
367   KMP_DEBUG_ASSERT(TCR_4(task_team->tt.tt_found_tasks) == TRUE);
368   KMP_DEBUG_ASSERT(TCR_PTR(task_team->tt.tt_threads_data) != NULL);
369 
370   // Find tasking deque specific to encountering thread
371   thread_data = &task_team->tt.tt_threads_data[tid];
372 
373   // No lock needed since only owner can allocate. If the task is hidden_helper,
374   // we don't need it either because we have initialized the dequeue for hidden
375   // helper thread data.
376   if (UNLIKELY(thread_data->td.td_deque == NULL)) {
377     __kmp_alloc_task_deque(thread, thread_data);
378   }
379 
380   int locked = 0;
381   // Check if deque is full
382   if (TCR_4(thread_data->td.td_deque_ntasks) >=
383       TASK_DEQUE_SIZE(thread_data->td)) {
384     if (__kmp_enable_task_throttling &&
385         __kmp_task_is_allowed(gtid, __kmp_task_stealing_constraint, taskdata,
386                               thread->th.th_current_task)) {
387       KA_TRACE(20, ("__kmp_push_task: T#%d deque is full; returning "
388                     "TASK_NOT_PUSHED for task %p\n",
389                     gtid, taskdata));
390       return TASK_NOT_PUSHED;
391     } else {
392       __kmp_acquire_bootstrap_lock(&thread_data->td.td_deque_lock);
393       locked = 1;
394       if (TCR_4(thread_data->td.td_deque_ntasks) >=
395           TASK_DEQUE_SIZE(thread_data->td)) {
396         // expand deque to push the task which is not allowed to execute
397         __kmp_realloc_task_deque(thread, thread_data);
398       }
399     }
400   }
401   // Lock the deque for the task push operation
402   if (!locked) {
403     __kmp_acquire_bootstrap_lock(&thread_data->td.td_deque_lock);
404     // Need to recheck as we can get a proxy task from thread outside of OpenMP
405     if (TCR_4(thread_data->td.td_deque_ntasks) >=
406         TASK_DEQUE_SIZE(thread_data->td)) {
407       if (__kmp_enable_task_throttling &&
408           __kmp_task_is_allowed(gtid, __kmp_task_stealing_constraint, taskdata,
409                                 thread->th.th_current_task)) {
410         __kmp_release_bootstrap_lock(&thread_data->td.td_deque_lock);
411         KA_TRACE(20, ("__kmp_push_task: T#%d deque is full on 2nd check; "
412                       "returning TASK_NOT_PUSHED for task %p\n",
413                       gtid, taskdata));
414         return TASK_NOT_PUSHED;
415       } else {
416         // expand deque to push the task which is not allowed to execute
417         __kmp_realloc_task_deque(thread, thread_data);
418       }
419     }
420   }
421   // Must have room since no thread can add tasks but calling thread
422   KMP_DEBUG_ASSERT(TCR_4(thread_data->td.td_deque_ntasks) <
423                    TASK_DEQUE_SIZE(thread_data->td));
424 
425   thread_data->td.td_deque[thread_data->td.td_deque_tail] =
426       taskdata; // Push taskdata
427   // Wrap index.
428   thread_data->td.td_deque_tail =
429       (thread_data->td.td_deque_tail + 1) & TASK_DEQUE_MASK(thread_data->td);
430   TCW_4(thread_data->td.td_deque_ntasks,
431         TCR_4(thread_data->td.td_deque_ntasks) + 1); // Adjust task count
432   KMP_FSYNC_RELEASING(thread->th.th_current_task); // releasing self
433   KMP_FSYNC_RELEASING(taskdata); // releasing child
434   KA_TRACE(20, ("__kmp_push_task: T#%d returning TASK_SUCCESSFULLY_PUSHED: "
435                 "task=%p ntasks=%d head=%u tail=%u\n",
436                 gtid, taskdata, thread_data->td.td_deque_ntasks,
437                 thread_data->td.td_deque_head, thread_data->td.td_deque_tail));
438 
439   __kmp_release_bootstrap_lock(&thread_data->td.td_deque_lock);
440 
441   // Signal one worker thread to execute the task
442   if (taskdata->td_flags.hidden_helper) {
443     // Wake hidden helper threads up if they're sleeping
444     __kmp_hidden_helper_worker_thread_signal();
445   }
446 
447   return TASK_SUCCESSFULLY_PUSHED;
448 }
449 
450 // __kmp_pop_current_task_from_thread: set up current task from called thread
451 // when team ends
452 //
453 // this_thr: thread structure to set current_task in.
454 void __kmp_pop_current_task_from_thread(kmp_info_t *this_thr) {
455   KF_TRACE(10, ("__kmp_pop_current_task_from_thread(enter): T#%d "
456                 "this_thread=%p, curtask=%p, "
457                 "curtask_parent=%p\n",
458                 0, this_thr, this_thr->th.th_current_task,
459                 this_thr->th.th_current_task->td_parent));
460 
461   this_thr->th.th_current_task = this_thr->th.th_current_task->td_parent;
462 
463   KF_TRACE(10, ("__kmp_pop_current_task_from_thread(exit): T#%d "
464                 "this_thread=%p, curtask=%p, "
465                 "curtask_parent=%p\n",
466                 0, this_thr, this_thr->th.th_current_task,
467                 this_thr->th.th_current_task->td_parent));
468 }
469 
470 // __kmp_push_current_task_to_thread: set up current task in called thread for a
471 // new team
472 //
473 // this_thr: thread structure to set up
474 // team: team for implicit task data
475 // tid: thread within team to set up
476 void __kmp_push_current_task_to_thread(kmp_info_t *this_thr, kmp_team_t *team,
477                                        int tid) {
478   // current task of the thread is a parent of the new just created implicit
479   // tasks of new team
480   KF_TRACE(10, ("__kmp_push_current_task_to_thread(enter): T#%d this_thread=%p "
481                 "curtask=%p "
482                 "parent_task=%p\n",
483                 tid, this_thr, this_thr->th.th_current_task,
484                 team->t.t_implicit_task_taskdata[tid].td_parent));
485 
486   KMP_DEBUG_ASSERT(this_thr != NULL);
487 
488   if (tid == 0) {
489     if (this_thr->th.th_current_task != &team->t.t_implicit_task_taskdata[0]) {
490       team->t.t_implicit_task_taskdata[0].td_parent =
491           this_thr->th.th_current_task;
492       this_thr->th.th_current_task = &team->t.t_implicit_task_taskdata[0];
493     }
494   } else {
495     team->t.t_implicit_task_taskdata[tid].td_parent =
496         team->t.t_implicit_task_taskdata[0].td_parent;
497     this_thr->th.th_current_task = &team->t.t_implicit_task_taskdata[tid];
498   }
499 
500   KF_TRACE(10, ("__kmp_push_current_task_to_thread(exit): T#%d this_thread=%p "
501                 "curtask=%p "
502                 "parent_task=%p\n",
503                 tid, this_thr, this_thr->th.th_current_task,
504                 team->t.t_implicit_task_taskdata[tid].td_parent));
505 }
506 
507 // __kmp_task_start: bookkeeping for a task starting execution
508 //
509 // GTID: global thread id of calling thread
510 // task: task starting execution
511 // current_task: task suspending
512 static void __kmp_task_start(kmp_int32 gtid, kmp_task_t *task,
513                              kmp_taskdata_t *current_task) {
514   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(task);
515   kmp_info_t *thread = __kmp_threads[gtid];
516 
517   KA_TRACE(10,
518            ("__kmp_task_start(enter): T#%d starting task %p: current_task=%p\n",
519             gtid, taskdata, current_task));
520 
521   KMP_DEBUG_ASSERT(taskdata->td_flags.tasktype == TASK_EXPLICIT);
522 
523   // mark currently executing task as suspended
524   // TODO: GEH - make sure root team implicit task is initialized properly.
525   // KMP_DEBUG_ASSERT( current_task -> td_flags.executing == 1 );
526   current_task->td_flags.executing = 0;
527 
528 // Add task to stack if tied
529 #ifdef BUILD_TIED_TASK_STACK
530   if (taskdata->td_flags.tiedness == TASK_TIED) {
531     __kmp_push_task_stack(gtid, thread, taskdata);
532   }
533 #endif /* BUILD_TIED_TASK_STACK */
534 
535   // mark starting task as executing and as current task
536   thread->th.th_current_task = taskdata;
537 
538   KMP_DEBUG_ASSERT(taskdata->td_flags.started == 0 ||
539                    taskdata->td_flags.tiedness == TASK_UNTIED);
540   KMP_DEBUG_ASSERT(taskdata->td_flags.executing == 0 ||
541                    taskdata->td_flags.tiedness == TASK_UNTIED);
542   taskdata->td_flags.started = 1;
543   taskdata->td_flags.executing = 1;
544   KMP_DEBUG_ASSERT(taskdata->td_flags.complete == 0);
545   KMP_DEBUG_ASSERT(taskdata->td_flags.freed == 0);
546 
547   // GEH TODO: shouldn't we pass some sort of location identifier here?
548   // APT: yes, we will pass location here.
549   // need to store current thread state (in a thread or taskdata structure)
550   // before setting work_state, otherwise wrong state is set after end of task
551 
552   KA_TRACE(10, ("__kmp_task_start(exit): T#%d task=%p\n", gtid, taskdata));
553 
554   return;
555 }
556 
557 #if OMPT_SUPPORT
558 //------------------------------------------------------------------------------
559 // __ompt_task_init:
560 //   Initialize OMPT fields maintained by a task. This will only be called after
561 //   ompt_start_tool, so we already know whether ompt is enabled or not.
562 
563 static inline void __ompt_task_init(kmp_taskdata_t *task, int tid) {
564   // The calls to __ompt_task_init already have the ompt_enabled condition.
565   task->ompt_task_info.task_data.value = 0;
566   task->ompt_task_info.frame.exit_frame = ompt_data_none;
567   task->ompt_task_info.frame.enter_frame = ompt_data_none;
568   task->ompt_task_info.frame.exit_frame_flags =
569       ompt_frame_runtime | ompt_frame_framepointer;
570   task->ompt_task_info.frame.enter_frame_flags =
571       ompt_frame_runtime | ompt_frame_framepointer;
572 }
573 
574 // __ompt_task_start:
575 //   Build and trigger task-begin event
576 static inline void __ompt_task_start(kmp_task_t *task,
577                                      kmp_taskdata_t *current_task,
578                                      kmp_int32 gtid) {
579   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(task);
580   ompt_task_status_t status = ompt_task_switch;
581   if (__kmp_threads[gtid]->th.ompt_thread_info.ompt_task_yielded) {
582     status = ompt_task_yield;
583     __kmp_threads[gtid]->th.ompt_thread_info.ompt_task_yielded = 0;
584   }
585   /* let OMPT know that we're about to run this task */
586   if (ompt_enabled.ompt_callback_task_schedule) {
587     ompt_callbacks.ompt_callback(ompt_callback_task_schedule)(
588         &(current_task->ompt_task_info.task_data), status,
589         &(taskdata->ompt_task_info.task_data));
590   }
591   taskdata->ompt_task_info.scheduling_parent = current_task;
592 }
593 
594 // __ompt_task_finish:
595 //   Build and trigger final task-schedule event
596 static inline void __ompt_task_finish(kmp_task_t *task,
597                                       kmp_taskdata_t *resumed_task,
598                                       ompt_task_status_t status) {
599   if (ompt_enabled.ompt_callback_task_schedule) {
600     kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(task);
601     if (__kmp_omp_cancellation && taskdata->td_taskgroup &&
602         taskdata->td_taskgroup->cancel_request == cancel_taskgroup) {
603       status = ompt_task_cancel;
604     }
605 
606     /* let OMPT know that we're returning to the callee task */
607     ompt_callbacks.ompt_callback(ompt_callback_task_schedule)(
608         &(taskdata->ompt_task_info.task_data), status,
609         (resumed_task ? &(resumed_task->ompt_task_info.task_data) : NULL));
610   }
611 }
612 #endif
613 
614 template <bool ompt>
615 static void __kmpc_omp_task_begin_if0_template(ident_t *loc_ref, kmp_int32 gtid,
616                                                kmp_task_t *task,
617                                                void *frame_address,
618                                                void *return_address) {
619   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(task);
620   kmp_taskdata_t *current_task = __kmp_threads[gtid]->th.th_current_task;
621 
622   KA_TRACE(10, ("__kmpc_omp_task_begin_if0(enter): T#%d loc=%p task=%p "
623                 "current_task=%p\n",
624                 gtid, loc_ref, taskdata, current_task));
625 
626   if (UNLIKELY(taskdata->td_flags.tiedness == TASK_UNTIED)) {
627     // untied task needs to increment counter so that the task structure is not
628     // freed prematurely
629     kmp_int32 counter = 1 + KMP_ATOMIC_INC(&taskdata->td_untied_count);
630     KMP_DEBUG_USE_VAR(counter);
631     KA_TRACE(20, ("__kmpc_omp_task_begin_if0: T#%d untied_count (%d) "
632                   "incremented for task %p\n",
633                   gtid, counter, taskdata));
634   }
635 
636   taskdata->td_flags.task_serial =
637       1; // Execute this task immediately, not deferred.
638   __kmp_task_start(gtid, task, current_task);
639 
640 #if OMPT_SUPPORT
641   if (ompt) {
642     if (current_task->ompt_task_info.frame.enter_frame.ptr == NULL) {
643       current_task->ompt_task_info.frame.enter_frame.ptr =
644           taskdata->ompt_task_info.frame.exit_frame.ptr = frame_address;
645       current_task->ompt_task_info.frame.enter_frame_flags =
646           taskdata->ompt_task_info.frame.exit_frame_flags =
647               ompt_frame_application | ompt_frame_framepointer;
648     }
649     if (ompt_enabled.ompt_callback_task_create) {
650       ompt_task_info_t *parent_info = &(current_task->ompt_task_info);
651       ompt_callbacks.ompt_callback(ompt_callback_task_create)(
652           &(parent_info->task_data), &(parent_info->frame),
653           &(taskdata->ompt_task_info.task_data),
654           ompt_task_explicit | TASK_TYPE_DETAILS_FORMAT(taskdata), 0,
655           return_address);
656     }
657     __ompt_task_start(task, current_task, gtid);
658   }
659 #endif // OMPT_SUPPORT
660 
661   KA_TRACE(10, ("__kmpc_omp_task_begin_if0(exit): T#%d loc=%p task=%p,\n", gtid,
662                 loc_ref, taskdata));
663 }
664 
665 #if OMPT_SUPPORT
666 OMPT_NOINLINE
667 static void __kmpc_omp_task_begin_if0_ompt(ident_t *loc_ref, kmp_int32 gtid,
668                                            kmp_task_t *task,
669                                            void *frame_address,
670                                            void *return_address) {
671   __kmpc_omp_task_begin_if0_template<true>(loc_ref, gtid, task, frame_address,
672                                            return_address);
673 }
674 #endif // OMPT_SUPPORT
675 
676 // __kmpc_omp_task_begin_if0: report that a given serialized task has started
677 // execution
678 //
679 // loc_ref: source location information; points to beginning of task block.
680 // gtid: global thread number.
681 // task: task thunk for the started task.
682 void __kmpc_omp_task_begin_if0(ident_t *loc_ref, kmp_int32 gtid,
683                                kmp_task_t *task) {
684 #if OMPT_SUPPORT
685   if (UNLIKELY(ompt_enabled.enabled)) {
686     OMPT_STORE_RETURN_ADDRESS(gtid);
687     __kmpc_omp_task_begin_if0_ompt(loc_ref, gtid, task,
688                                    OMPT_GET_FRAME_ADDRESS(1),
689                                    OMPT_LOAD_RETURN_ADDRESS(gtid));
690     return;
691   }
692 #endif
693   __kmpc_omp_task_begin_if0_template<false>(loc_ref, gtid, task, NULL, NULL);
694 }
695 
696 #ifdef TASK_UNUSED
697 // __kmpc_omp_task_begin: report that a given task has started execution
698 // NEVER GENERATED BY COMPILER, DEPRECATED!!!
699 void __kmpc_omp_task_begin(ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *task) {
700   kmp_taskdata_t *current_task = __kmp_threads[gtid]->th.th_current_task;
701 
702   KA_TRACE(
703       10,
704       ("__kmpc_omp_task_begin(enter): T#%d loc=%p task=%p current_task=%p\n",
705        gtid, loc_ref, KMP_TASK_TO_TASKDATA(task), current_task));
706 
707   __kmp_task_start(gtid, task, current_task);
708 
709   KA_TRACE(10, ("__kmpc_omp_task_begin(exit): T#%d loc=%p task=%p,\n", gtid,
710                 loc_ref, KMP_TASK_TO_TASKDATA(task)));
711   return;
712 }
713 #endif // TASK_UNUSED
714 
715 // __kmp_free_task: free the current task space and the space for shareds
716 //
717 // gtid: Global thread ID of calling thread
718 // taskdata: task to free
719 // thread: thread data structure of caller
720 static void __kmp_free_task(kmp_int32 gtid, kmp_taskdata_t *taskdata,
721                             kmp_info_t *thread) {
722   KA_TRACE(30, ("__kmp_free_task: T#%d freeing data from task %p\n", gtid,
723                 taskdata));
724 
725   // Check to make sure all flags and counters have the correct values
726   KMP_DEBUG_ASSERT(taskdata->td_flags.tasktype == TASK_EXPLICIT);
727   KMP_DEBUG_ASSERT(taskdata->td_flags.executing == 0);
728   KMP_DEBUG_ASSERT(taskdata->td_flags.complete == 1);
729   KMP_DEBUG_ASSERT(taskdata->td_flags.freed == 0);
730   KMP_DEBUG_ASSERT(taskdata->td_allocated_child_tasks == 0 ||
731                    taskdata->td_flags.task_serial == 1);
732   KMP_DEBUG_ASSERT(taskdata->td_incomplete_child_tasks == 0);
733 
734   taskdata->td_flags.freed = 1;
735   ANNOTATE_HAPPENS_BEFORE(taskdata);
736 // deallocate the taskdata and shared variable blocks associated with this task
737 #if USE_FAST_MEMORY
738   __kmp_fast_free(thread, taskdata);
739 #else /* ! USE_FAST_MEMORY */
740   __kmp_thread_free(thread, taskdata);
741 #endif
742   KA_TRACE(20, ("__kmp_free_task: T#%d freed task %p\n", gtid, taskdata));
743 }
744 
745 // __kmp_free_task_and_ancestors: free the current task and ancestors without
746 // children
747 //
748 // gtid: Global thread ID of calling thread
749 // taskdata: task to free
750 // thread: thread data structure of caller
751 static void __kmp_free_task_and_ancestors(kmp_int32 gtid,
752                                           kmp_taskdata_t *taskdata,
753                                           kmp_info_t *thread) {
754   // Proxy tasks must always be allowed to free their parents
755   // because they can be run in background even in serial mode.
756   kmp_int32 team_serial =
757       (taskdata->td_flags.team_serial || taskdata->td_flags.tasking_ser) &&
758       !taskdata->td_flags.proxy;
759   KMP_DEBUG_ASSERT(taskdata->td_flags.tasktype == TASK_EXPLICIT);
760 
761   kmp_int32 children = KMP_ATOMIC_DEC(&taskdata->td_allocated_child_tasks) - 1;
762   KMP_DEBUG_ASSERT(children >= 0);
763 
764   // Now, go up the ancestor tree to see if any ancestors can now be freed.
765   while (children == 0) {
766     kmp_taskdata_t *parent_taskdata = taskdata->td_parent;
767 
768     KA_TRACE(20, ("__kmp_free_task_and_ancestors(enter): T#%d task %p complete "
769                   "and freeing itself\n",
770                   gtid, taskdata));
771 
772     // --- Deallocate my ancestor task ---
773     __kmp_free_task(gtid, taskdata, thread);
774 
775     taskdata = parent_taskdata;
776 
777     if (team_serial)
778       return;
779     // Stop checking ancestors at implicit task instead of walking up ancestor
780     // tree to avoid premature deallocation of ancestors.
781     if (taskdata->td_flags.tasktype == TASK_IMPLICIT) {
782       if (taskdata->td_dephash) { // do we need to cleanup dephash?
783         int children = KMP_ATOMIC_LD_ACQ(&taskdata->td_incomplete_child_tasks);
784         kmp_tasking_flags_t flags_old = taskdata->td_flags;
785         if (children == 0 && flags_old.complete == 1) {
786           kmp_tasking_flags_t flags_new = flags_old;
787           flags_new.complete = 0;
788           if (KMP_COMPARE_AND_STORE_ACQ32(
789                   RCAST(kmp_int32 *, &taskdata->td_flags),
790                   *RCAST(kmp_int32 *, &flags_old),
791                   *RCAST(kmp_int32 *, &flags_new))) {
792             KA_TRACE(100, ("__kmp_free_task_and_ancestors: T#%d cleans "
793                            "dephash of implicit task %p\n",
794                            gtid, taskdata));
795             // cleanup dephash of finished implicit task
796             __kmp_dephash_free_entries(thread, taskdata->td_dephash);
797           }
798         }
799       }
800       return;
801     }
802     // Predecrement simulated by "- 1" calculation
803     children = KMP_ATOMIC_DEC(&taskdata->td_allocated_child_tasks) - 1;
804     KMP_DEBUG_ASSERT(children >= 0);
805   }
806 
807   KA_TRACE(
808       20, ("__kmp_free_task_and_ancestors(exit): T#%d task %p has %d children; "
809            "not freeing it yet\n",
810            gtid, taskdata, children));
811 }
812 
813 // __kmp_task_finish: bookkeeping to do when a task finishes execution
814 //
815 // gtid: global thread ID for calling thread
816 // task: task to be finished
817 // resumed_task: task to be resumed.  (may be NULL if task is serialized)
818 //
819 // template<ompt>: effectively ompt_enabled.enabled!=0
820 // the version with ompt=false is inlined, allowing to optimize away all ompt
821 // code in this case
822 template <bool ompt>
823 static void __kmp_task_finish(kmp_int32 gtid, kmp_task_t *task,
824                               kmp_taskdata_t *resumed_task) {
825   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(task);
826   kmp_info_t *thread = __kmp_threads[gtid];
827   kmp_task_team_t *task_team =
828       thread->th.th_task_team; // might be NULL for serial teams...
829   kmp_int32 children = 0;
830 
831   KA_TRACE(10, ("__kmp_task_finish(enter): T#%d finishing task %p and resuming "
832                 "task %p\n",
833                 gtid, taskdata, resumed_task));
834 
835   KMP_DEBUG_ASSERT(taskdata->td_flags.tasktype == TASK_EXPLICIT);
836 
837 // Pop task from stack if tied
838 #ifdef BUILD_TIED_TASK_STACK
839   if (taskdata->td_flags.tiedness == TASK_TIED) {
840     __kmp_pop_task_stack(gtid, thread, taskdata);
841   }
842 #endif /* BUILD_TIED_TASK_STACK */
843 
844   if (UNLIKELY(taskdata->td_flags.tiedness == TASK_UNTIED)) {
845     // untied task needs to check the counter so that the task structure is not
846     // freed prematurely
847     kmp_int32 counter = KMP_ATOMIC_DEC(&taskdata->td_untied_count) - 1;
848     KA_TRACE(
849         20,
850         ("__kmp_task_finish: T#%d untied_count (%d) decremented for task %p\n",
851          gtid, counter, taskdata));
852     if (counter > 0) {
853       // untied task is not done, to be continued possibly by other thread, do
854       // not free it now
855       if (resumed_task == NULL) {
856         KMP_DEBUG_ASSERT(taskdata->td_flags.task_serial);
857         resumed_task = taskdata->td_parent; // In a serialized task, the resumed
858         // task is the parent
859       }
860       thread->th.th_current_task = resumed_task; // restore current_task
861       resumed_task->td_flags.executing = 1; // resume previous task
862       KA_TRACE(10, ("__kmp_task_finish(exit): T#%d partially done task %p, "
863                     "resuming task %p\n",
864                     gtid, taskdata, resumed_task));
865       return;
866     }
867   }
868 
869   // bookkeeping for resuming task:
870   // GEH - note tasking_ser => task_serial
871   KMP_DEBUG_ASSERT(
872       (taskdata->td_flags.tasking_ser || taskdata->td_flags.task_serial) ==
873       taskdata->td_flags.task_serial);
874   if (taskdata->td_flags.task_serial) {
875     if (resumed_task == NULL) {
876       resumed_task = taskdata->td_parent; // In a serialized task, the resumed
877       // task is the parent
878     }
879   } else {
880     KMP_DEBUG_ASSERT(resumed_task !=
881                      NULL); // verify that resumed task is passed as argument
882   }
883 
884   /* If the tasks' destructor thunk flag has been set, we need to invoke the
885      destructor thunk that has been generated by the compiler. The code is
886      placed here, since at this point other tasks might have been released
887      hence overlapping the destructor invocations with some other work in the
888      released tasks.  The OpenMP spec is not specific on when the destructors
889      are invoked, so we should be free to choose. */
890   if (UNLIKELY(taskdata->td_flags.destructors_thunk)) {
891     kmp_routine_entry_t destr_thunk = task->data1.destructors;
892     KMP_ASSERT(destr_thunk);
893     destr_thunk(gtid, task);
894   }
895 
896   KMP_DEBUG_ASSERT(taskdata->td_flags.complete == 0);
897   KMP_DEBUG_ASSERT(taskdata->td_flags.started == 1);
898   KMP_DEBUG_ASSERT(taskdata->td_flags.freed == 0);
899 
900   bool detach = false;
901   if (UNLIKELY(taskdata->td_flags.detachable == TASK_DETACHABLE)) {
902     if (taskdata->td_allow_completion_event.type ==
903         KMP_EVENT_ALLOW_COMPLETION) {
904       // event hasn't been fulfilled yet. Try to detach task.
905       __kmp_acquire_tas_lock(&taskdata->td_allow_completion_event.lock, gtid);
906       if (taskdata->td_allow_completion_event.type ==
907           KMP_EVENT_ALLOW_COMPLETION) {
908         // task finished execution
909         KMP_DEBUG_ASSERT(taskdata->td_flags.executing == 1);
910         taskdata->td_flags.executing = 0; // suspend the finishing task
911 
912 #if OMPT_SUPPORT
913         // For a detached task, which is not completed, we switch back
914         // the omp_fulfill_event signals completion
915         // locking is necessary to avoid a race with ompt_task_late_fulfill
916         if (ompt)
917           __ompt_task_finish(task, resumed_task, ompt_task_detach);
918 #endif
919 
920         // no access to taskdata after this point!
921         // __kmp_fulfill_event might free taskdata at any time from now
922 
923         taskdata->td_flags.proxy = TASK_PROXY; // proxify!
924         detach = true;
925       }
926       __kmp_release_tas_lock(&taskdata->td_allow_completion_event.lock, gtid);
927     }
928   }
929 
930   if (!detach) {
931     taskdata->td_flags.complete = 1; // mark the task as completed
932 
933 #if OMPT_SUPPORT
934     // This is not a detached task, we are done here
935     if (ompt)
936       __ompt_task_finish(task, resumed_task, ompt_task_complete);
937 #endif
938 
939     // Only need to keep track of count if team parallel and tasking not
940     // serialized, or task is detachable and event has already been fulfilled
941     if (!(taskdata->td_flags.team_serial || taskdata->td_flags.tasking_ser) ||
942         taskdata->td_flags.detachable == TASK_DETACHABLE ||
943         taskdata->td_flags.hidden_helper) {
944       // Predecrement simulated by "- 1" calculation
945       children =
946           KMP_ATOMIC_DEC(&taskdata->td_parent->td_incomplete_child_tasks) - 1;
947       KMP_DEBUG_ASSERT(children >= 0);
948       if (taskdata->td_taskgroup)
949         KMP_ATOMIC_DEC(&taskdata->td_taskgroup->count);
950       __kmp_release_deps(gtid, taskdata);
951     } else if (task_team && task_team->tt.tt_found_proxy_tasks) {
952       // if we found proxy tasks there could exist a dependency chain
953       // with the proxy task as origin
954       __kmp_release_deps(gtid, taskdata);
955     }
956     // td_flags.executing must be marked as 0 after __kmp_release_deps has been
957     // called. Othertwise, if a task is executed immediately from the
958     // release_deps code, the flag will be reset to 1 again by this same
959     // function
960     KMP_DEBUG_ASSERT(taskdata->td_flags.executing == 1);
961     taskdata->td_flags.executing = 0; // suspend the finishing task
962   }
963 
964   KA_TRACE(
965       20, ("__kmp_task_finish: T#%d finished task %p, %d incomplete children\n",
966            gtid, taskdata, children));
967 
968   // Free this task and then ancestor tasks if they have no children.
969   // Restore th_current_task first as suggested by John:
970   // johnmc: if an asynchronous inquiry peers into the runtime system
971   // it doesn't see the freed task as the current task.
972   thread->th.th_current_task = resumed_task;
973   if (!detach)
974     __kmp_free_task_and_ancestors(gtid, taskdata, thread);
975 
976   // TODO: GEH - make sure root team implicit task is initialized properly.
977   // KMP_DEBUG_ASSERT( resumed_task->td_flags.executing == 0 );
978   resumed_task->td_flags.executing = 1; // resume previous task
979 
980   KA_TRACE(
981       10, ("__kmp_task_finish(exit): T#%d finished task %p, resuming task %p\n",
982            gtid, taskdata, resumed_task));
983 
984   return;
985 }
986 
987 template <bool ompt>
988 static void __kmpc_omp_task_complete_if0_template(ident_t *loc_ref,
989                                                   kmp_int32 gtid,
990                                                   kmp_task_t *task) {
991   KA_TRACE(10, ("__kmpc_omp_task_complete_if0(enter): T#%d loc=%p task=%p\n",
992                 gtid, loc_ref, KMP_TASK_TO_TASKDATA(task)));
993   KMP_DEBUG_ASSERT(gtid >= 0);
994   // this routine will provide task to resume
995   __kmp_task_finish<ompt>(gtid, task, NULL);
996 
997   KA_TRACE(10, ("__kmpc_omp_task_complete_if0(exit): T#%d loc=%p task=%p\n",
998                 gtid, loc_ref, KMP_TASK_TO_TASKDATA(task)));
999 
1000 #if OMPT_SUPPORT
1001   if (ompt) {
1002     ompt_frame_t *ompt_frame;
1003     __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL);
1004     ompt_frame->enter_frame = ompt_data_none;
1005     ompt_frame->enter_frame_flags =
1006         ompt_frame_runtime | ompt_frame_framepointer;
1007   }
1008 #endif
1009 
1010   return;
1011 }
1012 
1013 #if OMPT_SUPPORT
1014 OMPT_NOINLINE
1015 void __kmpc_omp_task_complete_if0_ompt(ident_t *loc_ref, kmp_int32 gtid,
1016                                        kmp_task_t *task) {
1017   __kmpc_omp_task_complete_if0_template<true>(loc_ref, gtid, task);
1018 }
1019 #endif // OMPT_SUPPORT
1020 
1021 // __kmpc_omp_task_complete_if0: report that a task has completed execution
1022 //
1023 // loc_ref: source location information; points to end of task block.
1024 // gtid: global thread number.
1025 // task: task thunk for the completed task.
1026 void __kmpc_omp_task_complete_if0(ident_t *loc_ref, kmp_int32 gtid,
1027                                   kmp_task_t *task) {
1028 #if OMPT_SUPPORT
1029   if (UNLIKELY(ompt_enabled.enabled)) {
1030     __kmpc_omp_task_complete_if0_ompt(loc_ref, gtid, task);
1031     return;
1032   }
1033 #endif
1034   __kmpc_omp_task_complete_if0_template<false>(loc_ref, gtid, task);
1035 }
1036 
1037 #ifdef TASK_UNUSED
1038 // __kmpc_omp_task_complete: report that a task has completed execution
1039 // NEVER GENERATED BY COMPILER, DEPRECATED!!!
1040 void __kmpc_omp_task_complete(ident_t *loc_ref, kmp_int32 gtid,
1041                               kmp_task_t *task) {
1042   KA_TRACE(10, ("__kmpc_omp_task_complete(enter): T#%d loc=%p task=%p\n", gtid,
1043                 loc_ref, KMP_TASK_TO_TASKDATA(task)));
1044 
1045   __kmp_task_finish<false>(gtid, task,
1046                            NULL); // Not sure how to find task to resume
1047 
1048   KA_TRACE(10, ("__kmpc_omp_task_complete(exit): T#%d loc=%p task=%p\n", gtid,
1049                 loc_ref, KMP_TASK_TO_TASKDATA(task)));
1050   return;
1051 }
1052 #endif // TASK_UNUSED
1053 
1054 // __kmp_init_implicit_task: Initialize the appropriate fields in the implicit
1055 // task for a given thread
1056 //
1057 // loc_ref:  reference to source location of parallel region
1058 // this_thr:  thread data structure corresponding to implicit task
1059 // team: team for this_thr
1060 // tid: thread id of given thread within team
1061 // set_curr_task: TRUE if need to push current task to thread
1062 // NOTE: Routine does not set up the implicit task ICVS.  This is assumed to
1063 // have already been done elsewhere.
1064 // TODO: Get better loc_ref.  Value passed in may be NULL
1065 void __kmp_init_implicit_task(ident_t *loc_ref, kmp_info_t *this_thr,
1066                               kmp_team_t *team, int tid, int set_curr_task) {
1067   kmp_taskdata_t *task = &team->t.t_implicit_task_taskdata[tid];
1068 
1069   KF_TRACE(
1070       10,
1071       ("__kmp_init_implicit_task(enter): T#:%d team=%p task=%p, reinit=%s\n",
1072        tid, team, task, set_curr_task ? "TRUE" : "FALSE"));
1073 
1074   task->td_task_id = KMP_GEN_TASK_ID();
1075   task->td_team = team;
1076   //    task->td_parent   = NULL;  // fix for CQ230101 (broken parent task info
1077   //    in debugger)
1078   task->td_ident = loc_ref;
1079   task->td_taskwait_ident = NULL;
1080   task->td_taskwait_counter = 0;
1081   task->td_taskwait_thread = 0;
1082 
1083   task->td_flags.tiedness = TASK_TIED;
1084   task->td_flags.tasktype = TASK_IMPLICIT;
1085   task->td_flags.proxy = TASK_FULL;
1086 
1087   // All implicit tasks are executed immediately, not deferred
1088   task->td_flags.task_serial = 1;
1089   task->td_flags.tasking_ser = (__kmp_tasking_mode == tskm_immediate_exec);
1090   task->td_flags.team_serial = (team->t.t_serialized) ? 1 : 0;
1091 
1092   task->td_flags.started = 1;
1093   task->td_flags.executing = 1;
1094   task->td_flags.complete = 0;
1095   task->td_flags.freed = 0;
1096 
1097   task->td_depnode = NULL;
1098   task->td_last_tied = task;
1099   task->td_allow_completion_event.type = KMP_EVENT_UNINITIALIZED;
1100 
1101   if (set_curr_task) { // only do this init first time thread is created
1102     KMP_ATOMIC_ST_REL(&task->td_incomplete_child_tasks, 0);
1103     // Not used: don't need to deallocate implicit task
1104     KMP_ATOMIC_ST_REL(&task->td_allocated_child_tasks, 0);
1105     task->td_taskgroup = NULL; // An implicit task does not have taskgroup
1106     task->td_dephash = NULL;
1107     __kmp_push_current_task_to_thread(this_thr, team, tid);
1108   } else {
1109     KMP_DEBUG_ASSERT(task->td_incomplete_child_tasks == 0);
1110     KMP_DEBUG_ASSERT(task->td_allocated_child_tasks == 0);
1111   }
1112 
1113 #if OMPT_SUPPORT
1114   if (UNLIKELY(ompt_enabled.enabled))
1115     __ompt_task_init(task, tid);
1116 #endif
1117 
1118   KF_TRACE(10, ("__kmp_init_implicit_task(exit): T#:%d team=%p task=%p\n", tid,
1119                 team, task));
1120 }
1121 
1122 // __kmp_finish_implicit_task: Release resources associated to implicit tasks
1123 // at the end of parallel regions. Some resources are kept for reuse in the next
1124 // parallel region.
1125 //
1126 // thread:  thread data structure corresponding to implicit task
1127 void __kmp_finish_implicit_task(kmp_info_t *thread) {
1128   kmp_taskdata_t *task = thread->th.th_current_task;
1129   if (task->td_dephash) {
1130     int children;
1131     task->td_flags.complete = 1;
1132     children = KMP_ATOMIC_LD_ACQ(&task->td_incomplete_child_tasks);
1133     kmp_tasking_flags_t flags_old = task->td_flags;
1134     if (children == 0 && flags_old.complete == 1) {
1135       kmp_tasking_flags_t flags_new = flags_old;
1136       flags_new.complete = 0;
1137       if (KMP_COMPARE_AND_STORE_ACQ32(RCAST(kmp_int32 *, &task->td_flags),
1138                                       *RCAST(kmp_int32 *, &flags_old),
1139                                       *RCAST(kmp_int32 *, &flags_new))) {
1140         KA_TRACE(100, ("__kmp_finish_implicit_task: T#%d cleans "
1141                        "dephash of implicit task %p\n",
1142                        thread->th.th_info.ds.ds_gtid, task));
1143         __kmp_dephash_free_entries(thread, task->td_dephash);
1144       }
1145     }
1146   }
1147 }
1148 
1149 // __kmp_free_implicit_task: Release resources associated to implicit tasks
1150 // when these are destroyed regions
1151 //
1152 // thread:  thread data structure corresponding to implicit task
1153 void __kmp_free_implicit_task(kmp_info_t *thread) {
1154   kmp_taskdata_t *task = thread->th.th_current_task;
1155   if (task && task->td_dephash) {
1156     __kmp_dephash_free(thread, task->td_dephash);
1157     task->td_dephash = NULL;
1158   }
1159 }
1160 
1161 // Round up a size to a power of two specified by val: Used to insert padding
1162 // between structures co-allocated using a single malloc() call
1163 static size_t __kmp_round_up_to_val(size_t size, size_t val) {
1164   if (size & (val - 1)) {
1165     size &= ~(val - 1);
1166     if (size <= KMP_SIZE_T_MAX - val) {
1167       size += val; // Round up if there is no overflow.
1168     }
1169   }
1170   return size;
1171 } // __kmp_round_up_to_va
1172 
1173 // __kmp_task_alloc: Allocate the taskdata and task data structures for a task
1174 //
1175 // loc_ref: source location information
1176 // gtid: global thread number.
1177 // flags: include tiedness & task type (explicit vs. implicit) of the ''new''
1178 // task encountered. Converted from kmp_int32 to kmp_tasking_flags_t in routine.
1179 // sizeof_kmp_task_t:  Size in bytes of kmp_task_t data structure including
1180 // private vars accessed in task.
1181 // sizeof_shareds:  Size in bytes of array of pointers to shared vars accessed
1182 // in task.
1183 // task_entry: Pointer to task code entry point generated by compiler.
1184 // returns: a pointer to the allocated kmp_task_t structure (task).
1185 kmp_task_t *__kmp_task_alloc(ident_t *loc_ref, kmp_int32 gtid,
1186                              kmp_tasking_flags_t *flags,
1187                              size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1188                              kmp_routine_entry_t task_entry) {
1189   kmp_task_t *task;
1190   kmp_taskdata_t *taskdata;
1191   kmp_info_t *thread = __kmp_threads[gtid];
1192   kmp_info_t *encountering_thread = thread;
1193   kmp_team_t *team = thread->th.th_team;
1194   kmp_taskdata_t *parent_task = thread->th.th_current_task;
1195   size_t shareds_offset;
1196 
1197   if (UNLIKELY(!TCR_4(__kmp_init_middle)))
1198     __kmp_middle_initialize();
1199 
1200   if (flags->hidden_helper) {
1201     if (__kmp_enable_hidden_helper) {
1202       if (!TCR_4(__kmp_init_hidden_helper))
1203         __kmp_hidden_helper_initialize();
1204 
1205       // For a hidden helper task encountered by a regular thread, we will push
1206       // the task to the (gtid%__kmp_hidden_helper_threads_num)-th hidden helper
1207       // thread.
1208       if (!KMP_HIDDEN_HELPER_THREAD(gtid)) {
1209         thread = __kmp_threads[KMP_GTID_TO_SHADOW_GTID(gtid)];
1210         // We don't change the parent-child relation for hidden helper task as
1211         // we need that to do per-task-region synchronization.
1212       }
1213     } else {
1214       // If the hidden helper task is not enabled, reset the flag to FALSE.
1215       flags->hidden_helper = FALSE;
1216     }
1217   }
1218 
1219   KA_TRACE(10, ("__kmp_task_alloc(enter): T#%d loc=%p, flags=(0x%x) "
1220                 "sizeof_task=%ld sizeof_shared=%ld entry=%p\n",
1221                 gtid, loc_ref, *((kmp_int32 *)flags), sizeof_kmp_task_t,
1222                 sizeof_shareds, task_entry));
1223 
1224   if (parent_task->td_flags.final) {
1225     if (flags->merged_if0) {
1226     }
1227     flags->final = 1;
1228   }
1229 
1230   if (flags->tiedness == TASK_UNTIED && !team->t.t_serialized) {
1231     // Untied task encountered causes the TSC algorithm to check entire deque of
1232     // the victim thread. If no untied task encountered, then checking the head
1233     // of the deque should be enough.
1234     KMP_CHECK_UPDATE(
1235         encountering_thread->th.th_task_team->tt.tt_untied_task_encountered, 1);
1236   }
1237 
1238   // Detachable tasks are not proxy tasks yet but could be in the future. Doing
1239   // the tasking setup
1240   // when that happens is too late.
1241   if (UNLIKELY(flags->proxy == TASK_PROXY ||
1242                flags->detachable == TASK_DETACHABLE || flags->hidden_helper)) {
1243     if (flags->proxy == TASK_PROXY) {
1244       flags->tiedness = TASK_UNTIED;
1245       flags->merged_if0 = 1;
1246     }
1247     /* are we running in a sequential parallel or tskm_immediate_exec... we need
1248        tasking support enabled */
1249     if ((encountering_thread->th.th_task_team) == NULL) {
1250       /* This should only happen if the team is serialized
1251           setup a task team and propagate it to the thread */
1252       KMP_DEBUG_ASSERT(team->t.t_serialized);
1253       KA_TRACE(30,
1254                ("T#%d creating task team in __kmp_task_alloc for proxy task\n",
1255                 gtid));
1256       __kmp_task_team_setup(
1257           encountering_thread, team,
1258           1); // 1 indicates setup the current team regardless of nthreads
1259       encountering_thread->th.th_task_team =
1260           team->t.t_task_team[encountering_thread->th.th_task_state];
1261     }
1262     kmp_task_team_t *task_team = encountering_thread->th.th_task_team;
1263 
1264     /* tasking must be enabled now as the task might not be pushed */
1265     if (!KMP_TASKING_ENABLED(task_team)) {
1266       KA_TRACE(
1267           30,
1268           ("T#%d enabling tasking in __kmp_task_alloc for proxy task\n", gtid));
1269       __kmp_enable_tasking(task_team, encountering_thread);
1270       kmp_int32 tid = encountering_thread->th.th_info.ds.ds_tid;
1271       kmp_thread_data_t *thread_data = &task_team->tt.tt_threads_data[tid];
1272       // No lock needed since only owner can allocate
1273       if (thread_data->td.td_deque == NULL) {
1274         __kmp_alloc_task_deque(encountering_thread, thread_data);
1275       }
1276     }
1277 
1278     if ((flags->proxy == TASK_PROXY || flags->detachable == TASK_DETACHABLE) &&
1279         task_team->tt.tt_found_proxy_tasks == FALSE)
1280       TCW_4(task_team->tt.tt_found_proxy_tasks, TRUE);
1281     if (flags->hidden_helper &&
1282         task_team->tt.tt_hidden_helper_task_encountered == FALSE)
1283       TCW_4(task_team->tt.tt_hidden_helper_task_encountered, TRUE);
1284   }
1285 
1286   // Calculate shared structure offset including padding after kmp_task_t struct
1287   // to align pointers in shared struct
1288   shareds_offset = sizeof(kmp_taskdata_t) + sizeof_kmp_task_t;
1289   shareds_offset = __kmp_round_up_to_val(shareds_offset, sizeof(void *));
1290 
1291   // Allocate a kmp_taskdata_t block and a kmp_task_t block.
1292   KA_TRACE(30, ("__kmp_task_alloc: T#%d First malloc size: %ld\n", gtid,
1293                 shareds_offset));
1294   KA_TRACE(30, ("__kmp_task_alloc: T#%d Second malloc size: %ld\n", gtid,
1295                 sizeof_shareds));
1296 
1297   // Avoid double allocation here by combining shareds with taskdata
1298 #if USE_FAST_MEMORY
1299   taskdata = (kmp_taskdata_t *)__kmp_fast_allocate(
1300       encountering_thread, shareds_offset + sizeof_shareds);
1301 #else /* ! USE_FAST_MEMORY */
1302   taskdata = (kmp_taskdata_t *)__kmp_thread_malloc(
1303       encountering_thread, shareds_offset + sizeof_shareds);
1304 #endif /* USE_FAST_MEMORY */
1305   ANNOTATE_HAPPENS_AFTER(taskdata);
1306 
1307   task = KMP_TASKDATA_TO_TASK(taskdata);
1308 
1309 // Make sure task & taskdata are aligned appropriately
1310 #if KMP_ARCH_X86 || KMP_ARCH_PPC64 || !KMP_HAVE_QUAD
1311   KMP_DEBUG_ASSERT((((kmp_uintptr_t)taskdata) & (sizeof(double) - 1)) == 0);
1312   KMP_DEBUG_ASSERT((((kmp_uintptr_t)task) & (sizeof(double) - 1)) == 0);
1313 #else
1314   KMP_DEBUG_ASSERT((((kmp_uintptr_t)taskdata) & (sizeof(_Quad) - 1)) == 0);
1315   KMP_DEBUG_ASSERT((((kmp_uintptr_t)task) & (sizeof(_Quad) - 1)) == 0);
1316 #endif
1317   if (sizeof_shareds > 0) {
1318     // Avoid double allocation here by combining shareds with taskdata
1319     task->shareds = &((char *)taskdata)[shareds_offset];
1320     // Make sure shareds struct is aligned to pointer size
1321     KMP_DEBUG_ASSERT((((kmp_uintptr_t)task->shareds) & (sizeof(void *) - 1)) ==
1322                      0);
1323   } else {
1324     task->shareds = NULL;
1325   }
1326   task->routine = task_entry;
1327   task->part_id = 0; // AC: Always start with 0 part id
1328 
1329   taskdata->td_task_id = KMP_GEN_TASK_ID();
1330   taskdata->td_team = thread->th.th_team;
1331   taskdata->td_alloc_thread = encountering_thread;
1332   taskdata->td_parent = parent_task;
1333   taskdata->td_level = parent_task->td_level + 1; // increment nesting level
1334   KMP_ATOMIC_ST_RLX(&taskdata->td_untied_count, 0);
1335   taskdata->td_ident = loc_ref;
1336   taskdata->td_taskwait_ident = NULL;
1337   taskdata->td_taskwait_counter = 0;
1338   taskdata->td_taskwait_thread = 0;
1339   KMP_DEBUG_ASSERT(taskdata->td_parent != NULL);
1340   // avoid copying icvs for proxy tasks
1341   if (flags->proxy == TASK_FULL)
1342     copy_icvs(&taskdata->td_icvs, &taskdata->td_parent->td_icvs);
1343 
1344   taskdata->td_flags.tiedness = flags->tiedness;
1345   taskdata->td_flags.final = flags->final;
1346   taskdata->td_flags.merged_if0 = flags->merged_if0;
1347   taskdata->td_flags.destructors_thunk = flags->destructors_thunk;
1348   taskdata->td_flags.proxy = flags->proxy;
1349   taskdata->td_flags.detachable = flags->detachable;
1350   taskdata->td_flags.hidden_helper = flags->hidden_helper;
1351   taskdata->encountering_gtid = gtid;
1352   taskdata->td_task_team = thread->th.th_task_team;
1353   taskdata->td_size_alloc = shareds_offset + sizeof_shareds;
1354   taskdata->td_flags.tasktype = TASK_EXPLICIT;
1355 
1356   // GEH - TODO: fix this to copy parent task's value of tasking_ser flag
1357   taskdata->td_flags.tasking_ser = (__kmp_tasking_mode == tskm_immediate_exec);
1358 
1359   // GEH - TODO: fix this to copy parent task's value of team_serial flag
1360   taskdata->td_flags.team_serial = (team->t.t_serialized) ? 1 : 0;
1361 
1362   // GEH - Note we serialize the task if the team is serialized to make sure
1363   // implicit parallel region tasks are not left until program termination to
1364   // execute. Also, it helps locality to execute immediately.
1365 
1366   taskdata->td_flags.task_serial =
1367       (parent_task->td_flags.final || taskdata->td_flags.team_serial ||
1368        taskdata->td_flags.tasking_ser || flags->merged_if0);
1369 
1370   taskdata->td_flags.started = 0;
1371   taskdata->td_flags.executing = 0;
1372   taskdata->td_flags.complete = 0;
1373   taskdata->td_flags.freed = 0;
1374 
1375   taskdata->td_flags.native = flags->native;
1376 
1377   KMP_ATOMIC_ST_RLX(&taskdata->td_incomplete_child_tasks, 0);
1378   // start at one because counts current task and children
1379   KMP_ATOMIC_ST_RLX(&taskdata->td_allocated_child_tasks, 1);
1380   taskdata->td_taskgroup =
1381       parent_task->td_taskgroup; // task inherits taskgroup from the parent task
1382   taskdata->td_dephash = NULL;
1383   taskdata->td_depnode = NULL;
1384   if (flags->tiedness == TASK_UNTIED)
1385     taskdata->td_last_tied = NULL; // will be set when the task is scheduled
1386   else
1387     taskdata->td_last_tied = taskdata;
1388   taskdata->td_allow_completion_event.type = KMP_EVENT_UNINITIALIZED;
1389 #if OMPT_SUPPORT
1390   if (UNLIKELY(ompt_enabled.enabled))
1391     __ompt_task_init(taskdata, gtid);
1392 #endif
1393   // Only need to keep track of child task counts if team parallel and tasking
1394   // not serialized or if it is a proxy or detachable or hidden helper task
1395   if (flags->proxy == TASK_PROXY || flags->detachable == TASK_DETACHABLE ||
1396       flags->hidden_helper ||
1397       !(taskdata->td_flags.team_serial || taskdata->td_flags.tasking_ser)) {
1398     KMP_ATOMIC_INC(&parent_task->td_incomplete_child_tasks);
1399     if (parent_task->td_taskgroup)
1400       KMP_ATOMIC_INC(&parent_task->td_taskgroup->count);
1401     // Only need to keep track of allocated child tasks for explicit tasks since
1402     // implicit not deallocated
1403     if (taskdata->td_parent->td_flags.tasktype == TASK_EXPLICIT) {
1404       KMP_ATOMIC_INC(&taskdata->td_parent->td_allocated_child_tasks);
1405     }
1406   }
1407 
1408   if (flags->hidden_helper) {
1409     taskdata->td_flags.task_serial = FALSE;
1410     // Increment the number of hidden helper tasks to be executed
1411     KMP_ATOMIC_INC(&__kmp_unexecuted_hidden_helper_tasks);
1412   }
1413 
1414   KA_TRACE(20, ("__kmp_task_alloc(exit): T#%d created task %p parent=%p\n",
1415                 gtid, taskdata, taskdata->td_parent));
1416   ANNOTATE_HAPPENS_BEFORE(task);
1417 
1418   return task;
1419 }
1420 
1421 kmp_task_t *__kmpc_omp_task_alloc(ident_t *loc_ref, kmp_int32 gtid,
1422                                   kmp_int32 flags, size_t sizeof_kmp_task_t,
1423                                   size_t sizeof_shareds,
1424                                   kmp_routine_entry_t task_entry) {
1425   kmp_task_t *retval;
1426   kmp_tasking_flags_t *input_flags = (kmp_tasking_flags_t *)&flags;
1427   __kmp_assert_valid_gtid(gtid);
1428   input_flags->native = FALSE;
1429   // __kmp_task_alloc() sets up all other runtime flags
1430   KA_TRACE(10, ("__kmpc_omp_task_alloc(enter): T#%d loc=%p, flags=(%s %s %s) "
1431                 "sizeof_task=%ld sizeof_shared=%ld entry=%p\n",
1432                 gtid, loc_ref, input_flags->tiedness ? "tied  " : "untied",
1433                 input_flags->proxy ? "proxy" : "",
1434                 input_flags->detachable ? "detachable" : "", sizeof_kmp_task_t,
1435                 sizeof_shareds, task_entry));
1436 
1437   retval = __kmp_task_alloc(loc_ref, gtid, input_flags, sizeof_kmp_task_t,
1438                             sizeof_shareds, task_entry);
1439 
1440   KA_TRACE(20, ("__kmpc_omp_task_alloc(exit): T#%d retval %p\n", gtid, retval));
1441 
1442   return retval;
1443 }
1444 
1445 kmp_task_t *__kmpc_omp_target_task_alloc(ident_t *loc_ref, kmp_int32 gtid,
1446                                          kmp_int32 flags,
1447                                          size_t sizeof_kmp_task_t,
1448                                          size_t sizeof_shareds,
1449                                          kmp_routine_entry_t task_entry,
1450                                          kmp_int64 device_id) {
1451   if (__kmp_enable_hidden_helper) {
1452     auto &input_flags = reinterpret_cast<kmp_tasking_flags_t &>(flags);
1453     input_flags.hidden_helper = TRUE;
1454   }
1455 
1456   return __kmpc_omp_task_alloc(loc_ref, gtid, flags, sizeof_kmp_task_t,
1457                                sizeof_shareds, task_entry);
1458 }
1459 
1460 /*!
1461 @ingroup TASKING
1462 @param loc_ref location of the original task directive
1463 @param gtid Global Thread ID of encountering thread
1464 @param new_task task thunk allocated by __kmpc_omp_task_alloc() for the ''new
1465 task''
1466 @param naffins Number of affinity items
1467 @param affin_list List of affinity items
1468 @return Returns non-zero if registering affinity information was not successful.
1469  Returns 0 if registration was successful
1470 This entry registers the affinity information attached to a task with the task
1471 thunk structure kmp_taskdata_t.
1472 */
1473 kmp_int32
1474 __kmpc_omp_reg_task_with_affinity(ident_t *loc_ref, kmp_int32 gtid,
1475                                   kmp_task_t *new_task, kmp_int32 naffins,
1476                                   kmp_task_affinity_info_t *affin_list) {
1477   return 0;
1478 }
1479 
1480 //  __kmp_invoke_task: invoke the specified task
1481 //
1482 // gtid: global thread ID of caller
1483 // task: the task to invoke
1484 // current_task: the task to resume after task invocation
1485 static void __kmp_invoke_task(kmp_int32 gtid, kmp_task_t *task,
1486                               kmp_taskdata_t *current_task) {
1487   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(task);
1488   kmp_info_t *thread;
1489   int discard = 0 /* false */;
1490   KA_TRACE(
1491       30, ("__kmp_invoke_task(enter): T#%d invoking task %p, current_task=%p\n",
1492            gtid, taskdata, current_task));
1493   KMP_DEBUG_ASSERT(task);
1494   if (UNLIKELY(taskdata->td_flags.proxy == TASK_PROXY &&
1495                taskdata->td_flags.complete == 1)) {
1496     // This is a proxy task that was already completed but it needs to run
1497     // its bottom-half finish
1498     KA_TRACE(
1499         30,
1500         ("__kmp_invoke_task: T#%d running bottom finish for proxy task %p\n",
1501          gtid, taskdata));
1502 
1503     __kmp_bottom_half_finish_proxy(gtid, task);
1504 
1505     KA_TRACE(30, ("__kmp_invoke_task(exit): T#%d completed bottom finish for "
1506                   "proxy task %p, resuming task %p\n",
1507                   gtid, taskdata, current_task));
1508 
1509     return;
1510   }
1511 
1512 #if OMPT_SUPPORT
1513   // For untied tasks, the first task executed only calls __kmpc_omp_task and
1514   // does not execute code.
1515   ompt_thread_info_t oldInfo;
1516   if (UNLIKELY(ompt_enabled.enabled)) {
1517     // Store the threads states and restore them after the task
1518     thread = __kmp_threads[gtid];
1519     oldInfo = thread->th.ompt_thread_info;
1520     thread->th.ompt_thread_info.wait_id = 0;
1521     thread->th.ompt_thread_info.state = (thread->th.th_team_serialized)
1522                                             ? ompt_state_work_serial
1523                                             : ompt_state_work_parallel;
1524     taskdata->ompt_task_info.frame.exit_frame.ptr = OMPT_GET_FRAME_ADDRESS(0);
1525   }
1526 #endif
1527 
1528   // Decreament the counter of hidden helper tasks to be executed
1529   if (taskdata->td_flags.hidden_helper) {
1530     // Hidden helper tasks can only be executed by hidden helper threads
1531     KMP_ASSERT(KMP_HIDDEN_HELPER_THREAD(gtid));
1532     KMP_ATOMIC_DEC(&__kmp_unexecuted_hidden_helper_tasks);
1533   }
1534 
1535   // Proxy tasks are not handled by the runtime
1536   if (taskdata->td_flags.proxy != TASK_PROXY) {
1537     ANNOTATE_HAPPENS_AFTER(task);
1538     __kmp_task_start(gtid, task, current_task); // OMPT only if not discarded
1539   }
1540 
1541   // TODO: cancel tasks if the parallel region has also been cancelled
1542   // TODO: check if this sequence can be hoisted above __kmp_task_start
1543   // if cancellation has been enabled for this run ...
1544   if (UNLIKELY(__kmp_omp_cancellation)) {
1545     thread = __kmp_threads[gtid];
1546     kmp_team_t *this_team = thread->th.th_team;
1547     kmp_taskgroup_t *taskgroup = taskdata->td_taskgroup;
1548     if ((taskgroup && taskgroup->cancel_request) ||
1549         (this_team->t.t_cancel_request == cancel_parallel)) {
1550 #if OMPT_SUPPORT && OMPT_OPTIONAL
1551       ompt_data_t *task_data;
1552       if (UNLIKELY(ompt_enabled.ompt_callback_cancel)) {
1553         __ompt_get_task_info_internal(0, NULL, &task_data, NULL, NULL, NULL);
1554         ompt_callbacks.ompt_callback(ompt_callback_cancel)(
1555             task_data,
1556             ((taskgroup && taskgroup->cancel_request) ? ompt_cancel_taskgroup
1557                                                       : ompt_cancel_parallel) |
1558                 ompt_cancel_discarded_task,
1559             NULL);
1560       }
1561 #endif
1562       KMP_COUNT_BLOCK(TASK_cancelled);
1563       // this task belongs to a task group and we need to cancel it
1564       discard = 1 /* true */;
1565     }
1566   }
1567 
1568   // Invoke the task routine and pass in relevant data.
1569   // Thunks generated by gcc take a different argument list.
1570   if (!discard) {
1571     if (taskdata->td_flags.tiedness == TASK_UNTIED) {
1572       taskdata->td_last_tied = current_task->td_last_tied;
1573       KMP_DEBUG_ASSERT(taskdata->td_last_tied);
1574     }
1575 #if KMP_STATS_ENABLED
1576     KMP_COUNT_BLOCK(TASK_executed);
1577     switch (KMP_GET_THREAD_STATE()) {
1578     case FORK_JOIN_BARRIER:
1579       KMP_PUSH_PARTITIONED_TIMER(OMP_task_join_bar);
1580       break;
1581     case PLAIN_BARRIER:
1582       KMP_PUSH_PARTITIONED_TIMER(OMP_task_plain_bar);
1583       break;
1584     case TASKYIELD:
1585       KMP_PUSH_PARTITIONED_TIMER(OMP_task_taskyield);
1586       break;
1587     case TASKWAIT:
1588       KMP_PUSH_PARTITIONED_TIMER(OMP_task_taskwait);
1589       break;
1590     case TASKGROUP:
1591       KMP_PUSH_PARTITIONED_TIMER(OMP_task_taskgroup);
1592       break;
1593     default:
1594       KMP_PUSH_PARTITIONED_TIMER(OMP_task_immediate);
1595       break;
1596     }
1597 #endif // KMP_STATS_ENABLED
1598 
1599 // OMPT task begin
1600 #if OMPT_SUPPORT
1601     if (UNLIKELY(ompt_enabled.enabled))
1602       __ompt_task_start(task, current_task, gtid);
1603 #endif
1604 
1605 #if USE_ITT_BUILD && USE_ITT_NOTIFY
1606     kmp_uint64 cur_time;
1607     kmp_int32 kmp_itt_count_task =
1608         __kmp_forkjoin_frames_mode == 3 && !taskdata->td_flags.task_serial &&
1609         current_task->td_flags.tasktype == TASK_IMPLICIT;
1610     if (kmp_itt_count_task) {
1611       thread = __kmp_threads[gtid];
1612       // Time outer level explicit task on barrier for adjusting imbalance time
1613       if (thread->th.th_bar_arrive_time)
1614         cur_time = __itt_get_timestamp();
1615       else
1616         kmp_itt_count_task = 0; // thread is not on a barrier - skip timing
1617     }
1618     KMP_FSYNC_ACQUIRED(taskdata); // acquired self (new task)
1619 #endif
1620 
1621 #ifdef KMP_GOMP_COMPAT
1622     if (taskdata->td_flags.native) {
1623       ((void (*)(void *))(*(task->routine)))(task->shareds);
1624     } else
1625 #endif /* KMP_GOMP_COMPAT */
1626     {
1627       (*(task->routine))(gtid, task);
1628     }
1629     KMP_POP_PARTITIONED_TIMER();
1630 
1631 #if USE_ITT_BUILD && USE_ITT_NOTIFY
1632     if (kmp_itt_count_task) {
1633       // Barrier imbalance - adjust arrive time with the task duration
1634       thread->th.th_bar_arrive_time += (__itt_get_timestamp() - cur_time);
1635     }
1636     KMP_FSYNC_CANCEL(taskdata); // destroy self (just executed)
1637     KMP_FSYNC_RELEASING(taskdata->td_parent); // releasing parent
1638 #endif
1639   }
1640 
1641   // Proxy tasks are not handled by the runtime
1642   if (taskdata->td_flags.proxy != TASK_PROXY) {
1643     ANNOTATE_HAPPENS_BEFORE(taskdata->td_parent);
1644 #if OMPT_SUPPORT
1645     if (UNLIKELY(ompt_enabled.enabled)) {
1646       thread->th.ompt_thread_info = oldInfo;
1647       if (taskdata->td_flags.tiedness == TASK_TIED) {
1648         taskdata->ompt_task_info.frame.exit_frame = ompt_data_none;
1649       }
1650       __kmp_task_finish<true>(gtid, task, current_task);
1651     } else
1652 #endif
1653       __kmp_task_finish<false>(gtid, task, current_task);
1654   }
1655 
1656   KA_TRACE(
1657       30,
1658       ("__kmp_invoke_task(exit): T#%d completed task %p, resuming task %p\n",
1659        gtid, taskdata, current_task));
1660   return;
1661 }
1662 
1663 // __kmpc_omp_task_parts: Schedule a thread-switchable task for execution
1664 //
1665 // loc_ref: location of original task pragma (ignored)
1666 // gtid: Global Thread ID of encountering thread
1667 // new_task: task thunk allocated by __kmp_omp_task_alloc() for the ''new task''
1668 // Returns:
1669 //    TASK_CURRENT_NOT_QUEUED (0) if did not suspend and queue current task to
1670 //    be resumed later.
1671 //    TASK_CURRENT_QUEUED (1) if suspended and queued the current task to be
1672 //    resumed later.
1673 kmp_int32 __kmpc_omp_task_parts(ident_t *loc_ref, kmp_int32 gtid,
1674                                 kmp_task_t *new_task) {
1675   kmp_taskdata_t *new_taskdata = KMP_TASK_TO_TASKDATA(new_task);
1676 
1677   KA_TRACE(10, ("__kmpc_omp_task_parts(enter): T#%d loc=%p task=%p\n", gtid,
1678                 loc_ref, new_taskdata));
1679 
1680 #if OMPT_SUPPORT
1681   kmp_taskdata_t *parent;
1682   if (UNLIKELY(ompt_enabled.enabled)) {
1683     parent = new_taskdata->td_parent;
1684     if (ompt_enabled.ompt_callback_task_create) {
1685       ompt_data_t task_data = ompt_data_none;
1686       ompt_callbacks.ompt_callback(ompt_callback_task_create)(
1687           parent ? &(parent->ompt_task_info.task_data) : &task_data,
1688           parent ? &(parent->ompt_task_info.frame) : NULL,
1689           &(new_taskdata->ompt_task_info.task_data), ompt_task_explicit, 0,
1690           OMPT_GET_RETURN_ADDRESS(0));
1691     }
1692   }
1693 #endif
1694 
1695   /* Should we execute the new task or queue it? For now, let's just always try
1696      to queue it.  If the queue fills up, then we'll execute it.  */
1697 
1698   if (__kmp_push_task(gtid, new_task) == TASK_NOT_PUSHED) // if cannot defer
1699   { // Execute this task immediately
1700     kmp_taskdata_t *current_task = __kmp_threads[gtid]->th.th_current_task;
1701     new_taskdata->td_flags.task_serial = 1;
1702     __kmp_invoke_task(gtid, new_task, current_task);
1703   }
1704 
1705   KA_TRACE(
1706       10,
1707       ("__kmpc_omp_task_parts(exit): T#%d returning TASK_CURRENT_NOT_QUEUED: "
1708        "loc=%p task=%p, return: TASK_CURRENT_NOT_QUEUED\n",
1709        gtid, loc_ref, new_taskdata));
1710 
1711   ANNOTATE_HAPPENS_BEFORE(new_task);
1712 #if OMPT_SUPPORT
1713   if (UNLIKELY(ompt_enabled.enabled)) {
1714     parent->ompt_task_info.frame.enter_frame = ompt_data_none;
1715   }
1716 #endif
1717   return TASK_CURRENT_NOT_QUEUED;
1718 }
1719 
1720 // __kmp_omp_task: Schedule a non-thread-switchable task for execution
1721 //
1722 // gtid: Global Thread ID of encountering thread
1723 // new_task:non-thread-switchable task thunk allocated by __kmp_omp_task_alloc()
1724 // serialize_immediate: if TRUE then if the task is executed immediately its
1725 // execution will be serialized
1726 // Returns:
1727 //    TASK_CURRENT_NOT_QUEUED (0) if did not suspend and queue current task to
1728 //    be resumed later.
1729 //    TASK_CURRENT_QUEUED (1) if suspended and queued the current task to be
1730 //    resumed later.
1731 kmp_int32 __kmp_omp_task(kmp_int32 gtid, kmp_task_t *new_task,
1732                          bool serialize_immediate) {
1733   kmp_taskdata_t *new_taskdata = KMP_TASK_TO_TASKDATA(new_task);
1734 
1735   /* Should we execute the new task or queue it? For now, let's just always try
1736      to queue it.  If the queue fills up, then we'll execute it.  */
1737   if (new_taskdata->td_flags.proxy == TASK_PROXY ||
1738       __kmp_push_task(gtid, new_task) == TASK_NOT_PUSHED) // if cannot defer
1739   { // Execute this task immediately
1740     kmp_taskdata_t *current_task = __kmp_threads[gtid]->th.th_current_task;
1741     if (serialize_immediate)
1742       new_taskdata->td_flags.task_serial = 1;
1743     __kmp_invoke_task(gtid, new_task, current_task);
1744   }
1745 
1746   ANNOTATE_HAPPENS_BEFORE(new_task);
1747   return TASK_CURRENT_NOT_QUEUED;
1748 }
1749 
1750 // __kmpc_omp_task: Wrapper around __kmp_omp_task to schedule a
1751 // non-thread-switchable task from the parent thread only!
1752 //
1753 // loc_ref: location of original task pragma (ignored)
1754 // gtid: Global Thread ID of encountering thread
1755 // new_task: non-thread-switchable task thunk allocated by
1756 // __kmp_omp_task_alloc()
1757 // Returns:
1758 //    TASK_CURRENT_NOT_QUEUED (0) if did not suspend and queue current task to
1759 //    be resumed later.
1760 //    TASK_CURRENT_QUEUED (1) if suspended and queued the current task to be
1761 //    resumed later.
1762 kmp_int32 __kmpc_omp_task(ident_t *loc_ref, kmp_int32 gtid,
1763                           kmp_task_t *new_task) {
1764   kmp_int32 res;
1765   KMP_SET_THREAD_STATE_BLOCK(EXPLICIT_TASK);
1766 
1767 #if KMP_DEBUG || OMPT_SUPPORT
1768   kmp_taskdata_t *new_taskdata = KMP_TASK_TO_TASKDATA(new_task);
1769 #endif
1770   KA_TRACE(10, ("__kmpc_omp_task(enter): T#%d loc=%p task=%p\n", gtid, loc_ref,
1771                 new_taskdata));
1772   __kmp_assert_valid_gtid(gtid);
1773 
1774 #if OMPT_SUPPORT
1775   kmp_taskdata_t *parent = NULL;
1776   if (UNLIKELY(ompt_enabled.enabled)) {
1777     if (!new_taskdata->td_flags.started) {
1778       OMPT_STORE_RETURN_ADDRESS(gtid);
1779       parent = new_taskdata->td_parent;
1780       if (!parent->ompt_task_info.frame.enter_frame.ptr) {
1781         parent->ompt_task_info.frame.enter_frame.ptr =
1782             OMPT_GET_FRAME_ADDRESS(0);
1783       }
1784       if (ompt_enabled.ompt_callback_task_create) {
1785         ompt_data_t task_data = ompt_data_none;
1786         ompt_callbacks.ompt_callback(ompt_callback_task_create)(
1787             parent ? &(parent->ompt_task_info.task_data) : &task_data,
1788             parent ? &(parent->ompt_task_info.frame) : NULL,
1789             &(new_taskdata->ompt_task_info.task_data),
1790             ompt_task_explicit | TASK_TYPE_DETAILS_FORMAT(new_taskdata), 0,
1791             OMPT_LOAD_RETURN_ADDRESS(gtid));
1792       }
1793     } else {
1794       // We are scheduling the continuation of an UNTIED task.
1795       // Scheduling back to the parent task.
1796       __ompt_task_finish(new_task,
1797                          new_taskdata->ompt_task_info.scheduling_parent,
1798                          ompt_task_switch);
1799       new_taskdata->ompt_task_info.frame.exit_frame = ompt_data_none;
1800     }
1801   }
1802 #endif
1803 
1804   res = __kmp_omp_task(gtid, new_task, true);
1805 
1806   KA_TRACE(10, ("__kmpc_omp_task(exit): T#%d returning "
1807                 "TASK_CURRENT_NOT_QUEUED: loc=%p task=%p\n",
1808                 gtid, loc_ref, new_taskdata));
1809 #if OMPT_SUPPORT
1810   if (UNLIKELY(ompt_enabled.enabled && parent != NULL)) {
1811     parent->ompt_task_info.frame.enter_frame = ompt_data_none;
1812   }
1813 #endif
1814   return res;
1815 }
1816 
1817 // __kmp_omp_taskloop_task: Wrapper around __kmp_omp_task to schedule
1818 // a taskloop task with the correct OMPT return address
1819 //
1820 // loc_ref: location of original task pragma (ignored)
1821 // gtid: Global Thread ID of encountering thread
1822 // new_task: non-thread-switchable task thunk allocated by
1823 // __kmp_omp_task_alloc()
1824 // codeptr_ra: return address for OMPT callback
1825 // Returns:
1826 //    TASK_CURRENT_NOT_QUEUED (0) if did not suspend and queue current task to
1827 //    be resumed later.
1828 //    TASK_CURRENT_QUEUED (1) if suspended and queued the current task to be
1829 //    resumed later.
1830 kmp_int32 __kmp_omp_taskloop_task(ident_t *loc_ref, kmp_int32 gtid,
1831                                   kmp_task_t *new_task, void *codeptr_ra) {
1832   kmp_int32 res;
1833   KMP_SET_THREAD_STATE_BLOCK(EXPLICIT_TASK);
1834 
1835 #if KMP_DEBUG || OMPT_SUPPORT
1836   kmp_taskdata_t *new_taskdata = KMP_TASK_TO_TASKDATA(new_task);
1837 #endif
1838   KA_TRACE(10, ("__kmpc_omp_task(enter): T#%d loc=%p task=%p\n", gtid, loc_ref,
1839                 new_taskdata));
1840 
1841 #if OMPT_SUPPORT
1842   kmp_taskdata_t *parent = NULL;
1843   if (UNLIKELY(ompt_enabled.enabled && !new_taskdata->td_flags.started)) {
1844     parent = new_taskdata->td_parent;
1845     if (!parent->ompt_task_info.frame.enter_frame.ptr)
1846       parent->ompt_task_info.frame.enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0);
1847     if (ompt_enabled.ompt_callback_task_create) {
1848       ompt_data_t task_data = ompt_data_none;
1849       ompt_callbacks.ompt_callback(ompt_callback_task_create)(
1850           parent ? &(parent->ompt_task_info.task_data) : &task_data,
1851           parent ? &(parent->ompt_task_info.frame) : NULL,
1852           &(new_taskdata->ompt_task_info.task_data),
1853           ompt_task_explicit | TASK_TYPE_DETAILS_FORMAT(new_taskdata), 0,
1854           codeptr_ra);
1855     }
1856   }
1857 #endif
1858 
1859   res = __kmp_omp_task(gtid, new_task, true);
1860 
1861   KA_TRACE(10, ("__kmpc_omp_task(exit): T#%d returning "
1862                 "TASK_CURRENT_NOT_QUEUED: loc=%p task=%p\n",
1863                 gtid, loc_ref, new_taskdata));
1864 #if OMPT_SUPPORT
1865   if (UNLIKELY(ompt_enabled.enabled && parent != NULL)) {
1866     parent->ompt_task_info.frame.enter_frame = ompt_data_none;
1867   }
1868 #endif
1869   return res;
1870 }
1871 
1872 template <bool ompt>
1873 static kmp_int32 __kmpc_omp_taskwait_template(ident_t *loc_ref, kmp_int32 gtid,
1874                                               void *frame_address,
1875                                               void *return_address) {
1876   kmp_taskdata_t *taskdata;
1877   kmp_info_t *thread;
1878   int thread_finished = FALSE;
1879   KMP_SET_THREAD_STATE_BLOCK(TASKWAIT);
1880 
1881   KA_TRACE(10, ("__kmpc_omp_taskwait(enter): T#%d loc=%p\n", gtid, loc_ref));
1882   KMP_DEBUG_ASSERT(gtid >= 0);
1883 
1884   if (__kmp_tasking_mode != tskm_immediate_exec) {
1885     thread = __kmp_threads[gtid];
1886     taskdata = thread->th.th_current_task;
1887 
1888 #if OMPT_SUPPORT && OMPT_OPTIONAL
1889     ompt_data_t *my_task_data;
1890     ompt_data_t *my_parallel_data;
1891 
1892     if (ompt) {
1893       my_task_data = &(taskdata->ompt_task_info.task_data);
1894       my_parallel_data = OMPT_CUR_TEAM_DATA(thread);
1895 
1896       taskdata->ompt_task_info.frame.enter_frame.ptr = frame_address;
1897 
1898       if (ompt_enabled.ompt_callback_sync_region) {
1899         ompt_callbacks.ompt_callback(ompt_callback_sync_region)(
1900             ompt_sync_region_taskwait, ompt_scope_begin, my_parallel_data,
1901             my_task_data, return_address);
1902       }
1903 
1904       if (ompt_enabled.ompt_callback_sync_region_wait) {
1905         ompt_callbacks.ompt_callback(ompt_callback_sync_region_wait)(
1906             ompt_sync_region_taskwait, ompt_scope_begin, my_parallel_data,
1907             my_task_data, return_address);
1908       }
1909     }
1910 #endif // OMPT_SUPPORT && OMPT_OPTIONAL
1911 
1912 // Debugger: The taskwait is active. Store location and thread encountered the
1913 // taskwait.
1914 #if USE_ITT_BUILD
1915 // Note: These values are used by ITT events as well.
1916 #endif /* USE_ITT_BUILD */
1917     taskdata->td_taskwait_counter += 1;
1918     taskdata->td_taskwait_ident = loc_ref;
1919     taskdata->td_taskwait_thread = gtid + 1;
1920 
1921 #if USE_ITT_BUILD
1922     void *itt_sync_obj = NULL;
1923 #if USE_ITT_NOTIFY
1924     KMP_ITT_TASKWAIT_STARTING(itt_sync_obj);
1925 #endif /* USE_ITT_NOTIFY */
1926 #endif /* USE_ITT_BUILD */
1927 
1928     bool must_wait =
1929         !taskdata->td_flags.team_serial && !taskdata->td_flags.final;
1930 
1931     must_wait = must_wait || (thread->th.th_task_team != NULL &&
1932                               thread->th.th_task_team->tt.tt_found_proxy_tasks);
1933     // If hidden helper thread is encountered, we must enable wait here.
1934     must_wait =
1935         must_wait ||
1936         (__kmp_enable_hidden_helper && thread->th.th_task_team != NULL &&
1937          thread->th.th_task_team->tt.tt_hidden_helper_task_encountered);
1938 
1939     if (must_wait) {
1940       kmp_flag_32<false, false> flag(
1941           RCAST(std::atomic<kmp_uint32> *,
1942                 &(taskdata->td_incomplete_child_tasks)),
1943           0U);
1944       while (KMP_ATOMIC_LD_ACQ(&taskdata->td_incomplete_child_tasks) != 0) {
1945         flag.execute_tasks(thread, gtid, FALSE,
1946                            &thread_finished USE_ITT_BUILD_ARG(itt_sync_obj),
1947                            __kmp_task_stealing_constraint);
1948       }
1949     }
1950 #if USE_ITT_BUILD
1951     KMP_ITT_TASKWAIT_FINISHED(itt_sync_obj);
1952     KMP_FSYNC_ACQUIRED(taskdata); // acquire self - sync with children
1953 #endif /* USE_ITT_BUILD */
1954 
1955     // Debugger:  The taskwait is completed. Location remains, but thread is
1956     // negated.
1957     taskdata->td_taskwait_thread = -taskdata->td_taskwait_thread;
1958 
1959 #if OMPT_SUPPORT && OMPT_OPTIONAL
1960     if (ompt) {
1961       if (ompt_enabled.ompt_callback_sync_region_wait) {
1962         ompt_callbacks.ompt_callback(ompt_callback_sync_region_wait)(
1963             ompt_sync_region_taskwait, ompt_scope_end, my_parallel_data,
1964             my_task_data, return_address);
1965       }
1966       if (ompt_enabled.ompt_callback_sync_region) {
1967         ompt_callbacks.ompt_callback(ompt_callback_sync_region)(
1968             ompt_sync_region_taskwait, ompt_scope_end, my_parallel_data,
1969             my_task_data, return_address);
1970       }
1971       taskdata->ompt_task_info.frame.enter_frame = ompt_data_none;
1972     }
1973 #endif // OMPT_SUPPORT && OMPT_OPTIONAL
1974 
1975     ANNOTATE_HAPPENS_AFTER(taskdata);
1976   }
1977 
1978   KA_TRACE(10, ("__kmpc_omp_taskwait(exit): T#%d task %p finished waiting, "
1979                 "returning TASK_CURRENT_NOT_QUEUED\n",
1980                 gtid, taskdata));
1981 
1982   return TASK_CURRENT_NOT_QUEUED;
1983 }
1984 
1985 #if OMPT_SUPPORT && OMPT_OPTIONAL
1986 OMPT_NOINLINE
1987 static kmp_int32 __kmpc_omp_taskwait_ompt(ident_t *loc_ref, kmp_int32 gtid,
1988                                           void *frame_address,
1989                                           void *return_address) {
1990   return __kmpc_omp_taskwait_template<true>(loc_ref, gtid, frame_address,
1991                                             return_address);
1992 }
1993 #endif // OMPT_SUPPORT && OMPT_OPTIONAL
1994 
1995 // __kmpc_omp_taskwait: Wait until all tasks generated by the current task are
1996 // complete
1997 kmp_int32 __kmpc_omp_taskwait(ident_t *loc_ref, kmp_int32 gtid) {
1998 #if OMPT_SUPPORT && OMPT_OPTIONAL
1999   if (UNLIKELY(ompt_enabled.enabled)) {
2000     OMPT_STORE_RETURN_ADDRESS(gtid);
2001     return __kmpc_omp_taskwait_ompt(loc_ref, gtid, OMPT_GET_FRAME_ADDRESS(0),
2002                                     OMPT_LOAD_RETURN_ADDRESS(gtid));
2003   }
2004 #endif
2005   return __kmpc_omp_taskwait_template<false>(loc_ref, gtid, NULL, NULL);
2006 }
2007 
2008 // __kmpc_omp_taskyield: switch to a different task
2009 kmp_int32 __kmpc_omp_taskyield(ident_t *loc_ref, kmp_int32 gtid, int end_part) {
2010   kmp_taskdata_t *taskdata;
2011   kmp_info_t *thread;
2012   int thread_finished = FALSE;
2013 
2014   KMP_COUNT_BLOCK(OMP_TASKYIELD);
2015   KMP_SET_THREAD_STATE_BLOCK(TASKYIELD);
2016 
2017   KA_TRACE(10, ("__kmpc_omp_taskyield(enter): T#%d loc=%p end_part = %d\n",
2018                 gtid, loc_ref, end_part));
2019   __kmp_assert_valid_gtid(gtid);
2020 
2021   if (__kmp_tasking_mode != tskm_immediate_exec && __kmp_init_parallel) {
2022     thread = __kmp_threads[gtid];
2023     taskdata = thread->th.th_current_task;
2024 // Should we model this as a task wait or not?
2025 // Debugger: The taskwait is active. Store location and thread encountered the
2026 // taskwait.
2027 #if USE_ITT_BUILD
2028 // Note: These values are used by ITT events as well.
2029 #endif /* USE_ITT_BUILD */
2030     taskdata->td_taskwait_counter += 1;
2031     taskdata->td_taskwait_ident = loc_ref;
2032     taskdata->td_taskwait_thread = gtid + 1;
2033 
2034 #if USE_ITT_BUILD
2035     void *itt_sync_obj = NULL;
2036 #if USE_ITT_NOTIFY
2037     KMP_ITT_TASKWAIT_STARTING(itt_sync_obj);
2038 #endif /* USE_ITT_NOTIFY */
2039 #endif /* USE_ITT_BUILD */
2040     if (!taskdata->td_flags.team_serial) {
2041       kmp_task_team_t *task_team = thread->th.th_task_team;
2042       if (task_team != NULL) {
2043         if (KMP_TASKING_ENABLED(task_team)) {
2044 #if OMPT_SUPPORT
2045           if (UNLIKELY(ompt_enabled.enabled))
2046             thread->th.ompt_thread_info.ompt_task_yielded = 1;
2047 #endif
2048           __kmp_execute_tasks_32(
2049               thread, gtid, (kmp_flag_32<> *)NULL, FALSE,
2050               &thread_finished USE_ITT_BUILD_ARG(itt_sync_obj),
2051               __kmp_task_stealing_constraint);
2052 #if OMPT_SUPPORT
2053           if (UNLIKELY(ompt_enabled.enabled))
2054             thread->th.ompt_thread_info.ompt_task_yielded = 0;
2055 #endif
2056         }
2057       }
2058     }
2059 #if USE_ITT_BUILD
2060     KMP_ITT_TASKWAIT_FINISHED(itt_sync_obj);
2061 #endif /* USE_ITT_BUILD */
2062 
2063     // Debugger:  The taskwait is completed. Location remains, but thread is
2064     // negated.
2065     taskdata->td_taskwait_thread = -taskdata->td_taskwait_thread;
2066   }
2067 
2068   KA_TRACE(10, ("__kmpc_omp_taskyield(exit): T#%d task %p resuming, "
2069                 "returning TASK_CURRENT_NOT_QUEUED\n",
2070                 gtid, taskdata));
2071 
2072   return TASK_CURRENT_NOT_QUEUED;
2073 }
2074 
2075 // Task Reduction implementation
2076 //
2077 // Note: initial implementation didn't take into account the possibility
2078 // to specify omp_orig for initializer of the UDR (user defined reduction).
2079 // Corrected implementation takes into account the omp_orig object.
2080 // Compiler is free to use old implementation if omp_orig is not specified.
2081 
2082 /*!
2083 @ingroup BASIC_TYPES
2084 @{
2085 */
2086 
2087 /*!
2088 Flags for special info per task reduction item.
2089 */
2090 typedef struct kmp_taskred_flags {
2091   /*! 1 - use lazy alloc/init (e.g. big objects, #tasks < #threads) */
2092   unsigned lazy_priv : 1;
2093   unsigned reserved31 : 31;
2094 } kmp_taskred_flags_t;
2095 
2096 /*!
2097 Internal struct for reduction data item related info set up by compiler.
2098 */
2099 typedef struct kmp_task_red_input {
2100   void *reduce_shar; /**< shared between tasks item to reduce into */
2101   size_t reduce_size; /**< size of data item in bytes */
2102   // three compiler-generated routines (init, fini are optional):
2103   void *reduce_init; /**< data initialization routine (single parameter) */
2104   void *reduce_fini; /**< data finalization routine */
2105   void *reduce_comb; /**< data combiner routine */
2106   kmp_taskred_flags_t flags; /**< flags for additional info from compiler */
2107 } kmp_task_red_input_t;
2108 
2109 /*!
2110 Internal struct for reduction data item related info saved by the library.
2111 */
2112 typedef struct kmp_taskred_data {
2113   void *reduce_shar; /**< shared between tasks item to reduce into */
2114   size_t reduce_size; /**< size of data item */
2115   kmp_taskred_flags_t flags; /**< flags for additional info from compiler */
2116   void *reduce_priv; /**< array of thread specific items */
2117   void *reduce_pend; /**< end of private data for faster comparison op */
2118   // three compiler-generated routines (init, fini are optional):
2119   void *reduce_comb; /**< data combiner routine */
2120   void *reduce_init; /**< data initialization routine (two parameters) */
2121   void *reduce_fini; /**< data finalization routine */
2122   void *reduce_orig; /**< original item (can be used in UDR initializer) */
2123 } kmp_taskred_data_t;
2124 
2125 /*!
2126 Internal struct for reduction data item related info set up by compiler.
2127 
2128 New interface: added reduce_orig field to provide omp_orig for UDR initializer.
2129 */
2130 typedef struct kmp_taskred_input {
2131   void *reduce_shar; /**< shared between tasks item to reduce into */
2132   void *reduce_orig; /**< original reduction item used for initialization */
2133   size_t reduce_size; /**< size of data item */
2134   // three compiler-generated routines (init, fini are optional):
2135   void *reduce_init; /**< data initialization routine (two parameters) */
2136   void *reduce_fini; /**< data finalization routine */
2137   void *reduce_comb; /**< data combiner routine */
2138   kmp_taskred_flags_t flags; /**< flags for additional info from compiler */
2139 } kmp_taskred_input_t;
2140 /*!
2141 @}
2142 */
2143 
2144 template <typename T> void __kmp_assign_orig(kmp_taskred_data_t &item, T &src);
2145 template <>
2146 void __kmp_assign_orig<kmp_task_red_input_t>(kmp_taskred_data_t &item,
2147                                              kmp_task_red_input_t &src) {
2148   item.reduce_orig = NULL;
2149 }
2150 template <>
2151 void __kmp_assign_orig<kmp_taskred_input_t>(kmp_taskred_data_t &item,
2152                                             kmp_taskred_input_t &src) {
2153   if (src.reduce_orig != NULL) {
2154     item.reduce_orig = src.reduce_orig;
2155   } else {
2156     item.reduce_orig = src.reduce_shar;
2157   } // non-NULL reduce_orig means new interface used
2158 }
2159 
2160 template <typename T> void __kmp_call_init(kmp_taskred_data_t &item, size_t j);
2161 template <>
2162 void __kmp_call_init<kmp_task_red_input_t>(kmp_taskred_data_t &item,
2163                                            size_t offset) {
2164   ((void (*)(void *))item.reduce_init)((char *)(item.reduce_priv) + offset);
2165 }
2166 template <>
2167 void __kmp_call_init<kmp_taskred_input_t>(kmp_taskred_data_t &item,
2168                                           size_t offset) {
2169   ((void (*)(void *, void *))item.reduce_init)(
2170       (char *)(item.reduce_priv) + offset, item.reduce_orig);
2171 }
2172 
2173 template <typename T>
2174 void *__kmp_task_reduction_init(int gtid, int num, T *data) {
2175   __kmp_assert_valid_gtid(gtid);
2176   kmp_info_t *thread = __kmp_threads[gtid];
2177   kmp_taskgroup_t *tg = thread->th.th_current_task->td_taskgroup;
2178   kmp_uint32 nth = thread->th.th_team_nproc;
2179   kmp_taskred_data_t *arr;
2180 
2181   // check input data just in case
2182   KMP_ASSERT(tg != NULL);
2183   KMP_ASSERT(data != NULL);
2184   KMP_ASSERT(num > 0);
2185   if (nth == 1) {
2186     KA_TRACE(10, ("__kmpc_task_reduction_init: T#%d, tg %p, exiting nth=1\n",
2187                   gtid, tg));
2188     return (void *)tg;
2189   }
2190   KA_TRACE(10, ("__kmpc_task_reduction_init: T#%d, taskgroup %p, #items %d\n",
2191                 gtid, tg, num));
2192   arr = (kmp_taskred_data_t *)__kmp_thread_malloc(
2193       thread, num * sizeof(kmp_taskred_data_t));
2194   for (int i = 0; i < num; ++i) {
2195     size_t size = data[i].reduce_size - 1;
2196     // round the size up to cache line per thread-specific item
2197     size += CACHE_LINE - size % CACHE_LINE;
2198     KMP_ASSERT(data[i].reduce_comb != NULL); // combiner is mandatory
2199     arr[i].reduce_shar = data[i].reduce_shar;
2200     arr[i].reduce_size = size;
2201     arr[i].flags = data[i].flags;
2202     arr[i].reduce_comb = data[i].reduce_comb;
2203     arr[i].reduce_init = data[i].reduce_init;
2204     arr[i].reduce_fini = data[i].reduce_fini;
2205     __kmp_assign_orig<T>(arr[i], data[i]);
2206     if (!arr[i].flags.lazy_priv) {
2207       // allocate cache-line aligned block and fill it with zeros
2208       arr[i].reduce_priv = __kmp_allocate(nth * size);
2209       arr[i].reduce_pend = (char *)(arr[i].reduce_priv) + nth * size;
2210       if (arr[i].reduce_init != NULL) {
2211         // initialize all thread-specific items
2212         for (size_t j = 0; j < nth; ++j) {
2213           __kmp_call_init<T>(arr[i], j * size);
2214         }
2215       }
2216     } else {
2217       // only allocate space for pointers now,
2218       // objects will be lazily allocated/initialized if/when requested
2219       // note that __kmp_allocate zeroes the allocated memory
2220       arr[i].reduce_priv = __kmp_allocate(nth * sizeof(void *));
2221     }
2222   }
2223   tg->reduce_data = (void *)arr;
2224   tg->reduce_num_data = num;
2225   return (void *)tg;
2226 }
2227 
2228 /*!
2229 @ingroup TASKING
2230 @param gtid      Global thread ID
2231 @param num       Number of data items to reduce
2232 @param data      Array of data for reduction
2233 @return The taskgroup identifier
2234 
2235 Initialize task reduction for the taskgroup.
2236 
2237 Note: this entry supposes the optional compiler-generated initializer routine
2238 has single parameter - pointer to object to be initialized. That means
2239 the reduction either does not use omp_orig object, or the omp_orig is accessible
2240 without help of the runtime library.
2241 */
2242 void *__kmpc_task_reduction_init(int gtid, int num, void *data) {
2243   return __kmp_task_reduction_init(gtid, num, (kmp_task_red_input_t *)data);
2244 }
2245 
2246 /*!
2247 @ingroup TASKING
2248 @param gtid      Global thread ID
2249 @param num       Number of data items to reduce
2250 @param data      Array of data for reduction
2251 @return The taskgroup identifier
2252 
2253 Initialize task reduction for the taskgroup.
2254 
2255 Note: this entry supposes the optional compiler-generated initializer routine
2256 has two parameters, pointer to object to be initialized and pointer to omp_orig
2257 */
2258 void *__kmpc_taskred_init(int gtid, int num, void *data) {
2259   return __kmp_task_reduction_init(gtid, num, (kmp_taskred_input_t *)data);
2260 }
2261 
2262 // Copy task reduction data (except for shared pointers).
2263 template <typename T>
2264 void __kmp_task_reduction_init_copy(kmp_info_t *thr, int num, T *data,
2265                                     kmp_taskgroup_t *tg, void *reduce_data) {
2266   kmp_taskred_data_t *arr;
2267   KA_TRACE(20, ("__kmp_task_reduction_init_copy: Th %p, init taskgroup %p,"
2268                 " from data %p\n",
2269                 thr, tg, reduce_data));
2270   arr = (kmp_taskred_data_t *)__kmp_thread_malloc(
2271       thr, num * sizeof(kmp_taskred_data_t));
2272   // threads will share private copies, thunk routines, sizes, flags, etc.:
2273   KMP_MEMCPY(arr, reduce_data, num * sizeof(kmp_taskred_data_t));
2274   for (int i = 0; i < num; ++i) {
2275     arr[i].reduce_shar = data[i].reduce_shar; // init unique shared pointers
2276   }
2277   tg->reduce_data = (void *)arr;
2278   tg->reduce_num_data = num;
2279 }
2280 
2281 /*!
2282 @ingroup TASKING
2283 @param gtid    Global thread ID
2284 @param tskgrp  The taskgroup ID (optional)
2285 @param data    Shared location of the item
2286 @return The pointer to per-thread data
2287 
2288 Get thread-specific location of data item
2289 */
2290 void *__kmpc_task_reduction_get_th_data(int gtid, void *tskgrp, void *data) {
2291   __kmp_assert_valid_gtid(gtid);
2292   kmp_info_t *thread = __kmp_threads[gtid];
2293   kmp_int32 nth = thread->th.th_team_nproc;
2294   if (nth == 1)
2295     return data; // nothing to do
2296 
2297   kmp_taskgroup_t *tg = (kmp_taskgroup_t *)tskgrp;
2298   if (tg == NULL)
2299     tg = thread->th.th_current_task->td_taskgroup;
2300   KMP_ASSERT(tg != NULL);
2301   kmp_taskred_data_t *arr = (kmp_taskred_data_t *)(tg->reduce_data);
2302   kmp_int32 num = tg->reduce_num_data;
2303   kmp_int32 tid = thread->th.th_info.ds.ds_tid;
2304 
2305   KMP_ASSERT(data != NULL);
2306   while (tg != NULL) {
2307     for (int i = 0; i < num; ++i) {
2308       if (!arr[i].flags.lazy_priv) {
2309         if (data == arr[i].reduce_shar ||
2310             (data >= arr[i].reduce_priv && data < arr[i].reduce_pend))
2311           return (char *)(arr[i].reduce_priv) + tid * arr[i].reduce_size;
2312       } else {
2313         // check shared location first
2314         void **p_priv = (void **)(arr[i].reduce_priv);
2315         if (data == arr[i].reduce_shar)
2316           goto found;
2317         // check if we get some thread specific location as parameter
2318         for (int j = 0; j < nth; ++j)
2319           if (data == p_priv[j])
2320             goto found;
2321         continue; // not found, continue search
2322       found:
2323         if (p_priv[tid] == NULL) {
2324           // allocate thread specific object lazily
2325           p_priv[tid] = __kmp_allocate(arr[i].reduce_size);
2326           if (arr[i].reduce_init != NULL) {
2327             if (arr[i].reduce_orig != NULL) { // new interface
2328               ((void (*)(void *, void *))arr[i].reduce_init)(
2329                   p_priv[tid], arr[i].reduce_orig);
2330             } else { // old interface (single parameter)
2331               ((void (*)(void *))arr[i].reduce_init)(p_priv[tid]);
2332             }
2333           }
2334         }
2335         return p_priv[tid];
2336       }
2337     }
2338     tg = tg->parent;
2339     arr = (kmp_taskred_data_t *)(tg->reduce_data);
2340     num = tg->reduce_num_data;
2341   }
2342   KMP_ASSERT2(0, "Unknown task reduction item");
2343   return NULL; // ERROR, this line never executed
2344 }
2345 
2346 // Finalize task reduction.
2347 // Called from __kmpc_end_taskgroup()
2348 static void __kmp_task_reduction_fini(kmp_info_t *th, kmp_taskgroup_t *tg) {
2349   kmp_int32 nth = th->th.th_team_nproc;
2350   KMP_DEBUG_ASSERT(nth > 1); // should not be called if nth == 1
2351   kmp_taskred_data_t *arr = (kmp_taskred_data_t *)tg->reduce_data;
2352   kmp_int32 num = tg->reduce_num_data;
2353   for (int i = 0; i < num; ++i) {
2354     void *sh_data = arr[i].reduce_shar;
2355     void (*f_fini)(void *) = (void (*)(void *))(arr[i].reduce_fini);
2356     void (*f_comb)(void *, void *) =
2357         (void (*)(void *, void *))(arr[i].reduce_comb);
2358     if (!arr[i].flags.lazy_priv) {
2359       void *pr_data = arr[i].reduce_priv;
2360       size_t size = arr[i].reduce_size;
2361       for (int j = 0; j < nth; ++j) {
2362         void *priv_data = (char *)pr_data + j * size;
2363         f_comb(sh_data, priv_data); // combine results
2364         if (f_fini)
2365           f_fini(priv_data); // finalize if needed
2366       }
2367     } else {
2368       void **pr_data = (void **)(arr[i].reduce_priv);
2369       for (int j = 0; j < nth; ++j) {
2370         if (pr_data[j] != NULL) {
2371           f_comb(sh_data, pr_data[j]); // combine results
2372           if (f_fini)
2373             f_fini(pr_data[j]); // finalize if needed
2374           __kmp_free(pr_data[j]);
2375         }
2376       }
2377     }
2378     __kmp_free(arr[i].reduce_priv);
2379   }
2380   __kmp_thread_free(th, arr);
2381   tg->reduce_data = NULL;
2382   tg->reduce_num_data = 0;
2383 }
2384 
2385 // Cleanup task reduction data for parallel or worksharing,
2386 // do not touch task private data other threads still working with.
2387 // Called from __kmpc_end_taskgroup()
2388 static void __kmp_task_reduction_clean(kmp_info_t *th, kmp_taskgroup_t *tg) {
2389   __kmp_thread_free(th, tg->reduce_data);
2390   tg->reduce_data = NULL;
2391   tg->reduce_num_data = 0;
2392 }
2393 
2394 template <typename T>
2395 void *__kmp_task_reduction_modifier_init(ident_t *loc, int gtid, int is_ws,
2396                                          int num, T *data) {
2397   __kmp_assert_valid_gtid(gtid);
2398   kmp_info_t *thr = __kmp_threads[gtid];
2399   kmp_int32 nth = thr->th.th_team_nproc;
2400   __kmpc_taskgroup(loc, gtid); // form new taskgroup first
2401   if (nth == 1) {
2402     KA_TRACE(10,
2403              ("__kmpc_reduction_modifier_init: T#%d, tg %p, exiting nth=1\n",
2404               gtid, thr->th.th_current_task->td_taskgroup));
2405     return (void *)thr->th.th_current_task->td_taskgroup;
2406   }
2407   kmp_team_t *team = thr->th.th_team;
2408   void *reduce_data;
2409   kmp_taskgroup_t *tg;
2410   reduce_data = KMP_ATOMIC_LD_RLX(&team->t.t_tg_reduce_data[is_ws]);
2411   if (reduce_data == NULL &&
2412       __kmp_atomic_compare_store(&team->t.t_tg_reduce_data[is_ws], reduce_data,
2413                                  (void *)1)) {
2414     // single thread enters this block to initialize common reduction data
2415     KMP_DEBUG_ASSERT(reduce_data == NULL);
2416     // first initialize own data, then make a copy other threads can use
2417     tg = (kmp_taskgroup_t *)__kmp_task_reduction_init<T>(gtid, num, data);
2418     reduce_data = __kmp_thread_malloc(thr, num * sizeof(kmp_taskred_data_t));
2419     KMP_MEMCPY(reduce_data, tg->reduce_data, num * sizeof(kmp_taskred_data_t));
2420     // fini counters should be 0 at this point
2421     KMP_DEBUG_ASSERT(KMP_ATOMIC_LD_RLX(&team->t.t_tg_fini_counter[0]) == 0);
2422     KMP_DEBUG_ASSERT(KMP_ATOMIC_LD_RLX(&team->t.t_tg_fini_counter[1]) == 0);
2423     KMP_ATOMIC_ST_REL(&team->t.t_tg_reduce_data[is_ws], reduce_data);
2424   } else {
2425     while (
2426         (reduce_data = KMP_ATOMIC_LD_ACQ(&team->t.t_tg_reduce_data[is_ws])) ==
2427         (void *)1) { // wait for task reduction initialization
2428       KMP_CPU_PAUSE();
2429     }
2430     KMP_DEBUG_ASSERT(reduce_data > (void *)1); // should be valid pointer here
2431     tg = thr->th.th_current_task->td_taskgroup;
2432     __kmp_task_reduction_init_copy<T>(thr, num, data, tg, reduce_data);
2433   }
2434   return tg;
2435 }
2436 
2437 /*!
2438 @ingroup TASKING
2439 @param loc       Source location info
2440 @param gtid      Global thread ID
2441 @param is_ws     Is 1 if the reduction is for worksharing, 0 otherwise
2442 @param num       Number of data items to reduce
2443 @param data      Array of data for reduction
2444 @return The taskgroup identifier
2445 
2446 Initialize task reduction for a parallel or worksharing.
2447 
2448 Note: this entry supposes the optional compiler-generated initializer routine
2449 has single parameter - pointer to object to be initialized. That means
2450 the reduction either does not use omp_orig object, or the omp_orig is accessible
2451 without help of the runtime library.
2452 */
2453 void *__kmpc_task_reduction_modifier_init(ident_t *loc, int gtid, int is_ws,
2454                                           int num, void *data) {
2455   return __kmp_task_reduction_modifier_init(loc, gtid, is_ws, num,
2456                                             (kmp_task_red_input_t *)data);
2457 }
2458 
2459 /*!
2460 @ingroup TASKING
2461 @param loc       Source location info
2462 @param gtid      Global thread ID
2463 @param is_ws     Is 1 if the reduction is for worksharing, 0 otherwise
2464 @param num       Number of data items to reduce
2465 @param data      Array of data for reduction
2466 @return The taskgroup identifier
2467 
2468 Initialize task reduction for a parallel or worksharing.
2469 
2470 Note: this entry supposes the optional compiler-generated initializer routine
2471 has two parameters, pointer to object to be initialized and pointer to omp_orig
2472 */
2473 void *__kmpc_taskred_modifier_init(ident_t *loc, int gtid, int is_ws, int num,
2474                                    void *data) {
2475   return __kmp_task_reduction_modifier_init(loc, gtid, is_ws, num,
2476                                             (kmp_taskred_input_t *)data);
2477 }
2478 
2479 /*!
2480 @ingroup TASKING
2481 @param loc       Source location info
2482 @param gtid      Global thread ID
2483 @param is_ws     Is 1 if the reduction is for worksharing, 0 otherwise
2484 
2485 Finalize task reduction for a parallel or worksharing.
2486 */
2487 void __kmpc_task_reduction_modifier_fini(ident_t *loc, int gtid, int is_ws) {
2488   __kmpc_end_taskgroup(loc, gtid);
2489 }
2490 
2491 // __kmpc_taskgroup: Start a new taskgroup
2492 void __kmpc_taskgroup(ident_t *loc, int gtid) {
2493   __kmp_assert_valid_gtid(gtid);
2494   kmp_info_t *thread = __kmp_threads[gtid];
2495   kmp_taskdata_t *taskdata = thread->th.th_current_task;
2496   kmp_taskgroup_t *tg_new =
2497       (kmp_taskgroup_t *)__kmp_thread_malloc(thread, sizeof(kmp_taskgroup_t));
2498   KA_TRACE(10, ("__kmpc_taskgroup: T#%d loc=%p group=%p\n", gtid, loc, tg_new));
2499   KMP_ATOMIC_ST_RLX(&tg_new->count, 0);
2500   KMP_ATOMIC_ST_RLX(&tg_new->cancel_request, cancel_noreq);
2501   tg_new->parent = taskdata->td_taskgroup;
2502   tg_new->reduce_data = NULL;
2503   tg_new->reduce_num_data = 0;
2504   taskdata->td_taskgroup = tg_new;
2505 
2506 #if OMPT_SUPPORT && OMPT_OPTIONAL
2507   if (UNLIKELY(ompt_enabled.ompt_callback_sync_region)) {
2508     void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid);
2509     if (!codeptr)
2510       codeptr = OMPT_GET_RETURN_ADDRESS(0);
2511     kmp_team_t *team = thread->th.th_team;
2512     ompt_data_t my_task_data = taskdata->ompt_task_info.task_data;
2513     // FIXME: I think this is wrong for lwt!
2514     ompt_data_t my_parallel_data = team->t.ompt_team_info.parallel_data;
2515 
2516     ompt_callbacks.ompt_callback(ompt_callback_sync_region)(
2517         ompt_sync_region_taskgroup, ompt_scope_begin, &(my_parallel_data),
2518         &(my_task_data), codeptr);
2519   }
2520 #endif
2521 }
2522 
2523 // __kmpc_end_taskgroup: Wait until all tasks generated by the current task
2524 //                       and its descendants are complete
2525 void __kmpc_end_taskgroup(ident_t *loc, int gtid) {
2526   __kmp_assert_valid_gtid(gtid);
2527   kmp_info_t *thread = __kmp_threads[gtid];
2528   kmp_taskdata_t *taskdata = thread->th.th_current_task;
2529   kmp_taskgroup_t *taskgroup = taskdata->td_taskgroup;
2530   int thread_finished = FALSE;
2531 
2532 #if OMPT_SUPPORT && OMPT_OPTIONAL
2533   kmp_team_t *team;
2534   ompt_data_t my_task_data;
2535   ompt_data_t my_parallel_data;
2536   void *codeptr;
2537   if (UNLIKELY(ompt_enabled.enabled)) {
2538     team = thread->th.th_team;
2539     my_task_data = taskdata->ompt_task_info.task_data;
2540     // FIXME: I think this is wrong for lwt!
2541     my_parallel_data = team->t.ompt_team_info.parallel_data;
2542     codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid);
2543     if (!codeptr)
2544       codeptr = OMPT_GET_RETURN_ADDRESS(0);
2545   }
2546 #endif
2547 
2548   KA_TRACE(10, ("__kmpc_end_taskgroup(enter): T#%d loc=%p\n", gtid, loc));
2549   KMP_DEBUG_ASSERT(taskgroup != NULL);
2550   KMP_SET_THREAD_STATE_BLOCK(TASKGROUP);
2551 
2552   if (__kmp_tasking_mode != tskm_immediate_exec) {
2553     // mark task as waiting not on a barrier
2554     taskdata->td_taskwait_counter += 1;
2555     taskdata->td_taskwait_ident = loc;
2556     taskdata->td_taskwait_thread = gtid + 1;
2557 #if USE_ITT_BUILD
2558     // For ITT the taskgroup wait is similar to taskwait until we need to
2559     // distinguish them
2560     void *itt_sync_obj = NULL;
2561 #if USE_ITT_NOTIFY
2562     KMP_ITT_TASKWAIT_STARTING(itt_sync_obj);
2563 #endif /* USE_ITT_NOTIFY */
2564 #endif /* USE_ITT_BUILD */
2565 
2566 #if OMPT_SUPPORT && OMPT_OPTIONAL
2567     if (UNLIKELY(ompt_enabled.ompt_callback_sync_region_wait)) {
2568       ompt_callbacks.ompt_callback(ompt_callback_sync_region_wait)(
2569           ompt_sync_region_taskgroup, ompt_scope_begin, &(my_parallel_data),
2570           &(my_task_data), codeptr);
2571     }
2572 #endif
2573 
2574     if (!taskdata->td_flags.team_serial ||
2575         (thread->th.th_task_team != NULL &&
2576          thread->th.th_task_team->tt.tt_found_proxy_tasks)) {
2577       kmp_flag_32<false, false> flag(
2578           RCAST(std::atomic<kmp_uint32> *, &(taskgroup->count)), 0U);
2579       while (KMP_ATOMIC_LD_ACQ(&taskgroup->count) != 0) {
2580         flag.execute_tasks(thread, gtid, FALSE,
2581                            &thread_finished USE_ITT_BUILD_ARG(itt_sync_obj),
2582                            __kmp_task_stealing_constraint);
2583       }
2584     }
2585     taskdata->td_taskwait_thread = -taskdata->td_taskwait_thread; // end waiting
2586 
2587 #if OMPT_SUPPORT && OMPT_OPTIONAL
2588     if (UNLIKELY(ompt_enabled.ompt_callback_sync_region_wait)) {
2589       ompt_callbacks.ompt_callback(ompt_callback_sync_region_wait)(
2590           ompt_sync_region_taskgroup, ompt_scope_end, &(my_parallel_data),
2591           &(my_task_data), codeptr);
2592     }
2593 #endif
2594 
2595 #if USE_ITT_BUILD
2596     KMP_ITT_TASKWAIT_FINISHED(itt_sync_obj);
2597     KMP_FSYNC_ACQUIRED(taskdata); // acquire self - sync with descendants
2598 #endif /* USE_ITT_BUILD */
2599   }
2600   KMP_DEBUG_ASSERT(taskgroup->count == 0);
2601 
2602   if (taskgroup->reduce_data != NULL) { // need to reduce?
2603     int cnt;
2604     void *reduce_data;
2605     kmp_team_t *t = thread->th.th_team;
2606     kmp_taskred_data_t *arr = (kmp_taskred_data_t *)taskgroup->reduce_data;
2607     // check if <priv> data of the first reduction variable shared for the team
2608     void *priv0 = arr[0].reduce_priv;
2609     if ((reduce_data = KMP_ATOMIC_LD_ACQ(&t->t.t_tg_reduce_data[0])) != NULL &&
2610         ((kmp_taskred_data_t *)reduce_data)[0].reduce_priv == priv0) {
2611       // finishing task reduction on parallel
2612       cnt = KMP_ATOMIC_INC(&t->t.t_tg_fini_counter[0]);
2613       if (cnt == thread->th.th_team_nproc - 1) {
2614         // we are the last thread passing __kmpc_reduction_modifier_fini()
2615         // finalize task reduction:
2616         __kmp_task_reduction_fini(thread, taskgroup);
2617         // cleanup fields in the team structure:
2618         // TODO: is relaxed store enough here (whole barrier should follow)?
2619         __kmp_thread_free(thread, reduce_data);
2620         KMP_ATOMIC_ST_REL(&t->t.t_tg_reduce_data[0], NULL);
2621         KMP_ATOMIC_ST_REL(&t->t.t_tg_fini_counter[0], 0);
2622       } else {
2623         // we are not the last thread passing __kmpc_reduction_modifier_fini(),
2624         // so do not finalize reduction, just clean own copy of the data
2625         __kmp_task_reduction_clean(thread, taskgroup);
2626       }
2627     } else if ((reduce_data = KMP_ATOMIC_LD_ACQ(&t->t.t_tg_reduce_data[1])) !=
2628                    NULL &&
2629                ((kmp_taskred_data_t *)reduce_data)[0].reduce_priv == priv0) {
2630       // finishing task reduction on worksharing
2631       cnt = KMP_ATOMIC_INC(&t->t.t_tg_fini_counter[1]);
2632       if (cnt == thread->th.th_team_nproc - 1) {
2633         // we are the last thread passing __kmpc_reduction_modifier_fini()
2634         __kmp_task_reduction_fini(thread, taskgroup);
2635         // cleanup fields in team structure:
2636         // TODO: is relaxed store enough here (whole barrier should follow)?
2637         __kmp_thread_free(thread, reduce_data);
2638         KMP_ATOMIC_ST_REL(&t->t.t_tg_reduce_data[1], NULL);
2639         KMP_ATOMIC_ST_REL(&t->t.t_tg_fini_counter[1], 0);
2640       } else {
2641         // we are not the last thread passing __kmpc_reduction_modifier_fini(),
2642         // so do not finalize reduction, just clean own copy of the data
2643         __kmp_task_reduction_clean(thread, taskgroup);
2644       }
2645     } else {
2646       // finishing task reduction on taskgroup
2647       __kmp_task_reduction_fini(thread, taskgroup);
2648     }
2649   }
2650   // Restore parent taskgroup for the current task
2651   taskdata->td_taskgroup = taskgroup->parent;
2652   __kmp_thread_free(thread, taskgroup);
2653 
2654   KA_TRACE(10, ("__kmpc_end_taskgroup(exit): T#%d task %p finished waiting\n",
2655                 gtid, taskdata));
2656   ANNOTATE_HAPPENS_AFTER(taskdata);
2657 
2658 #if OMPT_SUPPORT && OMPT_OPTIONAL
2659   if (UNLIKELY(ompt_enabled.ompt_callback_sync_region)) {
2660     ompt_callbacks.ompt_callback(ompt_callback_sync_region)(
2661         ompt_sync_region_taskgroup, ompt_scope_end, &(my_parallel_data),
2662         &(my_task_data), codeptr);
2663   }
2664 #endif
2665 }
2666 
2667 // __kmp_remove_my_task: remove a task from my own deque
2668 static kmp_task_t *__kmp_remove_my_task(kmp_info_t *thread, kmp_int32 gtid,
2669                                         kmp_task_team_t *task_team,
2670                                         kmp_int32 is_constrained) {
2671   kmp_task_t *task;
2672   kmp_taskdata_t *taskdata;
2673   kmp_thread_data_t *thread_data;
2674   kmp_uint32 tail;
2675 
2676   KMP_DEBUG_ASSERT(__kmp_tasking_mode != tskm_immediate_exec);
2677   KMP_DEBUG_ASSERT(task_team->tt.tt_threads_data !=
2678                    NULL); // Caller should check this condition
2679 
2680   thread_data = &task_team->tt.tt_threads_data[__kmp_tid_from_gtid(gtid)];
2681 
2682   KA_TRACE(10, ("__kmp_remove_my_task(enter): T#%d ntasks=%d head=%u tail=%u\n",
2683                 gtid, thread_data->td.td_deque_ntasks,
2684                 thread_data->td.td_deque_head, thread_data->td.td_deque_tail));
2685 
2686   if (TCR_4(thread_data->td.td_deque_ntasks) == 0) {
2687     KA_TRACE(10,
2688              ("__kmp_remove_my_task(exit #1): T#%d No tasks to remove: "
2689               "ntasks=%d head=%u tail=%u\n",
2690               gtid, thread_data->td.td_deque_ntasks,
2691               thread_data->td.td_deque_head, thread_data->td.td_deque_tail));
2692     return NULL;
2693   }
2694 
2695   __kmp_acquire_bootstrap_lock(&thread_data->td.td_deque_lock);
2696 
2697   if (TCR_4(thread_data->td.td_deque_ntasks) == 0) {
2698     __kmp_release_bootstrap_lock(&thread_data->td.td_deque_lock);
2699     KA_TRACE(10,
2700              ("__kmp_remove_my_task(exit #2): T#%d No tasks to remove: "
2701               "ntasks=%d head=%u tail=%u\n",
2702               gtid, thread_data->td.td_deque_ntasks,
2703               thread_data->td.td_deque_head, thread_data->td.td_deque_tail));
2704     return NULL;
2705   }
2706 
2707   tail = (thread_data->td.td_deque_tail - 1) &
2708          TASK_DEQUE_MASK(thread_data->td); // Wrap index.
2709   taskdata = thread_data->td.td_deque[tail];
2710 
2711   if (!__kmp_task_is_allowed(gtid, is_constrained, taskdata,
2712                              thread->th.th_current_task)) {
2713     // The TSC does not allow to steal victim task
2714     __kmp_release_bootstrap_lock(&thread_data->td.td_deque_lock);
2715     KA_TRACE(10,
2716              ("__kmp_remove_my_task(exit #3): T#%d TSC blocks tail task: "
2717               "ntasks=%d head=%u tail=%u\n",
2718               gtid, thread_data->td.td_deque_ntasks,
2719               thread_data->td.td_deque_head, thread_data->td.td_deque_tail));
2720     return NULL;
2721   }
2722 
2723   thread_data->td.td_deque_tail = tail;
2724   TCW_4(thread_data->td.td_deque_ntasks, thread_data->td.td_deque_ntasks - 1);
2725 
2726   __kmp_release_bootstrap_lock(&thread_data->td.td_deque_lock);
2727 
2728   KA_TRACE(10, ("__kmp_remove_my_task(exit #4): T#%d task %p removed: "
2729                 "ntasks=%d head=%u tail=%u\n",
2730                 gtid, taskdata, thread_data->td.td_deque_ntasks,
2731                 thread_data->td.td_deque_head, thread_data->td.td_deque_tail));
2732 
2733   task = KMP_TASKDATA_TO_TASK(taskdata);
2734   return task;
2735 }
2736 
2737 // __kmp_steal_task: remove a task from another thread's deque
2738 // Assume that calling thread has already checked existence of
2739 // task_team thread_data before calling this routine.
2740 static kmp_task_t *__kmp_steal_task(kmp_info_t *victim_thr, kmp_int32 gtid,
2741                                     kmp_task_team_t *task_team,
2742                                     std::atomic<kmp_int32> *unfinished_threads,
2743                                     int *thread_finished,
2744                                     kmp_int32 is_constrained) {
2745   kmp_task_t *task;
2746   kmp_taskdata_t *taskdata;
2747   kmp_taskdata_t *current;
2748   kmp_thread_data_t *victim_td, *threads_data;
2749   kmp_int32 target;
2750   kmp_int32 victim_tid;
2751 
2752   KMP_DEBUG_ASSERT(__kmp_tasking_mode != tskm_immediate_exec);
2753 
2754   threads_data = task_team->tt.tt_threads_data;
2755   KMP_DEBUG_ASSERT(threads_data != NULL); // Caller should check this condition
2756 
2757   victim_tid = victim_thr->th.th_info.ds.ds_tid;
2758   victim_td = &threads_data[victim_tid];
2759 
2760   KA_TRACE(10, ("__kmp_steal_task(enter): T#%d try to steal from T#%d: "
2761                 "task_team=%p ntasks=%d head=%u tail=%u\n",
2762                 gtid, __kmp_gtid_from_thread(victim_thr), task_team,
2763                 victim_td->td.td_deque_ntasks, victim_td->td.td_deque_head,
2764                 victim_td->td.td_deque_tail));
2765 
2766   if (TCR_4(victim_td->td.td_deque_ntasks) == 0) {
2767     KA_TRACE(10, ("__kmp_steal_task(exit #1): T#%d could not steal from T#%d: "
2768                   "task_team=%p ntasks=%d head=%u tail=%u\n",
2769                   gtid, __kmp_gtid_from_thread(victim_thr), task_team,
2770                   victim_td->td.td_deque_ntasks, victim_td->td.td_deque_head,
2771                   victim_td->td.td_deque_tail));
2772     return NULL;
2773   }
2774 
2775   __kmp_acquire_bootstrap_lock(&victim_td->td.td_deque_lock);
2776 
2777   int ntasks = TCR_4(victim_td->td.td_deque_ntasks);
2778   // Check again after we acquire the lock
2779   if (ntasks == 0) {
2780     __kmp_release_bootstrap_lock(&victim_td->td.td_deque_lock);
2781     KA_TRACE(10, ("__kmp_steal_task(exit #2): T#%d could not steal from T#%d: "
2782                   "task_team=%p ntasks=%d head=%u tail=%u\n",
2783                   gtid, __kmp_gtid_from_thread(victim_thr), task_team, ntasks,
2784                   victim_td->td.td_deque_head, victim_td->td.td_deque_tail));
2785     return NULL;
2786   }
2787 
2788   KMP_DEBUG_ASSERT(victim_td->td.td_deque != NULL);
2789   current = __kmp_threads[gtid]->th.th_current_task;
2790   taskdata = victim_td->td.td_deque[victim_td->td.td_deque_head];
2791   if (__kmp_task_is_allowed(gtid, is_constrained, taskdata, current)) {
2792     // Bump head pointer and Wrap.
2793     victim_td->td.td_deque_head =
2794         (victim_td->td.td_deque_head + 1) & TASK_DEQUE_MASK(victim_td->td);
2795   } else {
2796     if (!task_team->tt.tt_untied_task_encountered) {
2797       // The TSC does not allow to steal victim task
2798       __kmp_release_bootstrap_lock(&victim_td->td.td_deque_lock);
2799       KA_TRACE(10, ("__kmp_steal_task(exit #3): T#%d could not steal from "
2800                     "T#%d: task_team=%p ntasks=%d head=%u tail=%u\n",
2801                     gtid, __kmp_gtid_from_thread(victim_thr), task_team, ntasks,
2802                     victim_td->td.td_deque_head, victim_td->td.td_deque_tail));
2803       return NULL;
2804     }
2805     int i;
2806     // walk through victim's deque trying to steal any task
2807     target = victim_td->td.td_deque_head;
2808     taskdata = NULL;
2809     for (i = 1; i < ntasks; ++i) {
2810       target = (target + 1) & TASK_DEQUE_MASK(victim_td->td);
2811       taskdata = victim_td->td.td_deque[target];
2812       if (__kmp_task_is_allowed(gtid, is_constrained, taskdata, current)) {
2813         break; // found victim task
2814       } else {
2815         taskdata = NULL;
2816       }
2817     }
2818     if (taskdata == NULL) {
2819       // No appropriate candidate to steal found
2820       __kmp_release_bootstrap_lock(&victim_td->td.td_deque_lock);
2821       KA_TRACE(10, ("__kmp_steal_task(exit #4): T#%d could not steal from "
2822                     "T#%d: task_team=%p ntasks=%d head=%u tail=%u\n",
2823                     gtid, __kmp_gtid_from_thread(victim_thr), task_team, ntasks,
2824                     victim_td->td.td_deque_head, victim_td->td.td_deque_tail));
2825       return NULL;
2826     }
2827     int prev = target;
2828     for (i = i + 1; i < ntasks; ++i) {
2829       // shift remaining tasks in the deque left by 1
2830       target = (target + 1) & TASK_DEQUE_MASK(victim_td->td);
2831       victim_td->td.td_deque[prev] = victim_td->td.td_deque[target];
2832       prev = target;
2833     }
2834     KMP_DEBUG_ASSERT(
2835         victim_td->td.td_deque_tail ==
2836         (kmp_uint32)((target + 1) & TASK_DEQUE_MASK(victim_td->td)));
2837     victim_td->td.td_deque_tail = target; // tail -= 1 (wrapped))
2838   }
2839   if (*thread_finished) {
2840     // We need to un-mark this victim as a finished victim.  This must be done
2841     // before releasing the lock, or else other threads (starting with the
2842     // primary thread victim) might be prematurely released from the barrier!!!
2843     kmp_int32 count;
2844 
2845     count = KMP_ATOMIC_INC(unfinished_threads);
2846 
2847     KA_TRACE(
2848         20,
2849         ("__kmp_steal_task: T#%d inc unfinished_threads to %d: task_team=%p\n",
2850          gtid, count + 1, task_team));
2851 
2852     *thread_finished = FALSE;
2853   }
2854   TCW_4(victim_td->td.td_deque_ntasks, ntasks - 1);
2855 
2856   __kmp_release_bootstrap_lock(&victim_td->td.td_deque_lock);
2857 
2858   KMP_COUNT_BLOCK(TASK_stolen);
2859   KA_TRACE(10,
2860            ("__kmp_steal_task(exit #5): T#%d stole task %p from T#%d: "
2861             "task_team=%p ntasks=%d head=%u tail=%u\n",
2862             gtid, taskdata, __kmp_gtid_from_thread(victim_thr), task_team,
2863             ntasks, victim_td->td.td_deque_head, victim_td->td.td_deque_tail));
2864 
2865   task = KMP_TASKDATA_TO_TASK(taskdata);
2866   return task;
2867 }
2868 
2869 // __kmp_execute_tasks_template: Choose and execute tasks until either the
2870 // condition is statisfied (return true) or there are none left (return false).
2871 //
2872 // final_spin is TRUE if this is the spin at the release barrier.
2873 // thread_finished indicates whether the thread is finished executing all
2874 // the tasks it has on its deque, and is at the release barrier.
2875 // spinner is the location on which to spin.
2876 // spinner == NULL means only execute a single task and return.
2877 // checker is the value to check to terminate the spin.
2878 template <class C>
2879 static inline int __kmp_execute_tasks_template(
2880     kmp_info_t *thread, kmp_int32 gtid, C *flag, int final_spin,
2881     int *thread_finished USE_ITT_BUILD_ARG(void *itt_sync_obj),
2882     kmp_int32 is_constrained) {
2883   kmp_task_team_t *task_team = thread->th.th_task_team;
2884   kmp_thread_data_t *threads_data;
2885   kmp_task_t *task;
2886   kmp_info_t *other_thread;
2887   kmp_taskdata_t *current_task = thread->th.th_current_task;
2888   std::atomic<kmp_int32> *unfinished_threads;
2889   kmp_int32 nthreads, victim_tid = -2, use_own_tasks = 1, new_victim = 0,
2890                       tid = thread->th.th_info.ds.ds_tid;
2891 
2892   KMP_DEBUG_ASSERT(__kmp_tasking_mode != tskm_immediate_exec);
2893   KMP_DEBUG_ASSERT(thread == __kmp_threads[gtid]);
2894 
2895   if (task_team == NULL || current_task == NULL)
2896     return FALSE;
2897 
2898   KA_TRACE(15, ("__kmp_execute_tasks_template(enter): T#%d final_spin=%d "
2899                 "*thread_finished=%d\n",
2900                 gtid, final_spin, *thread_finished));
2901 
2902   thread->th.th_reap_state = KMP_NOT_SAFE_TO_REAP;
2903   threads_data = (kmp_thread_data_t *)TCR_PTR(task_team->tt.tt_threads_data);
2904 
2905   KMP_DEBUG_ASSERT(threads_data != NULL);
2906 
2907   nthreads = task_team->tt.tt_nproc;
2908   unfinished_threads = &(task_team->tt.tt_unfinished_threads);
2909   KMP_DEBUG_ASSERT(nthreads > 1 || task_team->tt.tt_found_proxy_tasks ||
2910                    task_team->tt.tt_hidden_helper_task_encountered);
2911   KMP_DEBUG_ASSERT(*unfinished_threads >= 0);
2912 
2913   while (1) { // Outer loop keeps trying to find tasks in case of single thread
2914     // getting tasks from target constructs
2915     while (1) { // Inner loop to find a task and execute it
2916       task = NULL;
2917       if (use_own_tasks) { // check on own queue first
2918         task = __kmp_remove_my_task(thread, gtid, task_team, is_constrained);
2919       }
2920       if ((task == NULL) && (nthreads > 1)) { // Steal a task
2921         int asleep = 1;
2922         use_own_tasks = 0;
2923         // Try to steal from the last place I stole from successfully.
2924         if (victim_tid == -2) { // haven't stolen anything yet
2925           victim_tid = threads_data[tid].td.td_deque_last_stolen;
2926           if (victim_tid !=
2927               -1) // if we have a last stolen from victim, get the thread
2928             other_thread = threads_data[victim_tid].td.td_thr;
2929         }
2930         if (victim_tid != -1) { // found last victim
2931           asleep = 0;
2932         } else if (!new_victim) { // no recent steals and we haven't already
2933           // used a new victim; select a random thread
2934           do { // Find a different thread to steal work from.
2935             // Pick a random thread. Initial plan was to cycle through all the
2936             // threads, and only return if we tried to steal from every thread,
2937             // and failed.  Arch says that's not such a great idea.
2938             victim_tid = __kmp_get_random(thread) % (nthreads - 1);
2939             if (victim_tid >= tid) {
2940               ++victim_tid; // Adjusts random distribution to exclude self
2941             }
2942             // Found a potential victim
2943             other_thread = threads_data[victim_tid].td.td_thr;
2944             // There is a slight chance that __kmp_enable_tasking() did not wake
2945             // up all threads waiting at the barrier.  If victim is sleeping,
2946             // then wake it up. Since we were going to pay the cache miss
2947             // penalty for referencing another thread's kmp_info_t struct
2948             // anyway,
2949             // the check shouldn't cost too much performance at this point. In
2950             // extra barrier mode, tasks do not sleep at the separate tasking
2951             // barrier, so this isn't a problem.
2952             asleep = 0;
2953             if ((__kmp_tasking_mode == tskm_task_teams) &&
2954                 (__kmp_dflt_blocktime != KMP_MAX_BLOCKTIME) &&
2955                 (TCR_PTR(CCAST(void *, other_thread->th.th_sleep_loc)) !=
2956                  NULL)) {
2957               asleep = 1;
2958               __kmp_null_resume_wrapper(__kmp_gtid_from_thread(other_thread),
2959                                         other_thread->th.th_sleep_loc);
2960               // A sleeping thread should not have any tasks on it's queue.
2961               // There is a slight possibility that it resumes, steals a task
2962               // from another thread, which spawns more tasks, all in the time
2963               // that it takes this thread to check => don't write an assertion
2964               // that the victim's queue is empty.  Try stealing from a
2965               // different thread.
2966             }
2967           } while (asleep);
2968         }
2969 
2970         if (!asleep) {
2971           // We have a victim to try to steal from
2972           task = __kmp_steal_task(other_thread, gtid, task_team,
2973                                   unfinished_threads, thread_finished,
2974                                   is_constrained);
2975         }
2976         if (task != NULL) { // set last stolen to victim
2977           if (threads_data[tid].td.td_deque_last_stolen != victim_tid) {
2978             threads_data[tid].td.td_deque_last_stolen = victim_tid;
2979             // The pre-refactored code did not try more than 1 successful new
2980             // vicitm, unless the last one generated more local tasks;
2981             // new_victim keeps track of this
2982             new_victim = 1;
2983           }
2984         } else { // No tasks found; unset last_stolen
2985           KMP_CHECK_UPDATE(threads_data[tid].td.td_deque_last_stolen, -1);
2986           victim_tid = -2; // no successful victim found
2987         }
2988       }
2989 
2990       if (task == NULL)
2991         break; // break out of tasking loop
2992 
2993 // Found a task; execute it
2994 #if USE_ITT_BUILD && USE_ITT_NOTIFY
2995       if (__itt_sync_create_ptr || KMP_ITT_DEBUG) {
2996         if (itt_sync_obj == NULL) { // we are at fork barrier where we could not
2997           // get the object reliably
2998           itt_sync_obj = __kmp_itt_barrier_object(gtid, bs_forkjoin_barrier);
2999         }
3000         __kmp_itt_task_starting(itt_sync_obj);
3001       }
3002 #endif /* USE_ITT_BUILD && USE_ITT_NOTIFY */
3003       __kmp_invoke_task(gtid, task, current_task);
3004 #if USE_ITT_BUILD
3005       if (itt_sync_obj != NULL)
3006         __kmp_itt_task_finished(itt_sync_obj);
3007 #endif /* USE_ITT_BUILD */
3008       // If this thread is only partway through the barrier and the condition is
3009       // met, then return now, so that the barrier gather/release pattern can
3010       // proceed. If this thread is in the last spin loop in the barrier,
3011       // waiting to be released, we know that the termination condition will not
3012       // be satisfied, so don't waste any cycles checking it.
3013       if (flag == NULL || (!final_spin && flag->done_check())) {
3014         KA_TRACE(
3015             15,
3016             ("__kmp_execute_tasks_template: T#%d spin condition satisfied\n",
3017              gtid));
3018         return TRUE;
3019       }
3020       if (thread->th.th_task_team == NULL) {
3021         break;
3022       }
3023       KMP_YIELD(__kmp_library == library_throughput); // Yield before next task
3024       // If execution of a stolen task results in more tasks being placed on our
3025       // run queue, reset use_own_tasks
3026       if (!use_own_tasks && TCR_4(threads_data[tid].td.td_deque_ntasks) != 0) {
3027         KA_TRACE(20, ("__kmp_execute_tasks_template: T#%d stolen task spawned "
3028                       "other tasks, restart\n",
3029                       gtid));
3030         use_own_tasks = 1;
3031         new_victim = 0;
3032       }
3033     }
3034 
3035     // The task source has been exhausted. If in final spin loop of barrier,
3036     // check if termination condition is satisfied. The work queue may be empty
3037     // but there might be proxy tasks still executing.
3038     if (final_spin &&
3039         KMP_ATOMIC_LD_ACQ(&current_task->td_incomplete_child_tasks) == 0) {
3040       // First, decrement the #unfinished threads, if that has not already been
3041       // done.  This decrement might be to the spin location, and result in the
3042       // termination condition being satisfied.
3043       if (!*thread_finished) {
3044         kmp_int32 count;
3045 
3046         count = KMP_ATOMIC_DEC(unfinished_threads) - 1;
3047         KA_TRACE(20, ("__kmp_execute_tasks_template: T#%d dec "
3048                       "unfinished_threads to %d task_team=%p\n",
3049                       gtid, count, task_team));
3050         *thread_finished = TRUE;
3051       }
3052 
3053       // It is now unsafe to reference thread->th.th_team !!!
3054       // Decrementing task_team->tt.tt_unfinished_threads can allow the primary
3055       // thread to pass through the barrier, where it might reset each thread's
3056       // th.th_team field for the next parallel region. If we can steal more
3057       // work, we know that this has not happened yet.
3058       if (flag != NULL && flag->done_check()) {
3059         KA_TRACE(
3060             15,
3061             ("__kmp_execute_tasks_template: T#%d spin condition satisfied\n",
3062              gtid));
3063         return TRUE;
3064       }
3065     }
3066 
3067     // If this thread's task team is NULL, primary thread has recognized that
3068     // there are no more tasks; bail out
3069     if (thread->th.th_task_team == NULL) {
3070       KA_TRACE(15,
3071                ("__kmp_execute_tasks_template: T#%d no more tasks\n", gtid));
3072       return FALSE;
3073     }
3074 
3075     // We could be getting tasks from target constructs; if this is the only
3076     // thread, keep trying to execute tasks from own queue
3077     if (nthreads == 1 &&
3078         KMP_ATOMIC_LD_ACQ(&current_task->td_incomplete_child_tasks))
3079       use_own_tasks = 1;
3080     else {
3081       KA_TRACE(15,
3082                ("__kmp_execute_tasks_template: T#%d can't find work\n", gtid));
3083       return FALSE;
3084     }
3085   }
3086 }
3087 
3088 template <bool C, bool S>
3089 int __kmp_execute_tasks_32(
3090     kmp_info_t *thread, kmp_int32 gtid, kmp_flag_32<C, S> *flag, int final_spin,
3091     int *thread_finished USE_ITT_BUILD_ARG(void *itt_sync_obj),
3092     kmp_int32 is_constrained) {
3093   return __kmp_execute_tasks_template(
3094       thread, gtid, flag, final_spin,
3095       thread_finished USE_ITT_BUILD_ARG(itt_sync_obj), is_constrained);
3096 }
3097 
3098 template <bool C, bool S>
3099 int __kmp_execute_tasks_64(
3100     kmp_info_t *thread, kmp_int32 gtid, kmp_flag_64<C, S> *flag, int final_spin,
3101     int *thread_finished USE_ITT_BUILD_ARG(void *itt_sync_obj),
3102     kmp_int32 is_constrained) {
3103   return __kmp_execute_tasks_template(
3104       thread, gtid, flag, final_spin,
3105       thread_finished USE_ITT_BUILD_ARG(itt_sync_obj), is_constrained);
3106 }
3107 
3108 int __kmp_execute_tasks_oncore(
3109     kmp_info_t *thread, kmp_int32 gtid, kmp_flag_oncore *flag, int final_spin,
3110     int *thread_finished USE_ITT_BUILD_ARG(void *itt_sync_obj),
3111     kmp_int32 is_constrained) {
3112   return __kmp_execute_tasks_template(
3113       thread, gtid, flag, final_spin,
3114       thread_finished USE_ITT_BUILD_ARG(itt_sync_obj), is_constrained);
3115 }
3116 
3117 template int
3118 __kmp_execute_tasks_32<false, false>(kmp_info_t *, kmp_int32,
3119                                      kmp_flag_32<false, false> *, int,
3120                                      int *USE_ITT_BUILD_ARG(void *), kmp_int32);
3121 
3122 template int __kmp_execute_tasks_64<false, true>(kmp_info_t *, kmp_int32,
3123                                                  kmp_flag_64<false, true> *,
3124                                                  int,
3125                                                  int *USE_ITT_BUILD_ARG(void *),
3126                                                  kmp_int32);
3127 
3128 template int __kmp_execute_tasks_64<true, false>(kmp_info_t *, kmp_int32,
3129                                                  kmp_flag_64<true, false> *,
3130                                                  int,
3131                                                  int *USE_ITT_BUILD_ARG(void *),
3132                                                  kmp_int32);
3133 
3134 // __kmp_enable_tasking: Allocate task team and resume threads sleeping at the
3135 // next barrier so they can assist in executing enqueued tasks.
3136 // First thread in allocates the task team atomically.
3137 static void __kmp_enable_tasking(kmp_task_team_t *task_team,
3138                                  kmp_info_t *this_thr) {
3139   kmp_thread_data_t *threads_data;
3140   int nthreads, i, is_init_thread;
3141 
3142   KA_TRACE(10, ("__kmp_enable_tasking(enter): T#%d\n",
3143                 __kmp_gtid_from_thread(this_thr)));
3144 
3145   KMP_DEBUG_ASSERT(task_team != NULL);
3146   KMP_DEBUG_ASSERT(this_thr->th.th_team != NULL);
3147 
3148   nthreads = task_team->tt.tt_nproc;
3149   KMP_DEBUG_ASSERT(nthreads > 0);
3150   KMP_DEBUG_ASSERT(nthreads == this_thr->th.th_team->t.t_nproc);
3151 
3152   // Allocate or increase the size of threads_data if necessary
3153   is_init_thread = __kmp_realloc_task_threads_data(this_thr, task_team);
3154 
3155   if (!is_init_thread) {
3156     // Some other thread already set up the array.
3157     KA_TRACE(
3158         20,
3159         ("__kmp_enable_tasking(exit): T#%d: threads array already set up.\n",
3160          __kmp_gtid_from_thread(this_thr)));
3161     return;
3162   }
3163   threads_data = (kmp_thread_data_t *)TCR_PTR(task_team->tt.tt_threads_data);
3164   KMP_DEBUG_ASSERT(threads_data != NULL);
3165 
3166   if (__kmp_tasking_mode == tskm_task_teams &&
3167       (__kmp_dflt_blocktime != KMP_MAX_BLOCKTIME)) {
3168     // Release any threads sleeping at the barrier, so that they can steal
3169     // tasks and execute them.  In extra barrier mode, tasks do not sleep
3170     // at the separate tasking barrier, so this isn't a problem.
3171     for (i = 0; i < nthreads; i++) {
3172       volatile void *sleep_loc;
3173       kmp_info_t *thread = threads_data[i].td.td_thr;
3174 
3175       if (i == this_thr->th.th_info.ds.ds_tid) {
3176         continue;
3177       }
3178       // Since we haven't locked the thread's suspend mutex lock at this
3179       // point, there is a small window where a thread might be putting
3180       // itself to sleep, but hasn't set the th_sleep_loc field yet.
3181       // To work around this, __kmp_execute_tasks_template() periodically checks
3182       // see if other threads are sleeping (using the same random mechanism that
3183       // is used for task stealing) and awakens them if they are.
3184       if ((sleep_loc = TCR_PTR(CCAST(void *, thread->th.th_sleep_loc))) !=
3185           NULL) {
3186         KF_TRACE(50, ("__kmp_enable_tasking: T#%d waking up thread T#%d\n",
3187                       __kmp_gtid_from_thread(this_thr),
3188                       __kmp_gtid_from_thread(thread)));
3189         __kmp_null_resume_wrapper(__kmp_gtid_from_thread(thread), sleep_loc);
3190       } else {
3191         KF_TRACE(50, ("__kmp_enable_tasking: T#%d don't wake up thread T#%d\n",
3192                       __kmp_gtid_from_thread(this_thr),
3193                       __kmp_gtid_from_thread(thread)));
3194       }
3195     }
3196   }
3197 
3198   KA_TRACE(10, ("__kmp_enable_tasking(exit): T#%d\n",
3199                 __kmp_gtid_from_thread(this_thr)));
3200 }
3201 
3202 /* // TODO: Check the comment consistency
3203  * Utility routines for "task teams".  A task team (kmp_task_t) is kind of
3204  * like a shadow of the kmp_team_t data struct, with a different lifetime.
3205  * After a child * thread checks into a barrier and calls __kmp_release() from
3206  * the particular variant of __kmp_<barrier_kind>_barrier_gather(), it can no
3207  * longer assume that the kmp_team_t structure is intact (at any moment, the
3208  * primary thread may exit the barrier code and free the team data structure,
3209  * and return the threads to the thread pool).
3210  *
3211  * This does not work with the tasking code, as the thread is still
3212  * expected to participate in the execution of any tasks that may have been
3213  * spawned my a member of the team, and the thread still needs access to all
3214  * to each thread in the team, so that it can steal work from it.
3215  *
3216  * Enter the existence of the kmp_task_team_t struct.  It employs a reference
3217  * counting mechanism, and is allocated by the primary thread before calling
3218  * __kmp_<barrier_kind>_release, and then is release by the last thread to
3219  * exit __kmp_<barrier_kind>_release at the next barrier.  I.e. the lifetimes
3220  * of the kmp_task_team_t structs for consecutive barriers can overlap
3221  * (and will, unless the primary thread is the last thread to exit the barrier
3222  * release phase, which is not typical). The existence of such a struct is
3223  * useful outside the context of tasking.
3224  *
3225  * We currently use the existence of the threads array as an indicator that
3226  * tasks were spawned since the last barrier.  If the structure is to be
3227  * useful outside the context of tasking, then this will have to change, but
3228  * not setting the field minimizes the performance impact of tasking on
3229  * barriers, when no explicit tasks were spawned (pushed, actually).
3230  */
3231 
3232 static kmp_task_team_t *__kmp_free_task_teams =
3233     NULL; // Free list for task_team data structures
3234 // Lock for task team data structures
3235 kmp_bootstrap_lock_t __kmp_task_team_lock =
3236     KMP_BOOTSTRAP_LOCK_INITIALIZER(__kmp_task_team_lock);
3237 
3238 // __kmp_alloc_task_deque:
3239 // Allocates a task deque for a particular thread, and initialize the necessary
3240 // data structures relating to the deque.  This only happens once per thread
3241 // per task team since task teams are recycled. No lock is needed during
3242 // allocation since each thread allocates its own deque.
3243 static void __kmp_alloc_task_deque(kmp_info_t *thread,
3244                                    kmp_thread_data_t *thread_data) {
3245   __kmp_init_bootstrap_lock(&thread_data->td.td_deque_lock);
3246   KMP_DEBUG_ASSERT(thread_data->td.td_deque == NULL);
3247 
3248   // Initialize last stolen task field to "none"
3249   thread_data->td.td_deque_last_stolen = -1;
3250 
3251   KMP_DEBUG_ASSERT(TCR_4(thread_data->td.td_deque_ntasks) == 0);
3252   KMP_DEBUG_ASSERT(thread_data->td.td_deque_head == 0);
3253   KMP_DEBUG_ASSERT(thread_data->td.td_deque_tail == 0);
3254 
3255   KE_TRACE(
3256       10,
3257       ("__kmp_alloc_task_deque: T#%d allocating deque[%d] for thread_data %p\n",
3258        __kmp_gtid_from_thread(thread), INITIAL_TASK_DEQUE_SIZE, thread_data));
3259   // Allocate space for task deque, and zero the deque
3260   // Cannot use __kmp_thread_calloc() because threads not around for
3261   // kmp_reap_task_team( ).
3262   thread_data->td.td_deque = (kmp_taskdata_t **)__kmp_allocate(
3263       INITIAL_TASK_DEQUE_SIZE * sizeof(kmp_taskdata_t *));
3264   thread_data->td.td_deque_size = INITIAL_TASK_DEQUE_SIZE;
3265 }
3266 
3267 // __kmp_free_task_deque:
3268 // Deallocates a task deque for a particular thread. Happens at library
3269 // deallocation so don't need to reset all thread data fields.
3270 static void __kmp_free_task_deque(kmp_thread_data_t *thread_data) {
3271   if (thread_data->td.td_deque != NULL) {
3272     __kmp_acquire_bootstrap_lock(&thread_data->td.td_deque_lock);
3273     TCW_4(thread_data->td.td_deque_ntasks, 0);
3274     __kmp_free(thread_data->td.td_deque);
3275     thread_data->td.td_deque = NULL;
3276     __kmp_release_bootstrap_lock(&thread_data->td.td_deque_lock);
3277   }
3278 
3279 #ifdef BUILD_TIED_TASK_STACK
3280   // GEH: Figure out what to do here for td_susp_tied_tasks
3281   if (thread_data->td.td_susp_tied_tasks.ts_entries != TASK_STACK_EMPTY) {
3282     __kmp_free_task_stack(__kmp_thread_from_gtid(gtid), thread_data);
3283   }
3284 #endif // BUILD_TIED_TASK_STACK
3285 }
3286 
3287 // __kmp_realloc_task_threads_data:
3288 // Allocates a threads_data array for a task team, either by allocating an
3289 // initial array or enlarging an existing array.  Only the first thread to get
3290 // the lock allocs or enlarges the array and re-initializes the array elements.
3291 // That thread returns "TRUE", the rest return "FALSE".
3292 // Assumes that the new array size is given by task_team -> tt.tt_nproc.
3293 // The current size is given by task_team -> tt.tt_max_threads.
3294 static int __kmp_realloc_task_threads_data(kmp_info_t *thread,
3295                                            kmp_task_team_t *task_team) {
3296   kmp_thread_data_t **threads_data_p;
3297   kmp_int32 nthreads, maxthreads;
3298   int is_init_thread = FALSE;
3299 
3300   if (TCR_4(task_team->tt.tt_found_tasks)) {
3301     // Already reallocated and initialized.
3302     return FALSE;
3303   }
3304 
3305   threads_data_p = &task_team->tt.tt_threads_data;
3306   nthreads = task_team->tt.tt_nproc;
3307   maxthreads = task_team->tt.tt_max_threads;
3308 
3309   // All threads must lock when they encounter the first task of the implicit
3310   // task region to make sure threads_data fields are (re)initialized before
3311   // used.
3312   __kmp_acquire_bootstrap_lock(&task_team->tt.tt_threads_lock);
3313 
3314   if (!TCR_4(task_team->tt.tt_found_tasks)) {
3315     // first thread to enable tasking
3316     kmp_team_t *team = thread->th.th_team;
3317     int i;
3318 
3319     is_init_thread = TRUE;
3320     if (maxthreads < nthreads) {
3321 
3322       if (*threads_data_p != NULL) {
3323         kmp_thread_data_t *old_data = *threads_data_p;
3324         kmp_thread_data_t *new_data = NULL;
3325 
3326         KE_TRACE(
3327             10,
3328             ("__kmp_realloc_task_threads_data: T#%d reallocating "
3329              "threads data for task_team %p, new_size = %d, old_size = %d\n",
3330              __kmp_gtid_from_thread(thread), task_team, nthreads, maxthreads));
3331         // Reallocate threads_data to have more elements than current array
3332         // Cannot use __kmp_thread_realloc() because threads not around for
3333         // kmp_reap_task_team( ).  Note all new array entries are initialized
3334         // to zero by __kmp_allocate().
3335         new_data = (kmp_thread_data_t *)__kmp_allocate(
3336             nthreads * sizeof(kmp_thread_data_t));
3337         // copy old data to new data
3338         KMP_MEMCPY_S((void *)new_data, nthreads * sizeof(kmp_thread_data_t),
3339                      (void *)old_data, maxthreads * sizeof(kmp_thread_data_t));
3340 
3341 #ifdef BUILD_TIED_TASK_STACK
3342         // GEH: Figure out if this is the right thing to do
3343         for (i = maxthreads; i < nthreads; i++) {
3344           kmp_thread_data_t *thread_data = &(*threads_data_p)[i];
3345           __kmp_init_task_stack(__kmp_gtid_from_thread(thread), thread_data);
3346         }
3347 #endif // BUILD_TIED_TASK_STACK
3348        // Install the new data and free the old data
3349         (*threads_data_p) = new_data;
3350         __kmp_free(old_data);
3351       } else {
3352         KE_TRACE(10, ("__kmp_realloc_task_threads_data: T#%d allocating "
3353                       "threads data for task_team %p, size = %d\n",
3354                       __kmp_gtid_from_thread(thread), task_team, nthreads));
3355         // Make the initial allocate for threads_data array, and zero entries
3356         // Cannot use __kmp_thread_calloc() because threads not around for
3357         // kmp_reap_task_team( ).
3358         ANNOTATE_IGNORE_WRITES_BEGIN();
3359         *threads_data_p = (kmp_thread_data_t *)__kmp_allocate(
3360             nthreads * sizeof(kmp_thread_data_t));
3361         ANNOTATE_IGNORE_WRITES_END();
3362 #ifdef BUILD_TIED_TASK_STACK
3363         // GEH: Figure out if this is the right thing to do
3364         for (i = 0; i < nthreads; i++) {
3365           kmp_thread_data_t *thread_data = &(*threads_data_p)[i];
3366           __kmp_init_task_stack(__kmp_gtid_from_thread(thread), thread_data);
3367         }
3368 #endif // BUILD_TIED_TASK_STACK
3369       }
3370       task_team->tt.tt_max_threads = nthreads;
3371     } else {
3372       // If array has (more than) enough elements, go ahead and use it
3373       KMP_DEBUG_ASSERT(*threads_data_p != NULL);
3374     }
3375 
3376     // initialize threads_data pointers back to thread_info structures
3377     for (i = 0; i < nthreads; i++) {
3378       kmp_thread_data_t *thread_data = &(*threads_data_p)[i];
3379       thread_data->td.td_thr = team->t.t_threads[i];
3380 
3381       if (thread_data->td.td_deque_last_stolen >= nthreads) {
3382         // The last stolen field survives across teams / barrier, and the number
3383         // of threads may have changed.  It's possible (likely?) that a new
3384         // parallel region will exhibit the same behavior as previous region.
3385         thread_data->td.td_deque_last_stolen = -1;
3386       }
3387     }
3388 
3389     KMP_MB();
3390     TCW_SYNC_4(task_team->tt.tt_found_tasks, TRUE);
3391   }
3392 
3393   __kmp_release_bootstrap_lock(&task_team->tt.tt_threads_lock);
3394   return is_init_thread;
3395 }
3396 
3397 // __kmp_free_task_threads_data:
3398 // Deallocates a threads_data array for a task team, including any attached
3399 // tasking deques.  Only occurs at library shutdown.
3400 static void __kmp_free_task_threads_data(kmp_task_team_t *task_team) {
3401   __kmp_acquire_bootstrap_lock(&task_team->tt.tt_threads_lock);
3402   if (task_team->tt.tt_threads_data != NULL) {
3403     int i;
3404     for (i = 0; i < task_team->tt.tt_max_threads; i++) {
3405       __kmp_free_task_deque(&task_team->tt.tt_threads_data[i]);
3406     }
3407     __kmp_free(task_team->tt.tt_threads_data);
3408     task_team->tt.tt_threads_data = NULL;
3409   }
3410   __kmp_release_bootstrap_lock(&task_team->tt.tt_threads_lock);
3411 }
3412 
3413 // __kmp_allocate_task_team:
3414 // Allocates a task team associated with a specific team, taking it from
3415 // the global task team free list if possible.  Also initializes data
3416 // structures.
3417 static kmp_task_team_t *__kmp_allocate_task_team(kmp_info_t *thread,
3418                                                  kmp_team_t *team) {
3419   kmp_task_team_t *task_team = NULL;
3420   int nthreads;
3421 
3422   KA_TRACE(20, ("__kmp_allocate_task_team: T#%d entering; team = %p\n",
3423                 (thread ? __kmp_gtid_from_thread(thread) : -1), team));
3424 
3425   if (TCR_PTR(__kmp_free_task_teams) != NULL) {
3426     // Take a task team from the task team pool
3427     __kmp_acquire_bootstrap_lock(&__kmp_task_team_lock);
3428     if (__kmp_free_task_teams != NULL) {
3429       task_team = __kmp_free_task_teams;
3430       TCW_PTR(__kmp_free_task_teams, task_team->tt.tt_next);
3431       task_team->tt.tt_next = NULL;
3432     }
3433     __kmp_release_bootstrap_lock(&__kmp_task_team_lock);
3434   }
3435 
3436   if (task_team == NULL) {
3437     KE_TRACE(10, ("__kmp_allocate_task_team: T#%d allocating "
3438                   "task team for team %p\n",
3439                   __kmp_gtid_from_thread(thread), team));
3440     // Allocate a new task team if one is not available. Cannot use
3441     // __kmp_thread_malloc because threads not around for kmp_reap_task_team.
3442     task_team = (kmp_task_team_t *)__kmp_allocate(sizeof(kmp_task_team_t));
3443     __kmp_init_bootstrap_lock(&task_team->tt.tt_threads_lock);
3444 #if USE_ITT_BUILD && USE_ITT_NOTIFY && KMP_DEBUG
3445     // suppress race conditions detection on synchronization flags in debug mode
3446     // this helps to analyze library internals eliminating false positives
3447     __itt_suppress_mark_range(
3448         __itt_suppress_range, __itt_suppress_threading_errors,
3449         &task_team->tt.tt_found_tasks, sizeof(task_team->tt.tt_found_tasks));
3450     __itt_suppress_mark_range(__itt_suppress_range,
3451                               __itt_suppress_threading_errors,
3452                               CCAST(kmp_uint32 *, &task_team->tt.tt_active),
3453                               sizeof(task_team->tt.tt_active));
3454 #endif /* USE_ITT_BUILD && USE_ITT_NOTIFY && KMP_DEBUG */
3455     // Note: __kmp_allocate zeroes returned memory, othewise we would need:
3456     // task_team->tt.tt_threads_data = NULL;
3457     // task_team->tt.tt_max_threads = 0;
3458     // task_team->tt.tt_next = NULL;
3459   }
3460 
3461   TCW_4(task_team->tt.tt_found_tasks, FALSE);
3462   TCW_4(task_team->tt.tt_found_proxy_tasks, FALSE);
3463   task_team->tt.tt_nproc = nthreads = team->t.t_nproc;
3464 
3465   KMP_ATOMIC_ST_REL(&task_team->tt.tt_unfinished_threads, nthreads);
3466   TCW_4(task_team->tt.tt_hidden_helper_task_encountered, FALSE);
3467   TCW_4(task_team->tt.tt_active, TRUE);
3468 
3469   KA_TRACE(20, ("__kmp_allocate_task_team: T#%d exiting; task_team = %p "
3470                 "unfinished_threads init'd to %d\n",
3471                 (thread ? __kmp_gtid_from_thread(thread) : -1), task_team,
3472                 KMP_ATOMIC_LD_RLX(&task_team->tt.tt_unfinished_threads)));
3473   return task_team;
3474 }
3475 
3476 // __kmp_free_task_team:
3477 // Frees the task team associated with a specific thread, and adds it
3478 // to the global task team free list.
3479 void __kmp_free_task_team(kmp_info_t *thread, kmp_task_team_t *task_team) {
3480   KA_TRACE(20, ("__kmp_free_task_team: T#%d task_team = %p\n",
3481                 thread ? __kmp_gtid_from_thread(thread) : -1, task_team));
3482 
3483   // Put task team back on free list
3484   __kmp_acquire_bootstrap_lock(&__kmp_task_team_lock);
3485 
3486   KMP_DEBUG_ASSERT(task_team->tt.tt_next == NULL);
3487   task_team->tt.tt_next = __kmp_free_task_teams;
3488   TCW_PTR(__kmp_free_task_teams, task_team);
3489 
3490   __kmp_release_bootstrap_lock(&__kmp_task_team_lock);
3491 }
3492 
3493 // __kmp_reap_task_teams:
3494 // Free all the task teams on the task team free list.
3495 // Should only be done during library shutdown.
3496 // Cannot do anything that needs a thread structure or gtid since they are
3497 // already gone.
3498 void __kmp_reap_task_teams(void) {
3499   kmp_task_team_t *task_team;
3500 
3501   if (TCR_PTR(__kmp_free_task_teams) != NULL) {
3502     // Free all task_teams on the free list
3503     __kmp_acquire_bootstrap_lock(&__kmp_task_team_lock);
3504     while ((task_team = __kmp_free_task_teams) != NULL) {
3505       __kmp_free_task_teams = task_team->tt.tt_next;
3506       task_team->tt.tt_next = NULL;
3507 
3508       // Free threads_data if necessary
3509       if (task_team->tt.tt_threads_data != NULL) {
3510         __kmp_free_task_threads_data(task_team);
3511       }
3512       __kmp_free(task_team);
3513     }
3514     __kmp_release_bootstrap_lock(&__kmp_task_team_lock);
3515   }
3516 }
3517 
3518 // __kmp_wait_to_unref_task_teams:
3519 // Some threads could still be in the fork barrier release code, possibly
3520 // trying to steal tasks.  Wait for each thread to unreference its task team.
3521 void __kmp_wait_to_unref_task_teams(void) {
3522   kmp_info_t *thread;
3523   kmp_uint32 spins;
3524   int done;
3525 
3526   KMP_INIT_YIELD(spins);
3527 
3528   for (;;) {
3529     done = TRUE;
3530 
3531     // TODO: GEH - this may be is wrong because some sync would be necessary
3532     // in case threads are added to the pool during the traversal. Need to
3533     // verify that lock for thread pool is held when calling this routine.
3534     for (thread = CCAST(kmp_info_t *, __kmp_thread_pool); thread != NULL;
3535          thread = thread->th.th_next_pool) {
3536 #if KMP_OS_WINDOWS
3537       DWORD exit_val;
3538 #endif
3539       if (TCR_PTR(thread->th.th_task_team) == NULL) {
3540         KA_TRACE(10, ("__kmp_wait_to_unref_task_team: T#%d task_team == NULL\n",
3541                       __kmp_gtid_from_thread(thread)));
3542         continue;
3543       }
3544 #if KMP_OS_WINDOWS
3545       // TODO: GEH - add this check for Linux* OS / OS X* as well?
3546       if (!__kmp_is_thread_alive(thread, &exit_val)) {
3547         thread->th.th_task_team = NULL;
3548         continue;
3549       }
3550 #endif
3551 
3552       done = FALSE; // Because th_task_team pointer is not NULL for this thread
3553 
3554       KA_TRACE(10, ("__kmp_wait_to_unref_task_team: Waiting for T#%d to "
3555                     "unreference task_team\n",
3556                     __kmp_gtid_from_thread(thread)));
3557 
3558       if (__kmp_dflt_blocktime != KMP_MAX_BLOCKTIME) {
3559         volatile void *sleep_loc;
3560         // If the thread is sleeping, awaken it.
3561         if ((sleep_loc = TCR_PTR(CCAST(void *, thread->th.th_sleep_loc))) !=
3562             NULL) {
3563           KA_TRACE(
3564               10,
3565               ("__kmp_wait_to_unref_task_team: T#%d waking up thread T#%d\n",
3566                __kmp_gtid_from_thread(thread), __kmp_gtid_from_thread(thread)));
3567           __kmp_null_resume_wrapper(__kmp_gtid_from_thread(thread), sleep_loc);
3568         }
3569       }
3570     }
3571     if (done) {
3572       break;
3573     }
3574 
3575     // If oversubscribed or have waited a bit, yield.
3576     KMP_YIELD_OVERSUB_ELSE_SPIN(spins);
3577   }
3578 }
3579 
3580 // __kmp_task_team_setup:  Create a task_team for the current team, but use
3581 // an already created, unused one if it already exists.
3582 void __kmp_task_team_setup(kmp_info_t *this_thr, kmp_team_t *team, int always) {
3583   KMP_DEBUG_ASSERT(__kmp_tasking_mode != tskm_immediate_exec);
3584 
3585   // If this task_team hasn't been created yet, allocate it. It will be used in
3586   // the region after the next.
3587   // If it exists, it is the current task team and shouldn't be touched yet as
3588   // it may still be in use.
3589   if (team->t.t_task_team[this_thr->th.th_task_state] == NULL &&
3590       (always || team->t.t_nproc > 1)) {
3591     team->t.t_task_team[this_thr->th.th_task_state] =
3592         __kmp_allocate_task_team(this_thr, team);
3593     KA_TRACE(20, ("__kmp_task_team_setup: Primary T#%d created new task_team %p"
3594                   " for team %d at parity=%d\n",
3595                   __kmp_gtid_from_thread(this_thr),
3596                   team->t.t_task_team[this_thr->th.th_task_state],
3597                   ((team != NULL) ? team->t.t_id : -1),
3598                   this_thr->th.th_task_state));
3599   }
3600 
3601   // After threads exit the release, they will call sync, and then point to this
3602   // other task_team; make sure it is allocated and properly initialized. As
3603   // threads spin in the barrier release phase, they will continue to use the
3604   // previous task_team struct(above), until they receive the signal to stop
3605   // checking for tasks (they can't safely reference the kmp_team_t struct,
3606   // which could be reallocated by the primary thread). No task teams are formed
3607   // for serialized teams.
3608   if (team->t.t_nproc > 1) {
3609     int other_team = 1 - this_thr->th.th_task_state;
3610     if (team->t.t_task_team[other_team] == NULL) { // setup other team as well
3611       team->t.t_task_team[other_team] =
3612           __kmp_allocate_task_team(this_thr, team);
3613       KA_TRACE(20, ("__kmp_task_team_setup: Primary T#%d created second new "
3614                     "task_team %p for team %d at parity=%d\n",
3615                     __kmp_gtid_from_thread(this_thr),
3616                     team->t.t_task_team[other_team],
3617                     ((team != NULL) ? team->t.t_id : -1), other_team));
3618     } else { // Leave the old task team struct in place for the upcoming region;
3619       // adjust as needed
3620       kmp_task_team_t *task_team = team->t.t_task_team[other_team];
3621       if (!task_team->tt.tt_active ||
3622           team->t.t_nproc != task_team->tt.tt_nproc) {
3623         TCW_4(task_team->tt.tt_nproc, team->t.t_nproc);
3624         TCW_4(task_team->tt.tt_found_tasks, FALSE);
3625         TCW_4(task_team->tt.tt_found_proxy_tasks, FALSE);
3626         KMP_ATOMIC_ST_REL(&task_team->tt.tt_unfinished_threads,
3627                           team->t.t_nproc);
3628         TCW_4(task_team->tt.tt_active, TRUE);
3629       }
3630       // if team size has changed, the first thread to enable tasking will
3631       // realloc threads_data if necessary
3632       KA_TRACE(20, ("__kmp_task_team_setup: Primary T#%d reset next task_team "
3633                     "%p for team %d at parity=%d\n",
3634                     __kmp_gtid_from_thread(this_thr),
3635                     team->t.t_task_team[other_team],
3636                     ((team != NULL) ? team->t.t_id : -1), other_team));
3637     }
3638   }
3639 
3640   // For regular thread, task enabling should be called when the task is going
3641   // to be pushed to a dequeue. However, for the hidden helper thread, we need
3642   // it ahead of time so that some operations can be performed without race
3643   // condition.
3644   if (this_thr == __kmp_hidden_helper_main_thread) {
3645     for (int i = 0; i < 2; ++i) {
3646       kmp_task_team_t *task_team = team->t.t_task_team[i];
3647       if (KMP_TASKING_ENABLED(task_team)) {
3648         continue;
3649       }
3650       __kmp_enable_tasking(task_team, this_thr);
3651       for (int j = 0; j < task_team->tt.tt_nproc; ++j) {
3652         kmp_thread_data_t *thread_data = &task_team->tt.tt_threads_data[j];
3653         if (thread_data->td.td_deque == NULL) {
3654           __kmp_alloc_task_deque(__kmp_hidden_helper_threads[j], thread_data);
3655         }
3656       }
3657     }
3658   }
3659 }
3660 
3661 // __kmp_task_team_sync: Propagation of task team data from team to threads
3662 // which happens just after the release phase of a team barrier.  This may be
3663 // called by any thread, but only for teams with # threads > 1.
3664 void __kmp_task_team_sync(kmp_info_t *this_thr, kmp_team_t *team) {
3665   KMP_DEBUG_ASSERT(__kmp_tasking_mode != tskm_immediate_exec);
3666 
3667   // Toggle the th_task_state field, to switch which task_team this thread
3668   // refers to
3669   this_thr->th.th_task_state = (kmp_uint8)(1 - this_thr->th.th_task_state);
3670 
3671   // It is now safe to propagate the task team pointer from the team struct to
3672   // the current thread.
3673   TCW_PTR(this_thr->th.th_task_team,
3674           team->t.t_task_team[this_thr->th.th_task_state]);
3675   KA_TRACE(20,
3676            ("__kmp_task_team_sync: Thread T#%d task team switched to task_team "
3677             "%p from Team #%d (parity=%d)\n",
3678             __kmp_gtid_from_thread(this_thr), this_thr->th.th_task_team,
3679             ((team != NULL) ? team->t.t_id : -1), this_thr->th.th_task_state));
3680 }
3681 
3682 // __kmp_task_team_wait: Primary thread waits for outstanding tasks after the
3683 // barrier gather phase. Only called by primary thread if #threads in team > 1
3684 // or if proxy tasks were created.
3685 //
3686 // wait is a flag that defaults to 1 (see kmp.h), but waiting can be turned off
3687 // by passing in 0 optionally as the last argument. When wait is zero, primary
3688 // thread does not wait for unfinished_threads to reach 0.
3689 void __kmp_task_team_wait(
3690     kmp_info_t *this_thr,
3691     kmp_team_t *team USE_ITT_BUILD_ARG(void *itt_sync_obj), int wait) {
3692   kmp_task_team_t *task_team = team->t.t_task_team[this_thr->th.th_task_state];
3693 
3694   KMP_DEBUG_ASSERT(__kmp_tasking_mode != tskm_immediate_exec);
3695   KMP_DEBUG_ASSERT(task_team == this_thr->th.th_task_team);
3696 
3697   if ((task_team != NULL) && KMP_TASKING_ENABLED(task_team)) {
3698     if (wait) {
3699       KA_TRACE(20, ("__kmp_task_team_wait: Primary T#%d waiting for all tasks "
3700                     "(for unfinished_threads to reach 0) on task_team = %p\n",
3701                     __kmp_gtid_from_thread(this_thr), task_team));
3702       // Worker threads may have dropped through to release phase, but could
3703       // still be executing tasks. Wait here for tasks to complete. To avoid
3704       // memory contention, only primary thread checks termination condition.
3705       kmp_flag_32<false, false> flag(
3706           RCAST(std::atomic<kmp_uint32> *,
3707                 &task_team->tt.tt_unfinished_threads),
3708           0U);
3709       flag.wait(this_thr, TRUE USE_ITT_BUILD_ARG(itt_sync_obj));
3710     }
3711     // Deactivate the old task team, so that the worker threads will stop
3712     // referencing it while spinning.
3713     KA_TRACE(
3714         20,
3715         ("__kmp_task_team_wait: Primary T#%d deactivating task_team %p: "
3716          "setting active to false, setting local and team's pointer to NULL\n",
3717          __kmp_gtid_from_thread(this_thr), task_team));
3718     KMP_DEBUG_ASSERT(task_team->tt.tt_nproc > 1 ||
3719                      task_team->tt.tt_found_proxy_tasks == TRUE);
3720     TCW_SYNC_4(task_team->tt.tt_found_proxy_tasks, FALSE);
3721     KMP_CHECK_UPDATE(task_team->tt.tt_untied_task_encountered, 0);
3722     TCW_SYNC_4(task_team->tt.tt_active, FALSE);
3723     KMP_MB();
3724 
3725     TCW_PTR(this_thr->th.th_task_team, NULL);
3726   }
3727 }
3728 
3729 // __kmp_tasking_barrier:
3730 // This routine is called only when __kmp_tasking_mode == tskm_extra_barrier.
3731 // Internal function to execute all tasks prior to a regular barrier or a join
3732 // barrier. It is a full barrier itself, which unfortunately turns regular
3733 // barriers into double barriers and join barriers into 1 1/2 barriers.
3734 void __kmp_tasking_barrier(kmp_team_t *team, kmp_info_t *thread, int gtid) {
3735   std::atomic<kmp_uint32> *spin = RCAST(
3736       std::atomic<kmp_uint32> *,
3737       &team->t.t_task_team[thread->th.th_task_state]->tt.tt_unfinished_threads);
3738   int flag = FALSE;
3739   KMP_DEBUG_ASSERT(__kmp_tasking_mode == tskm_extra_barrier);
3740 
3741 #if USE_ITT_BUILD
3742   KMP_FSYNC_SPIN_INIT(spin, NULL);
3743 #endif /* USE_ITT_BUILD */
3744   kmp_flag_32<false, false> spin_flag(spin, 0U);
3745   while (!spin_flag.execute_tasks(thread, gtid, TRUE,
3746                                   &flag USE_ITT_BUILD_ARG(NULL), 0)) {
3747 #if USE_ITT_BUILD
3748     // TODO: What about itt_sync_obj??
3749     KMP_FSYNC_SPIN_PREPARE(RCAST(void *, spin));
3750 #endif /* USE_ITT_BUILD */
3751 
3752     if (TCR_4(__kmp_global.g.g_done)) {
3753       if (__kmp_global.g.g_abort)
3754         __kmp_abort_thread();
3755       break;
3756     }
3757     KMP_YIELD(TRUE);
3758   }
3759 #if USE_ITT_BUILD
3760   KMP_FSYNC_SPIN_ACQUIRED(RCAST(void *, spin));
3761 #endif /* USE_ITT_BUILD */
3762 }
3763 
3764 // __kmp_give_task puts a task into a given thread queue if:
3765 //  - the queue for that thread was created
3766 //  - there's space in that queue
3767 // Because of this, __kmp_push_task needs to check if there's space after
3768 // getting the lock
3769 static bool __kmp_give_task(kmp_info_t *thread, kmp_int32 tid, kmp_task_t *task,
3770                             kmp_int32 pass) {
3771   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(task);
3772   kmp_task_team_t *task_team = taskdata->td_task_team;
3773 
3774   KA_TRACE(20, ("__kmp_give_task: trying to give task %p to thread %d.\n",
3775                 taskdata, tid));
3776 
3777   // If task_team is NULL something went really bad...
3778   KMP_DEBUG_ASSERT(task_team != NULL);
3779 
3780   bool result = false;
3781   kmp_thread_data_t *thread_data = &task_team->tt.tt_threads_data[tid];
3782 
3783   if (thread_data->td.td_deque == NULL) {
3784     // There's no queue in this thread, go find another one
3785     // We're guaranteed that at least one thread has a queue
3786     KA_TRACE(30,
3787              ("__kmp_give_task: thread %d has no queue while giving task %p.\n",
3788               tid, taskdata));
3789     return result;
3790   }
3791 
3792   if (TCR_4(thread_data->td.td_deque_ntasks) >=
3793       TASK_DEQUE_SIZE(thread_data->td)) {
3794     KA_TRACE(
3795         30,
3796         ("__kmp_give_task: queue is full while giving task %p to thread %d.\n",
3797          taskdata, tid));
3798 
3799     // if this deque is bigger than the pass ratio give a chance to another
3800     // thread
3801     if (TASK_DEQUE_SIZE(thread_data->td) / INITIAL_TASK_DEQUE_SIZE >= pass)
3802       return result;
3803 
3804     __kmp_acquire_bootstrap_lock(&thread_data->td.td_deque_lock);
3805     if (TCR_4(thread_data->td.td_deque_ntasks) >=
3806         TASK_DEQUE_SIZE(thread_data->td)) {
3807       // expand deque to push the task which is not allowed to execute
3808       __kmp_realloc_task_deque(thread, thread_data);
3809     }
3810 
3811   } else {
3812 
3813     __kmp_acquire_bootstrap_lock(&thread_data->td.td_deque_lock);
3814 
3815     if (TCR_4(thread_data->td.td_deque_ntasks) >=
3816         TASK_DEQUE_SIZE(thread_data->td)) {
3817       KA_TRACE(30, ("__kmp_give_task: queue is full while giving task %p to "
3818                     "thread %d.\n",
3819                     taskdata, tid));
3820 
3821       // if this deque is bigger than the pass ratio give a chance to another
3822       // thread
3823       if (TASK_DEQUE_SIZE(thread_data->td) / INITIAL_TASK_DEQUE_SIZE >= pass)
3824         goto release_and_exit;
3825 
3826       __kmp_realloc_task_deque(thread, thread_data);
3827     }
3828   }
3829 
3830   // lock is held here, and there is space in the deque
3831 
3832   thread_data->td.td_deque[thread_data->td.td_deque_tail] = taskdata;
3833   // Wrap index.
3834   thread_data->td.td_deque_tail =
3835       (thread_data->td.td_deque_tail + 1) & TASK_DEQUE_MASK(thread_data->td);
3836   TCW_4(thread_data->td.td_deque_ntasks,
3837         TCR_4(thread_data->td.td_deque_ntasks) + 1);
3838 
3839   result = true;
3840   KA_TRACE(30, ("__kmp_give_task: successfully gave task %p to thread %d.\n",
3841                 taskdata, tid));
3842 
3843 release_and_exit:
3844   __kmp_release_bootstrap_lock(&thread_data->td.td_deque_lock);
3845 
3846   return result;
3847 }
3848 
3849 /* The finish of the proxy tasks is divided in two pieces:
3850     - the top half is the one that can be done from a thread outside the team
3851     - the bottom half must be run from a thread within the team
3852 
3853    In order to run the bottom half the task gets queued back into one of the
3854    threads of the team. Once the td_incomplete_child_task counter of the parent
3855    is decremented the threads can leave the barriers. So, the bottom half needs
3856    to be queued before the counter is decremented. The top half is therefore
3857    divided in two parts:
3858     - things that can be run before queuing the bottom half
3859     - things that must be run after queuing the bottom half
3860 
3861    This creates a second race as the bottom half can free the task before the
3862    second top half is executed. To avoid this we use the
3863    td_incomplete_child_task of the proxy task to synchronize the top and bottom
3864    half. */
3865 static void __kmp_first_top_half_finish_proxy(kmp_taskdata_t *taskdata) {
3866   KMP_DEBUG_ASSERT(taskdata->td_flags.tasktype == TASK_EXPLICIT);
3867   KMP_DEBUG_ASSERT(taskdata->td_flags.proxy == TASK_PROXY);
3868   KMP_DEBUG_ASSERT(taskdata->td_flags.complete == 0);
3869   KMP_DEBUG_ASSERT(taskdata->td_flags.freed == 0);
3870 
3871   taskdata->td_flags.complete = 1; // mark the task as completed
3872 
3873   if (taskdata->td_taskgroup)
3874     KMP_ATOMIC_DEC(&taskdata->td_taskgroup->count);
3875 
3876   // Create an imaginary children for this task so the bottom half cannot
3877   // release the task before we have completed the second top half
3878   KMP_ATOMIC_INC(&taskdata->td_incomplete_child_tasks);
3879 }
3880 
3881 static void __kmp_second_top_half_finish_proxy(kmp_taskdata_t *taskdata) {
3882   kmp_int32 children = 0;
3883 
3884   // Predecrement simulated by "- 1" calculation
3885   children =
3886       KMP_ATOMIC_DEC(&taskdata->td_parent->td_incomplete_child_tasks) - 1;
3887   KMP_DEBUG_ASSERT(children >= 0);
3888 
3889   // Remove the imaginary children
3890   KMP_ATOMIC_DEC(&taskdata->td_incomplete_child_tasks);
3891 }
3892 
3893 static void __kmp_bottom_half_finish_proxy(kmp_int32 gtid, kmp_task_t *ptask) {
3894   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(ptask);
3895   kmp_info_t *thread = __kmp_threads[gtid];
3896 
3897   KMP_DEBUG_ASSERT(taskdata->td_flags.proxy == TASK_PROXY);
3898   KMP_DEBUG_ASSERT(taskdata->td_flags.complete ==
3899                    1); // top half must run before bottom half
3900 
3901   // We need to wait to make sure the top half is finished
3902   // Spinning here should be ok as this should happen quickly
3903   while (KMP_ATOMIC_LD_ACQ(&taskdata->td_incomplete_child_tasks) > 0)
3904     ;
3905 
3906   __kmp_release_deps(gtid, taskdata);
3907   __kmp_free_task_and_ancestors(gtid, taskdata, thread);
3908 }
3909 
3910 /*!
3911 @ingroup TASKING
3912 @param gtid Global Thread ID of encountering thread
3913 @param ptask Task which execution is completed
3914 
3915 Execute the completion of a proxy task from a thread of that is part of the
3916 team. Run first and bottom halves directly.
3917 */
3918 void __kmpc_proxy_task_completed(kmp_int32 gtid, kmp_task_t *ptask) {
3919   KMP_DEBUG_ASSERT(ptask != NULL);
3920   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(ptask);
3921   KA_TRACE(
3922       10, ("__kmp_proxy_task_completed(enter): T#%d proxy task %p completing\n",
3923            gtid, taskdata));
3924   __kmp_assert_valid_gtid(gtid);
3925   KMP_DEBUG_ASSERT(taskdata->td_flags.proxy == TASK_PROXY);
3926 
3927   __kmp_first_top_half_finish_proxy(taskdata);
3928   __kmp_second_top_half_finish_proxy(taskdata);
3929   __kmp_bottom_half_finish_proxy(gtid, ptask);
3930 
3931   KA_TRACE(10,
3932            ("__kmp_proxy_task_completed(exit): T#%d proxy task %p completing\n",
3933             gtid, taskdata));
3934 }
3935 
3936 /*!
3937 @ingroup TASKING
3938 @param ptask Task which execution is completed
3939 
3940 Execute the completion of a proxy task from a thread that could not belong to
3941 the team.
3942 */
3943 void __kmpc_proxy_task_completed_ooo(kmp_task_t *ptask) {
3944   KMP_DEBUG_ASSERT(ptask != NULL);
3945   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(ptask);
3946 
3947   KA_TRACE(
3948       10,
3949       ("__kmp_proxy_task_completed_ooo(enter): proxy task completing ooo %p\n",
3950        taskdata));
3951 
3952   KMP_DEBUG_ASSERT(taskdata->td_flags.proxy == TASK_PROXY);
3953 
3954   __kmp_first_top_half_finish_proxy(taskdata);
3955 
3956   // Enqueue task to complete bottom half completion from a thread within the
3957   // corresponding team
3958   kmp_team_t *team = taskdata->td_team;
3959   kmp_int32 nthreads = team->t.t_nproc;
3960   kmp_info_t *thread;
3961 
3962   // This should be similar to start_k = __kmp_get_random( thread ) % nthreads
3963   // but we cannot use __kmp_get_random here
3964   kmp_int32 start_k = 0;
3965   kmp_int32 pass = 1;
3966   kmp_int32 k = start_k;
3967 
3968   do {
3969     // For now we're just linearly trying to find a thread
3970     thread = team->t.t_threads[k];
3971     k = (k + 1) % nthreads;
3972 
3973     // we did a full pass through all the threads
3974     if (k == start_k)
3975       pass = pass << 1;
3976 
3977   } while (!__kmp_give_task(thread, k, ptask, pass));
3978 
3979   __kmp_second_top_half_finish_proxy(taskdata);
3980 
3981   KA_TRACE(
3982       10,
3983       ("__kmp_proxy_task_completed_ooo(exit): proxy task completing ooo %p\n",
3984        taskdata));
3985 }
3986 
3987 kmp_event_t *__kmpc_task_allow_completion_event(ident_t *loc_ref, int gtid,
3988                                                 kmp_task_t *task) {
3989   kmp_taskdata_t *td = KMP_TASK_TO_TASKDATA(task);
3990   if (td->td_allow_completion_event.type == KMP_EVENT_UNINITIALIZED) {
3991     td->td_allow_completion_event.type = KMP_EVENT_ALLOW_COMPLETION;
3992     td->td_allow_completion_event.ed.task = task;
3993     __kmp_init_tas_lock(&td->td_allow_completion_event.lock);
3994   }
3995   return &td->td_allow_completion_event;
3996 }
3997 
3998 void __kmp_fulfill_event(kmp_event_t *event) {
3999   if (event->type == KMP_EVENT_ALLOW_COMPLETION) {
4000     kmp_task_t *ptask = event->ed.task;
4001     kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(ptask);
4002     bool detached = false;
4003     int gtid = __kmp_get_gtid();
4004 
4005     // The associated task might have completed or could be completing at this
4006     // point.
4007     // We need to take the lock to avoid races
4008     __kmp_acquire_tas_lock(&event->lock, gtid);
4009     if (taskdata->td_flags.proxy == TASK_PROXY) {
4010       detached = true;
4011     } else {
4012 #if OMPT_SUPPORT
4013       // The OMPT event must occur under mutual exclusion,
4014       // otherwise the tool might access ptask after free
4015       if (UNLIKELY(ompt_enabled.enabled))
4016         __ompt_task_finish(ptask, NULL, ompt_task_early_fulfill);
4017 #endif
4018     }
4019     event->type = KMP_EVENT_UNINITIALIZED;
4020     __kmp_release_tas_lock(&event->lock, gtid);
4021 
4022     if (detached) {
4023 #if OMPT_SUPPORT
4024       // We free ptask afterwards and know the task is finished,
4025       // so locking is not necessary
4026       if (UNLIKELY(ompt_enabled.enabled))
4027         __ompt_task_finish(ptask, NULL, ompt_task_late_fulfill);
4028 #endif
4029       // If the task detached complete the proxy task
4030       if (gtid >= 0) {
4031         kmp_team_t *team = taskdata->td_team;
4032         kmp_info_t *thread = __kmp_get_thread();
4033         if (thread->th.th_team == team) {
4034           __kmpc_proxy_task_completed(gtid, ptask);
4035           return;
4036         }
4037       }
4038 
4039       // fallback
4040       __kmpc_proxy_task_completed_ooo(ptask);
4041     }
4042   }
4043 }
4044 
4045 // __kmp_task_dup_alloc: Allocate the taskdata and make a copy of source task
4046 // for taskloop
4047 //
4048 // thread:   allocating thread
4049 // task_src: pointer to source task to be duplicated
4050 // returns:  a pointer to the allocated kmp_task_t structure (task).
4051 kmp_task_t *__kmp_task_dup_alloc(kmp_info_t *thread, kmp_task_t *task_src) {
4052   kmp_task_t *task;
4053   kmp_taskdata_t *taskdata;
4054   kmp_taskdata_t *taskdata_src = KMP_TASK_TO_TASKDATA(task_src);
4055   kmp_taskdata_t *parent_task = taskdata_src->td_parent; // same parent task
4056   size_t shareds_offset;
4057   size_t task_size;
4058 
4059   KA_TRACE(10, ("__kmp_task_dup_alloc(enter): Th %p, source task %p\n", thread,
4060                 task_src));
4061   KMP_DEBUG_ASSERT(taskdata_src->td_flags.proxy ==
4062                    TASK_FULL); // it should not be proxy task
4063   KMP_DEBUG_ASSERT(taskdata_src->td_flags.tasktype == TASK_EXPLICIT);
4064   task_size = taskdata_src->td_size_alloc;
4065 
4066   // Allocate a kmp_taskdata_t block and a kmp_task_t block.
4067   KA_TRACE(30, ("__kmp_task_dup_alloc: Th %p, malloc size %ld\n", thread,
4068                 task_size));
4069 #if USE_FAST_MEMORY
4070   taskdata = (kmp_taskdata_t *)__kmp_fast_allocate(thread, task_size);
4071 #else
4072   taskdata = (kmp_taskdata_t *)__kmp_thread_malloc(thread, task_size);
4073 #endif /* USE_FAST_MEMORY */
4074   KMP_MEMCPY(taskdata, taskdata_src, task_size);
4075 
4076   task = KMP_TASKDATA_TO_TASK(taskdata);
4077 
4078   // Initialize new task (only specific fields not affected by memcpy)
4079   taskdata->td_task_id = KMP_GEN_TASK_ID();
4080   if (task->shareds != NULL) { // need setup shareds pointer
4081     shareds_offset = (char *)task_src->shareds - (char *)taskdata_src;
4082     task->shareds = &((char *)taskdata)[shareds_offset];
4083     KMP_DEBUG_ASSERT((((kmp_uintptr_t)task->shareds) & (sizeof(void *) - 1)) ==
4084                      0);
4085   }
4086   taskdata->td_alloc_thread = thread;
4087   taskdata->td_parent = parent_task;
4088   // task inherits the taskgroup from the parent task
4089   taskdata->td_taskgroup = parent_task->td_taskgroup;
4090   // tied task needs to initialize the td_last_tied at creation,
4091   // untied one does this when it is scheduled for execution
4092   if (taskdata->td_flags.tiedness == TASK_TIED)
4093     taskdata->td_last_tied = taskdata;
4094 
4095   // Only need to keep track of child task counts if team parallel and tasking
4096   // not serialized
4097   if (!(taskdata->td_flags.team_serial || taskdata->td_flags.tasking_ser)) {
4098     KMP_ATOMIC_INC(&parent_task->td_incomplete_child_tasks);
4099     if (parent_task->td_taskgroup)
4100       KMP_ATOMIC_INC(&parent_task->td_taskgroup->count);
4101     // Only need to keep track of allocated child tasks for explicit tasks since
4102     // implicit not deallocated
4103     if (taskdata->td_parent->td_flags.tasktype == TASK_EXPLICIT)
4104       KMP_ATOMIC_INC(&taskdata->td_parent->td_allocated_child_tasks);
4105   }
4106 
4107   KA_TRACE(20,
4108            ("__kmp_task_dup_alloc(exit): Th %p, created task %p, parent=%p\n",
4109             thread, taskdata, taskdata->td_parent));
4110 #if OMPT_SUPPORT
4111   if (UNLIKELY(ompt_enabled.enabled))
4112     __ompt_task_init(taskdata, thread->th.th_info.ds.ds_gtid);
4113 #endif
4114   return task;
4115 }
4116 
4117 // Routine optionally generated by the compiler for setting the lastprivate flag
4118 // and calling needed constructors for private/firstprivate objects
4119 // (used to form taskloop tasks from pattern task)
4120 // Parameters: dest task, src task, lastprivate flag.
4121 typedef void (*p_task_dup_t)(kmp_task_t *, kmp_task_t *, kmp_int32);
4122 
4123 KMP_BUILD_ASSERT(sizeof(long) == 4 || sizeof(long) == 8);
4124 
4125 // class to encapsulate manipulating loop bounds in a taskloop task.
4126 // this abstracts away the Intel vs GOMP taskloop interface for setting/getting
4127 // the loop bound variables.
4128 class kmp_taskloop_bounds_t {
4129   kmp_task_t *task;
4130   const kmp_taskdata_t *taskdata;
4131   size_t lower_offset;
4132   size_t upper_offset;
4133 
4134 public:
4135   kmp_taskloop_bounds_t(kmp_task_t *_task, kmp_uint64 *lb, kmp_uint64 *ub)
4136       : task(_task), taskdata(KMP_TASK_TO_TASKDATA(task)),
4137         lower_offset((char *)lb - (char *)task),
4138         upper_offset((char *)ub - (char *)task) {
4139     KMP_DEBUG_ASSERT((char *)lb > (char *)_task);
4140     KMP_DEBUG_ASSERT((char *)ub > (char *)_task);
4141   }
4142   kmp_taskloop_bounds_t(kmp_task_t *_task, const kmp_taskloop_bounds_t &bounds)
4143       : task(_task), taskdata(KMP_TASK_TO_TASKDATA(_task)),
4144         lower_offset(bounds.lower_offset), upper_offset(bounds.upper_offset) {}
4145   size_t get_lower_offset() const { return lower_offset; }
4146   size_t get_upper_offset() const { return upper_offset; }
4147   kmp_uint64 get_lb() const {
4148     kmp_int64 retval;
4149 #if defined(KMP_GOMP_COMPAT)
4150     // Intel task just returns the lower bound normally
4151     if (!taskdata->td_flags.native) {
4152       retval = *(kmp_int64 *)((char *)task + lower_offset);
4153     } else {
4154       // GOMP task has to take into account the sizeof(long)
4155       if (taskdata->td_size_loop_bounds == 4) {
4156         kmp_int32 *lb = RCAST(kmp_int32 *, task->shareds);
4157         retval = (kmp_int64)*lb;
4158       } else {
4159         kmp_int64 *lb = RCAST(kmp_int64 *, task->shareds);
4160         retval = (kmp_int64)*lb;
4161       }
4162     }
4163 #else
4164     (void)taskdata;
4165     retval = *(kmp_int64 *)((char *)task + lower_offset);
4166 #endif // defined(KMP_GOMP_COMPAT)
4167     return retval;
4168   }
4169   kmp_uint64 get_ub() const {
4170     kmp_int64 retval;
4171 #if defined(KMP_GOMP_COMPAT)
4172     // Intel task just returns the upper bound normally
4173     if (!taskdata->td_flags.native) {
4174       retval = *(kmp_int64 *)((char *)task + upper_offset);
4175     } else {
4176       // GOMP task has to take into account the sizeof(long)
4177       if (taskdata->td_size_loop_bounds == 4) {
4178         kmp_int32 *ub = RCAST(kmp_int32 *, task->shareds) + 1;
4179         retval = (kmp_int64)*ub;
4180       } else {
4181         kmp_int64 *ub = RCAST(kmp_int64 *, task->shareds) + 1;
4182         retval = (kmp_int64)*ub;
4183       }
4184     }
4185 #else
4186     retval = *(kmp_int64 *)((char *)task + upper_offset);
4187 #endif // defined(KMP_GOMP_COMPAT)
4188     return retval;
4189   }
4190   void set_lb(kmp_uint64 lb) {
4191 #if defined(KMP_GOMP_COMPAT)
4192     // Intel task just sets the lower bound normally
4193     if (!taskdata->td_flags.native) {
4194       *(kmp_uint64 *)((char *)task + lower_offset) = lb;
4195     } else {
4196       // GOMP task has to take into account the sizeof(long)
4197       if (taskdata->td_size_loop_bounds == 4) {
4198         kmp_uint32 *lower = RCAST(kmp_uint32 *, task->shareds);
4199         *lower = (kmp_uint32)lb;
4200       } else {
4201         kmp_uint64 *lower = RCAST(kmp_uint64 *, task->shareds);
4202         *lower = (kmp_uint64)lb;
4203       }
4204     }
4205 #else
4206     *(kmp_uint64 *)((char *)task + lower_offset) = lb;
4207 #endif // defined(KMP_GOMP_COMPAT)
4208   }
4209   void set_ub(kmp_uint64 ub) {
4210 #if defined(KMP_GOMP_COMPAT)
4211     // Intel task just sets the upper bound normally
4212     if (!taskdata->td_flags.native) {
4213       *(kmp_uint64 *)((char *)task + upper_offset) = ub;
4214     } else {
4215       // GOMP task has to take into account the sizeof(long)
4216       if (taskdata->td_size_loop_bounds == 4) {
4217         kmp_uint32 *upper = RCAST(kmp_uint32 *, task->shareds) + 1;
4218         *upper = (kmp_uint32)ub;
4219       } else {
4220         kmp_uint64 *upper = RCAST(kmp_uint64 *, task->shareds) + 1;
4221         *upper = (kmp_uint64)ub;
4222       }
4223     }
4224 #else
4225     *(kmp_uint64 *)((char *)task + upper_offset) = ub;
4226 #endif // defined(KMP_GOMP_COMPAT)
4227   }
4228 };
4229 
4230 // __kmp_taskloop_linear: Start tasks of the taskloop linearly
4231 //
4232 // loc        Source location information
4233 // gtid       Global thread ID
4234 // task       Pattern task, exposes the loop iteration range
4235 // lb         Pointer to loop lower bound in task structure
4236 // ub         Pointer to loop upper bound in task structure
4237 // st         Loop stride
4238 // ub_glob    Global upper bound (used for lastprivate check)
4239 // num_tasks  Number of tasks to execute
4240 // grainsize  Number of loop iterations per task
4241 // extras     Number of chunks with grainsize+1 iterations
4242 // last_chunk Reduction of grainsize for last task
4243 // tc         Iterations count
4244 // task_dup   Tasks duplication routine
4245 // codeptr_ra Return address for OMPT events
4246 void __kmp_taskloop_linear(ident_t *loc, int gtid, kmp_task_t *task,
4247                            kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st,
4248                            kmp_uint64 ub_glob, kmp_uint64 num_tasks,
4249                            kmp_uint64 grainsize, kmp_uint64 extras,
4250                            kmp_int64 last_chunk, kmp_uint64 tc,
4251 #if OMPT_SUPPORT
4252                            void *codeptr_ra,
4253 #endif
4254                            void *task_dup) {
4255   KMP_COUNT_BLOCK(OMP_TASKLOOP);
4256   KMP_TIME_PARTITIONED_BLOCK(OMP_taskloop_scheduling);
4257   p_task_dup_t ptask_dup = (p_task_dup_t)task_dup;
4258   // compiler provides global bounds here
4259   kmp_taskloop_bounds_t task_bounds(task, lb, ub);
4260   kmp_uint64 lower = task_bounds.get_lb();
4261   kmp_uint64 upper = task_bounds.get_ub();
4262   kmp_uint64 i;
4263   kmp_info_t *thread = __kmp_threads[gtid];
4264   kmp_taskdata_t *current_task = thread->th.th_current_task;
4265   kmp_task_t *next_task;
4266   kmp_int32 lastpriv = 0;
4267 
4268   KMP_DEBUG_ASSERT(tc == num_tasks * grainsize +
4269                              (last_chunk < 0 ? last_chunk : extras));
4270   KMP_DEBUG_ASSERT(num_tasks > extras);
4271   KMP_DEBUG_ASSERT(num_tasks > 0);
4272   KA_TRACE(20, ("__kmp_taskloop_linear: T#%d: %lld tasks, grainsize %lld, "
4273                 "extras %lld, last_chunk %lld, i=%lld,%lld(%d)%lld, dup %p\n",
4274                 gtid, num_tasks, grainsize, extras, last_chunk, lower, upper,
4275                 ub_glob, st, task_dup));
4276 
4277   // Launch num_tasks tasks, assign grainsize iterations each task
4278   for (i = 0; i < num_tasks; ++i) {
4279     kmp_uint64 chunk_minus_1;
4280     if (extras == 0) {
4281       chunk_minus_1 = grainsize - 1;
4282     } else {
4283       chunk_minus_1 = grainsize;
4284       --extras; // first extras iterations get bigger chunk (grainsize+1)
4285     }
4286     upper = lower + st * chunk_minus_1;
4287     if (upper > *ub) {
4288       upper = *ub;
4289     }
4290     if (i == num_tasks - 1) {
4291       // schedule the last task, set lastprivate flag if needed
4292       if (st == 1) { // most common case
4293         KMP_DEBUG_ASSERT(upper == *ub);
4294         if (upper == ub_glob)
4295           lastpriv = 1;
4296       } else if (st > 0) { // positive loop stride
4297         KMP_DEBUG_ASSERT((kmp_uint64)st > *ub - upper);
4298         if ((kmp_uint64)st > ub_glob - upper)
4299           lastpriv = 1;
4300       } else { // negative loop stride
4301         KMP_DEBUG_ASSERT(upper + st < *ub);
4302         if (upper - ub_glob < (kmp_uint64)(-st))
4303           lastpriv = 1;
4304       }
4305     }
4306     next_task = __kmp_task_dup_alloc(thread, task); // allocate new task
4307     kmp_taskdata_t *next_taskdata = KMP_TASK_TO_TASKDATA(next_task);
4308     kmp_taskloop_bounds_t next_task_bounds =
4309         kmp_taskloop_bounds_t(next_task, task_bounds);
4310 
4311     // adjust task-specific bounds
4312     next_task_bounds.set_lb(lower);
4313     if (next_taskdata->td_flags.native) {
4314       next_task_bounds.set_ub(upper + (st > 0 ? 1 : -1));
4315     } else {
4316       next_task_bounds.set_ub(upper);
4317     }
4318     if (ptask_dup != NULL) // set lastprivate flag, construct firstprivates,
4319                            // etc.
4320       ptask_dup(next_task, task, lastpriv);
4321     KA_TRACE(40,
4322              ("__kmp_taskloop_linear: T#%d; task #%llu: task %p: lower %lld, "
4323               "upper %lld stride %lld, (offsets %p %p)\n",
4324               gtid, i, next_task, lower, upper, st,
4325               next_task_bounds.get_lower_offset(),
4326               next_task_bounds.get_upper_offset()));
4327 #if OMPT_SUPPORT
4328     __kmp_omp_taskloop_task(NULL, gtid, next_task,
4329                             codeptr_ra); // schedule new task
4330 #else
4331     __kmp_omp_task(gtid, next_task, true); // schedule new task
4332 #endif
4333     lower = upper + st; // adjust lower bound for the next iteration
4334   }
4335   // free the pattern task and exit
4336   __kmp_task_start(gtid, task, current_task); // make internal bookkeeping
4337   // do not execute the pattern task, just do internal bookkeeping
4338   __kmp_task_finish<false>(gtid, task, current_task);
4339 }
4340 
4341 // Structure to keep taskloop parameters for auxiliary task
4342 // kept in the shareds of the task structure.
4343 typedef struct __taskloop_params {
4344   kmp_task_t *task;
4345   kmp_uint64 *lb;
4346   kmp_uint64 *ub;
4347   void *task_dup;
4348   kmp_int64 st;
4349   kmp_uint64 ub_glob;
4350   kmp_uint64 num_tasks;
4351   kmp_uint64 grainsize;
4352   kmp_uint64 extras;
4353   kmp_int64 last_chunk;
4354   kmp_uint64 tc;
4355   kmp_uint64 num_t_min;
4356 #if OMPT_SUPPORT
4357   void *codeptr_ra;
4358 #endif
4359 } __taskloop_params_t;
4360 
4361 void __kmp_taskloop_recur(ident_t *, int, kmp_task_t *, kmp_uint64 *,
4362                           kmp_uint64 *, kmp_int64, kmp_uint64, kmp_uint64,
4363                           kmp_uint64, kmp_uint64, kmp_int64, kmp_uint64,
4364                           kmp_uint64,
4365 #if OMPT_SUPPORT
4366                           void *,
4367 #endif
4368                           void *);
4369 
4370 // Execute part of the taskloop submitted as a task.
4371 int __kmp_taskloop_task(int gtid, void *ptask) {
4372   __taskloop_params_t *p =
4373       (__taskloop_params_t *)((kmp_task_t *)ptask)->shareds;
4374   kmp_task_t *task = p->task;
4375   kmp_uint64 *lb = p->lb;
4376   kmp_uint64 *ub = p->ub;
4377   void *task_dup = p->task_dup;
4378   //  p_task_dup_t ptask_dup = (p_task_dup_t)task_dup;
4379   kmp_int64 st = p->st;
4380   kmp_uint64 ub_glob = p->ub_glob;
4381   kmp_uint64 num_tasks = p->num_tasks;
4382   kmp_uint64 grainsize = p->grainsize;
4383   kmp_uint64 extras = p->extras;
4384   kmp_int64 last_chunk = p->last_chunk;
4385   kmp_uint64 tc = p->tc;
4386   kmp_uint64 num_t_min = p->num_t_min;
4387 #if OMPT_SUPPORT
4388   void *codeptr_ra = p->codeptr_ra;
4389 #endif
4390 #if KMP_DEBUG
4391   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(task);
4392   KMP_DEBUG_ASSERT(task != NULL);
4393   KA_TRACE(20,
4394            ("__kmp_taskloop_task: T#%d, task %p: %lld tasks, grainsize"
4395             " %lld, extras %lld, last_chunk %lld, i=%lld,%lld(%d), dup %p\n",
4396             gtid, taskdata, num_tasks, grainsize, extras, last_chunk, *lb, *ub,
4397             st, task_dup));
4398 #endif
4399   KMP_DEBUG_ASSERT(num_tasks * 2 + 1 > num_t_min);
4400   if (num_tasks > num_t_min)
4401     __kmp_taskloop_recur(NULL, gtid, task, lb, ub, st, ub_glob, num_tasks,
4402                          grainsize, extras, last_chunk, tc, num_t_min,
4403 #if OMPT_SUPPORT
4404                          codeptr_ra,
4405 #endif
4406                          task_dup);
4407   else
4408     __kmp_taskloop_linear(NULL, gtid, task, lb, ub, st, ub_glob, num_tasks,
4409                           grainsize, extras, last_chunk, tc,
4410 #if OMPT_SUPPORT
4411                           codeptr_ra,
4412 #endif
4413                           task_dup);
4414 
4415   KA_TRACE(40, ("__kmp_taskloop_task(exit): T#%d\n", gtid));
4416   return 0;
4417 }
4418 
4419 // Schedule part of the taskloop as a task,
4420 // execute the rest of the taskloop.
4421 //
4422 // loc        Source location information
4423 // gtid       Global thread ID
4424 // task       Pattern task, exposes the loop iteration range
4425 // lb         Pointer to loop lower bound in task structure
4426 // ub         Pointer to loop upper bound in task structure
4427 // st         Loop stride
4428 // ub_glob    Global upper bound (used for lastprivate check)
4429 // num_tasks  Number of tasks to execute
4430 // grainsize  Number of loop iterations per task
4431 // extras     Number of chunks with grainsize+1 iterations
4432 // last_chunk Reduction of grainsize for last task
4433 // tc         Iterations count
4434 // num_t_min  Threshold to launch tasks recursively
4435 // task_dup   Tasks duplication routine
4436 // codeptr_ra Return address for OMPT events
4437 void __kmp_taskloop_recur(ident_t *loc, int gtid, kmp_task_t *task,
4438                           kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st,
4439                           kmp_uint64 ub_glob, kmp_uint64 num_tasks,
4440                           kmp_uint64 grainsize, kmp_uint64 extras,
4441                           kmp_int64 last_chunk, kmp_uint64 tc,
4442                           kmp_uint64 num_t_min,
4443 #if OMPT_SUPPORT
4444                           void *codeptr_ra,
4445 #endif
4446                           void *task_dup) {
4447   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(task);
4448   KMP_DEBUG_ASSERT(task != NULL);
4449   KMP_DEBUG_ASSERT(num_tasks > num_t_min);
4450   KA_TRACE(20,
4451            ("__kmp_taskloop_recur: T#%d, task %p: %lld tasks, grainsize"
4452             " %lld, extras %lld, last_chunk %lld, i=%lld,%lld(%d), dup %p\n",
4453             gtid, taskdata, num_tasks, grainsize, extras, last_chunk, *lb, *ub,
4454             st, task_dup));
4455   p_task_dup_t ptask_dup = (p_task_dup_t)task_dup;
4456   kmp_uint64 lower = *lb;
4457   kmp_info_t *thread = __kmp_threads[gtid];
4458   //  kmp_taskdata_t *current_task = thread->th.th_current_task;
4459   kmp_task_t *next_task;
4460   size_t lower_offset =
4461       (char *)lb - (char *)task; // remember offset of lb in the task structure
4462   size_t upper_offset =
4463       (char *)ub - (char *)task; // remember offset of ub in the task structure
4464 
4465   KMP_DEBUG_ASSERT(tc == num_tasks * grainsize +
4466                              (last_chunk < 0 ? last_chunk : extras));
4467   KMP_DEBUG_ASSERT(num_tasks > extras);
4468   KMP_DEBUG_ASSERT(num_tasks > 0);
4469 
4470   // split the loop in two halves
4471   kmp_uint64 lb1, ub0, tc0, tc1, ext0, ext1;
4472   kmp_int64 last_chunk0 = 0, last_chunk1 = 0;
4473   kmp_uint64 gr_size0 = grainsize;
4474   kmp_uint64 n_tsk0 = num_tasks >> 1; // num_tasks/2 to execute
4475   kmp_uint64 n_tsk1 = num_tasks - n_tsk0; // to schedule as a task
4476   if (last_chunk < 0) {
4477     ext0 = ext1 = 0;
4478     last_chunk1 = last_chunk;
4479     tc0 = grainsize * n_tsk0;
4480     tc1 = tc - tc0;
4481   } else if (n_tsk0 <= extras) {
4482     gr_size0++; // integrate extras into grainsize
4483     ext0 = 0; // no extra iters in 1st half
4484     ext1 = extras - n_tsk0; // remaining extras
4485     tc0 = gr_size0 * n_tsk0;
4486     tc1 = tc - tc0;
4487   } else { // n_tsk0 > extras
4488     ext1 = 0; // no extra iters in 2nd half
4489     ext0 = extras;
4490     tc1 = grainsize * n_tsk1;
4491     tc0 = tc - tc1;
4492   }
4493   ub0 = lower + st * (tc0 - 1);
4494   lb1 = ub0 + st;
4495 
4496   // create pattern task for 2nd half of the loop
4497   next_task = __kmp_task_dup_alloc(thread, task); // duplicate the task
4498   // adjust lower bound (upper bound is not changed) for the 2nd half
4499   *(kmp_uint64 *)((char *)next_task + lower_offset) = lb1;
4500   if (ptask_dup != NULL) // construct firstprivates, etc.
4501     ptask_dup(next_task, task, 0);
4502   *ub = ub0; // adjust upper bound for the 1st half
4503 
4504   // create auxiliary task for 2nd half of the loop
4505   // make sure new task has same parent task as the pattern task
4506   kmp_taskdata_t *current_task = thread->th.th_current_task;
4507   thread->th.th_current_task = taskdata->td_parent;
4508   kmp_task_t *new_task =
4509       __kmpc_omp_task_alloc(loc, gtid, 1, 3 * sizeof(void *),
4510                             sizeof(__taskloop_params_t), &__kmp_taskloop_task);
4511   // restore current task
4512   thread->th.th_current_task = current_task;
4513   __taskloop_params_t *p = (__taskloop_params_t *)new_task->shareds;
4514   p->task = next_task;
4515   p->lb = (kmp_uint64 *)((char *)next_task + lower_offset);
4516   p->ub = (kmp_uint64 *)((char *)next_task + upper_offset);
4517   p->task_dup = task_dup;
4518   p->st = st;
4519   p->ub_glob = ub_glob;
4520   p->num_tasks = n_tsk1;
4521   p->grainsize = grainsize;
4522   p->extras = ext1;
4523   p->last_chunk = last_chunk1;
4524   p->tc = tc1;
4525   p->num_t_min = num_t_min;
4526 #if OMPT_SUPPORT
4527   p->codeptr_ra = codeptr_ra;
4528 #endif
4529 
4530 #if OMPT_SUPPORT
4531   // schedule new task with correct return address for OMPT events
4532   __kmp_omp_taskloop_task(NULL, gtid, new_task, codeptr_ra);
4533 #else
4534   __kmp_omp_task(gtid, new_task, true); // schedule new task
4535 #endif
4536 
4537   // execute the 1st half of current subrange
4538   if (n_tsk0 > num_t_min)
4539     __kmp_taskloop_recur(loc, gtid, task, lb, ub, st, ub_glob, n_tsk0, gr_size0,
4540                          ext0, last_chunk0, tc0, num_t_min,
4541 #if OMPT_SUPPORT
4542                          codeptr_ra,
4543 #endif
4544                          task_dup);
4545   else
4546     __kmp_taskloop_linear(loc, gtid, task, lb, ub, st, ub_glob, n_tsk0,
4547                           gr_size0, ext0, last_chunk0, tc0,
4548 #if OMPT_SUPPORT
4549                           codeptr_ra,
4550 #endif
4551                           task_dup);
4552 
4553   KA_TRACE(40, ("__kmp_taskloop_recur(exit): T#%d\n", gtid));
4554 }
4555 
4556 static void __kmp_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int if_val,
4557                            kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st,
4558                            int nogroup, int sched, kmp_uint64 grainsize,
4559                            int modifier, void *task_dup) {
4560   kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(task);
4561   KMP_DEBUG_ASSERT(task != NULL);
4562   if (nogroup == 0) {
4563 #if OMPT_SUPPORT && OMPT_OPTIONAL
4564     OMPT_STORE_RETURN_ADDRESS(gtid);
4565 #endif
4566     __kmpc_taskgroup(loc, gtid);
4567   }
4568 
4569   // =========================================================================
4570   // calculate loop parameters
4571   kmp_taskloop_bounds_t task_bounds(task, lb, ub);
4572   kmp_uint64 tc;
4573   // compiler provides global bounds here
4574   kmp_uint64 lower = task_bounds.get_lb();
4575   kmp_uint64 upper = task_bounds.get_ub();
4576   kmp_uint64 ub_glob = upper; // global upper used to calc lastprivate flag
4577   kmp_uint64 num_tasks = 0, extras = 0;
4578   kmp_int64 last_chunk =
4579       0; // reduce grainsize of last task by last_chunk in strict mode
4580   kmp_uint64 num_tasks_min = __kmp_taskloop_min_tasks;
4581   kmp_info_t *thread = __kmp_threads[gtid];
4582   kmp_taskdata_t *current_task = thread->th.th_current_task;
4583 
4584   KA_TRACE(20, ("__kmp_taskloop: T#%d, task %p, lb %lld, ub %lld, st %lld, "
4585                 "grain %llu(%d, %d), dup %p\n",
4586                 gtid, taskdata, lower, upper, st, grainsize, sched, modifier,
4587                 task_dup));
4588 
4589   // compute trip count
4590   if (st == 1) { // most common case
4591     tc = upper - lower + 1;
4592   } else if (st < 0) {
4593     tc = (lower - upper) / (-st) + 1;
4594   } else { // st > 0
4595     tc = (upper - lower) / st + 1;
4596   }
4597   if (tc == 0) {
4598     KA_TRACE(20, ("__kmp_taskloop(exit): T#%d zero-trip loop\n", gtid));
4599     // free the pattern task and exit
4600     __kmp_task_start(gtid, task, current_task);
4601     // do not execute anything for zero-trip loop
4602     __kmp_task_finish<false>(gtid, task, current_task);
4603     return;
4604   }
4605 
4606 #if OMPT_SUPPORT && OMPT_OPTIONAL
4607   ompt_team_info_t *team_info = __ompt_get_teaminfo(0, NULL);
4608   ompt_task_info_t *task_info = __ompt_get_task_info_object(0);
4609   if (ompt_enabled.ompt_callback_work) {
4610     ompt_callbacks.ompt_callback(ompt_callback_work)(
4611         ompt_work_taskloop, ompt_scope_begin, &(team_info->parallel_data),
4612         &(task_info->task_data), tc, OMPT_GET_RETURN_ADDRESS(0));
4613   }
4614 #endif
4615 
4616   if (num_tasks_min == 0)
4617     // TODO: can we choose better default heuristic?
4618     num_tasks_min =
4619         KMP_MIN(thread->th.th_team_nproc * 10, INITIAL_TASK_DEQUE_SIZE);
4620 
4621   // compute num_tasks/grainsize based on the input provided
4622   switch (sched) {
4623   case 0: // no schedule clause specified, we can choose the default
4624     // let's try to schedule (team_size*10) tasks
4625     grainsize = thread->th.th_team_nproc * 10;
4626     KMP_FALLTHROUGH();
4627   case 2: // num_tasks provided
4628     if (grainsize > tc) {
4629       num_tasks = tc; // too big num_tasks requested, adjust values
4630       grainsize = 1;
4631       extras = 0;
4632     } else {
4633       num_tasks = grainsize;
4634       grainsize = tc / num_tasks;
4635       extras = tc % num_tasks;
4636     }
4637     break;
4638   case 1: // grainsize provided
4639     if (grainsize > tc) {
4640       num_tasks = 1;
4641       grainsize = tc; // too big grainsize requested, adjust values
4642       extras = 0;
4643     } else {
4644       if (modifier) {
4645         num_tasks = (tc + grainsize - 1) / grainsize;
4646         last_chunk = tc - (num_tasks * grainsize);
4647         extras = 0;
4648       } else {
4649         num_tasks = tc / grainsize;
4650         // adjust grainsize for balanced distribution of iterations
4651         grainsize = tc / num_tasks;
4652         extras = tc % num_tasks;
4653       }
4654     }
4655     break;
4656   default:
4657     KMP_ASSERT2(0, "unknown scheduling of taskloop");
4658   }
4659 
4660   KMP_DEBUG_ASSERT(tc == num_tasks * grainsize +
4661                              (last_chunk < 0 ? last_chunk : extras));
4662   KMP_DEBUG_ASSERT(num_tasks > extras);
4663   KMP_DEBUG_ASSERT(num_tasks > 0);
4664   // =========================================================================
4665 
4666   // check if clause value first
4667   // Also require GOMP_taskloop to reduce to linear (taskdata->td_flags.native)
4668   if (if_val == 0) { // if(0) specified, mark task as serial
4669     taskdata->td_flags.task_serial = 1;
4670     taskdata->td_flags.tiedness = TASK_TIED; // AC: serial task cannot be untied
4671     // always start serial tasks linearly
4672     __kmp_taskloop_linear(loc, gtid, task, lb, ub, st, ub_glob, num_tasks,
4673                           grainsize, extras, last_chunk, tc,
4674 #if OMPT_SUPPORT
4675                           OMPT_GET_RETURN_ADDRESS(0),
4676 #endif
4677                           task_dup);
4678     // !taskdata->td_flags.native => currently force linear spawning of tasks
4679     // for GOMP_taskloop
4680   } else if (num_tasks > num_tasks_min && !taskdata->td_flags.native) {
4681     KA_TRACE(20, ("__kmp_taskloop: T#%d, go recursive: tc %llu, #tasks %llu"
4682                   "(%lld), grain %llu, extras %llu, last_chunk %lld\n",
4683                   gtid, tc, num_tasks, num_tasks_min, grainsize, extras,
4684                   last_chunk));
4685     __kmp_taskloop_recur(loc, gtid, task, lb, ub, st, ub_glob, num_tasks,
4686                          grainsize, extras, last_chunk, tc, num_tasks_min,
4687 #if OMPT_SUPPORT
4688                          OMPT_GET_RETURN_ADDRESS(0),
4689 #endif
4690                          task_dup);
4691   } else {
4692     KA_TRACE(20, ("__kmp_taskloop: T#%d, go linear: tc %llu, #tasks %llu"
4693                   "(%lld), grain %llu, extras %llu, last_chunk %lld\n",
4694                   gtid, tc, num_tasks, num_tasks_min, grainsize, extras,
4695                   last_chunk));
4696     __kmp_taskloop_linear(loc, gtid, task, lb, ub, st, ub_glob, num_tasks,
4697                           grainsize, extras, last_chunk, tc,
4698 #if OMPT_SUPPORT
4699                           OMPT_GET_RETURN_ADDRESS(0),
4700 #endif
4701                           task_dup);
4702   }
4703 
4704 #if OMPT_SUPPORT && OMPT_OPTIONAL
4705   if (ompt_enabled.ompt_callback_work) {
4706     ompt_callbacks.ompt_callback(ompt_callback_work)(
4707         ompt_work_taskloop, ompt_scope_end, &(team_info->parallel_data),
4708         &(task_info->task_data), tc, OMPT_GET_RETURN_ADDRESS(0));
4709   }
4710 #endif
4711 
4712   if (nogroup == 0) {
4713 #if OMPT_SUPPORT && OMPT_OPTIONAL
4714     OMPT_STORE_RETURN_ADDRESS(gtid);
4715 #endif
4716     __kmpc_end_taskgroup(loc, gtid);
4717   }
4718   KA_TRACE(20, ("__kmp_taskloop(exit): T#%d\n", gtid));
4719 }
4720 
4721 /*!
4722 @ingroup TASKING
4723 @param loc       Source location information
4724 @param gtid      Global thread ID
4725 @param task      Task structure
4726 @param if_val    Value of the if clause
4727 @param lb        Pointer to loop lower bound in task structure
4728 @param ub        Pointer to loop upper bound in task structure
4729 @param st        Loop stride
4730 @param nogroup   Flag, 1 if nogroup clause specified, 0 otherwise
4731 @param sched     Schedule specified 0/1/2 for none/grainsize/num_tasks
4732 @param grainsize Schedule value if specified
4733 @param task_dup  Tasks duplication routine
4734 
4735 Execute the taskloop construct.
4736 */
4737 void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int if_val,
4738                      kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup,
4739                      int sched, kmp_uint64 grainsize, void *task_dup) {
4740   __kmp_assert_valid_gtid(gtid);
4741   KA_TRACE(20, ("__kmpc_taskloop(enter): T#%d\n", gtid));
4742   __kmp_taskloop(loc, gtid, task, if_val, lb, ub, st, nogroup, sched, grainsize,
4743                  0, task_dup);
4744   KA_TRACE(20, ("__kmpc_taskloop(exit): T#%d\n", gtid));
4745 }
4746 
4747 /*!
4748 @ingroup TASKING
4749 @param loc       Source location information
4750 @param gtid      Global thread ID
4751 @param task      Task structure
4752 @param if_val    Value of the if clause
4753 @param lb        Pointer to loop lower bound in task structure
4754 @param ub        Pointer to loop upper bound in task structure
4755 @param st        Loop stride
4756 @param nogroup   Flag, 1 if nogroup clause specified, 0 otherwise
4757 @param sched     Schedule specified 0/1/2 for none/grainsize/num_tasks
4758 @param grainsize Schedule value if specified
4759 @param modifer   Modifier 'strict' for sched, 1 if present, 0 otherwise
4760 @param task_dup  Tasks duplication routine
4761 
4762 Execute the taskloop construct.
4763 */
4764 void __kmpc_taskloop_5(ident_t *loc, int gtid, kmp_task_t *task, int if_val,
4765                        kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st,
4766                        int nogroup, int sched, kmp_uint64 grainsize,
4767                        int modifier, void *task_dup) {
4768   __kmp_assert_valid_gtid(gtid);
4769   KA_TRACE(20, ("__kmpc_taskloop_5(enter): T#%d\n", gtid));
4770   __kmp_taskloop(loc, gtid, task, if_val, lb, ub, st, nogroup, sched, grainsize,
4771                  modifier, task_dup);
4772   KA_TRACE(20, ("__kmpc_taskloop_5(exit): T#%d\n", gtid));
4773 }
4774