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