1 //===---- Parallelism.cpp - OpenMP GPU parallel implementation ---- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Parallel implementation in the GPU. Here is the pattern:
10 //
11 //    while (not finished) {
12 //
13 //    if (master) {
14 //      sequential code, decide which par loop to do, or if finished
15 //     __kmpc_kernel_prepare_parallel() // exec by master only
16 //    }
17 //    syncthreads // A
18 //    __kmpc_kernel_parallel() // exec by all
19 //    if (this thread is included in the parallel) {
20 //      switch () for all parallel loops
21 //      __kmpc_kernel_end_parallel() // exec only by threads in parallel
22 //    }
23 //
24 //
25 //    The reason we don't exec end_parallel for the threads not included
26 //    in the parallel loop is that for each barrier in the parallel
27 //    region, these non-included threads will cycle through the
28 //    syncthread A. Thus they must preserve their current threadId that
29 //    is larger than thread in team.
30 //
31 //    To make a long story short...
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "Debug.h"
36 #include "Interface.h"
37 #include "Mapping.h"
38 #include "State.h"
39 #include "Synchronization.h"
40 #include "Types.h"
41 #include "Utils.h"
42 
43 using namespace _OMP;
44 
45 #pragma omp begin declare target device_type(nohost)
46 
47 namespace {
48 
49 uint32_t determineNumberOfThreads(int32_t NumThreadsClause) {
50   uint32_t NThreadsICV =
51       NumThreadsClause != -1 ? NumThreadsClause : icv::NThreads;
52   uint32_t NumThreads = mapping::getBlockSize();
53 
54   if (NThreadsICV != 0 && NThreadsICV < NumThreads)
55     NumThreads = NThreadsICV;
56 
57   // Round down to a multiple of WARPSIZE since it is legal to do so in OpenMP.
58   if (NumThreads < mapping::getWarpSize())
59     NumThreads = 1;
60   else
61     NumThreads = (NumThreads & ~((uint32_t)mapping::getWarpSize() - 1));
62 
63   return NumThreads;
64 }
65 
66 // Invoke an outlined parallel function unwrapping arguments (up to 32).
67 void invokeMicrotask(int32_t global_tid, int32_t bound_tid, void *fn,
68                      void **args, int64_t nargs) {
69   DebugEntryRAII Entry(__FILE__, __LINE__, "<OpenMP Outlined Function>");
70   switch (nargs) {
71 #include "generated_microtask_cases.gen"
72   default:
73     PRINT("Too many arguments in kmp_invoke_microtask, aborting execution.\n");
74     __builtin_trap();
75   }
76 }
77 
78 } // namespace
79 
80 extern "C" {
81 
82 void __kmpc_parallel_51(IdentTy *ident, int32_t, int32_t if_expr,
83                         int32_t num_threads, int proc_bind, void *fn,
84                         void *wrapper_fn, void **args, int64_t nargs) {
85   FunctionTracingRAII();
86 
87   uint32_t TId = mapping::getThreadIdInBlock();
88   // Handle the serialized case first, same for SPMD/non-SPMD.
89   if (OMP_UNLIKELY(!if_expr || icv::Level)) {
90     state::DateEnvironmentRAII DERAII(ident);
91     ++icv::Level;
92     invokeMicrotask(TId, 0, fn, args, nargs);
93     return;
94   }
95 
96   uint32_t NumThreads = determineNumberOfThreads(num_threads);
97   if (mapping::isSPMDMode()) {
98     // Avoid the race between the read of the `icv::Level` above and the write
99     // below by synchronizing all threads here.
100     synchronize::threadsAligned();
101     {
102       // Note that the order here is important. `icv::Level` has to be updated
103       // last or the other updates will cause a thread specific state to be
104       // created.
105       state::ValueRAII ParallelTeamSizeRAII(state::ParallelTeamSize, NumThreads,
106                                             1u, TId == 0, ident);
107       state::ValueRAII ActiveLevelRAII(icv::ActiveLevel, 1u, 0u, TId == 0,
108                                        ident);
109       state::ValueRAII LevelRAII(icv::Level, 1u, 0u, TId == 0, ident);
110 
111       // Synchronize all threads after the main thread (TId == 0) set up the
112       // team state properly.
113       synchronize::threadsAligned();
114 
115       ASSERT(state::ParallelTeamSize == NumThreads);
116       ASSERT(icv::ActiveLevel == 1u);
117       ASSERT(icv::Level == 1u);
118 
119       if (TId < NumThreads)
120         invokeMicrotask(TId, 0, fn, args, nargs);
121 
122       // Synchronize all threads at the end of a parallel region.
123       synchronize::threadsAligned();
124     }
125 
126     // Synchronize all threads to make sure every thread exits the scope above;
127     // otherwise the following assertions and the assumption in
128     // __kmpc_target_deinit may not hold.
129     synchronize::threadsAligned();
130 
131     ASSERT(state::ParallelTeamSize == 1u);
132     ASSERT(icv::ActiveLevel == 0u);
133     ASSERT(icv::Level == 0u);
134     return;
135   }
136 
137   // We do *not* create a new data environment because all threads in the team
138   // that are active are now running this parallel region. They share the
139   // TeamState, which has an increase level-var and potentially active-level
140   // set, but they do not have individual ThreadStates yet. If they ever
141   // modify the ICVs beyond this point a ThreadStates will be allocated.
142 
143   bool IsActiveParallelRegion = NumThreads > 1;
144   if (!IsActiveParallelRegion) {
145     state::ValueRAII LevelRAII(icv::Level, 1u, 0u, true, ident);
146     invokeMicrotask(TId, 0, fn, args, nargs);
147     return;
148   }
149 
150   void **GlobalArgs = nullptr;
151   if (nargs) {
152     __kmpc_begin_sharing_variables(&GlobalArgs, nargs);
153     switch (nargs) {
154     default:
155       for (int I = 0; I < nargs; I++)
156         GlobalArgs[I] = args[I];
157       break;
158     case 16:
159       GlobalArgs[15] = args[15];
160       [[fallthrough]];
161     case 15:
162       GlobalArgs[14] = args[14];
163       [[fallthrough]];
164     case 14:
165       GlobalArgs[13] = args[13];
166       [[fallthrough]];
167     case 13:
168       GlobalArgs[12] = args[12];
169       [[fallthrough]];
170     case 12:
171       GlobalArgs[11] = args[11];
172       [[fallthrough]];
173     case 11:
174       GlobalArgs[10] = args[10];
175       [[fallthrough]];
176     case 10:
177       GlobalArgs[9] = args[9];
178       [[fallthrough]];
179     case 9:
180       GlobalArgs[8] = args[8];
181       [[fallthrough]];
182     case 8:
183       GlobalArgs[7] = args[7];
184       [[fallthrough]];
185     case 7:
186       GlobalArgs[6] = args[6];
187       [[fallthrough]];
188     case 6:
189       GlobalArgs[5] = args[5];
190       [[fallthrough]];
191     case 5:
192       GlobalArgs[4] = args[4];
193       [[fallthrough]];
194     case 4:
195       GlobalArgs[3] = args[3];
196       [[fallthrough]];
197     case 3:
198       GlobalArgs[2] = args[2];
199       [[fallthrough]];
200     case 2:
201       GlobalArgs[1] = args[1];
202       [[fallthrough]];
203     case 1:
204       GlobalArgs[0] = args[0];
205       [[fallthrough]];
206     case 0:
207       break;
208     }
209   }
210 
211   {
212     // Note that the order here is important. `icv::Level` has to be updated
213     // last or the other updates will cause a thread specific state to be
214     // created.
215     state::ValueRAII ParallelTeamSizeRAII(state::ParallelTeamSize, NumThreads,
216                                           1u, true, ident);
217     state::ValueRAII ParallelRegionFnRAII(state::ParallelRegionFn, wrapper_fn,
218                                           (void *)nullptr, true, ident);
219     state::ValueRAII ActiveLevelRAII(icv::ActiveLevel, 1u, 0u, true, ident);
220     state::ValueRAII LevelRAII(icv::Level, 1u, 0u, true, ident);
221 
222     // Master signals work to activate workers.
223     synchronize::threads();
224     // Master waits for workers to signal.
225     synchronize::threads();
226   }
227 
228   if (nargs)
229     __kmpc_end_sharing_variables();
230 }
231 
232 __attribute__((noinline)) bool
233 __kmpc_kernel_parallel(ParallelRegionFnTy *WorkFn) {
234   FunctionTracingRAII();
235   // Work function and arguments for L1 parallel region.
236   *WorkFn = state::ParallelRegionFn;
237 
238   // If this is the termination signal from the master, quit early.
239   if (!*WorkFn)
240     return false;
241 
242   // Set to true for workers participating in the parallel region.
243   uint32_t TId = mapping::getThreadIdInBlock();
244   bool ThreadIsActive = TId < state::ParallelTeamSize;
245   return ThreadIsActive;
246 }
247 
248 __attribute__((noinline)) void __kmpc_kernel_end_parallel() {
249   FunctionTracingRAII();
250   // In case we have modified an ICV for this thread before a ThreadState was
251   // created. We drop it now to not contaminate the next parallel region.
252   ASSERT(!mapping::isSPMDMode());
253   uint32_t TId = mapping::getThreadIdInBlock();
254   state::resetStateForThread(TId);
255   ASSERT(!mapping::isSPMDMode());
256 }
257 
258 uint16_t __kmpc_parallel_level(IdentTy *, uint32_t) {
259   FunctionTracingRAII();
260   return omp_get_level();
261 }
262 
263 int32_t __kmpc_global_thread_num(IdentTy *) {
264   FunctionTracingRAII();
265   return omp_get_thread_num();
266 }
267 
268 void __kmpc_push_num_teams(IdentTy *loc, int32_t tid, int32_t num_teams,
269                            int32_t thread_limit) {
270   FunctionTracingRAII();
271 }
272 
273 void __kmpc_push_proc_bind(IdentTy *loc, uint32_t tid, int proc_bind) {
274   FunctionTracingRAII();
275 }
276 }
277 
278 #pragma omp end declare target
279