13de4cd12SGeorge Rokos //===----RTLs/cuda/src/rtl.cpp - Target RTLs Implementation ------- C++ -*-===//
23de4cd12SGeorge Rokos //
357b08b09SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
457b08b09SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
557b08b09SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
63de4cd12SGeorge Rokos //
73de4cd12SGeorge Rokos //===----------------------------------------------------------------------===//
83de4cd12SGeorge Rokos //
93de4cd12SGeorge Rokos // RTL for CUDA machine
103de4cd12SGeorge Rokos //
113de4cd12SGeorge Rokos //===----------------------------------------------------------------------===//
123de4cd12SGeorge Rokos 
133de4cd12SGeorge Rokos #include <cassert>
143de4cd12SGeorge Rokos #include <cstddef>
153de4cd12SGeorge Rokos #include <cuda.h>
163de4cd12SGeorge Rokos #include <list>
17a5153dbcSJohannes Doerfert #include <memory>
18feed674dSShilei Tian #include <mutex>
193de4cd12SGeorge Rokos #include <string>
203de4cd12SGeorge Rokos #include <vector>
213de4cd12SGeorge Rokos 
221546d319SGeorge Rokos #include "omptargetplugin.h"
233de4cd12SGeorge Rokos 
243de4cd12SGeorge Rokos #ifndef TARGET_NAME
253de4cd12SGeorge Rokos #define TARGET_NAME CUDA
263de4cd12SGeorge Rokos #endif
273de4cd12SGeorge Rokos 
28b305d26bSSergey Dmitriev #ifdef OMPTARGET_DEBUG
29b305d26bSSergey Dmitriev static int DebugLevel = 0;
30b305d26bSSergey Dmitriev 
313de4cd12SGeorge Rokos #define GETNAME2(name) #name
323de4cd12SGeorge Rokos #define GETNAME(name) GETNAME2(name)
33b305d26bSSergey Dmitriev #define DP(...) \
34b305d26bSSergey Dmitriev   do { \
35b305d26bSSergey Dmitriev     if (DebugLevel > 0) { \
36b305d26bSSergey Dmitriev       DEBUGP("Target " GETNAME(TARGET_NAME) " RTL", __VA_ARGS__); \
37b305d26bSSergey Dmitriev     } \
38b305d26bSSergey Dmitriev   } while (false)
3978769ec4SMichael Kruse 
4078769ec4SMichael Kruse // Utility for retrieving and printing CUDA error string.
4178769ec4SMichael Kruse #define CUDA_ERR_STRING(err) \
4278769ec4SMichael Kruse   do { \
4378769ec4SMichael Kruse     if (DebugLevel > 0) { \
4478769ec4SMichael Kruse       const char *errStr; \
4578769ec4SMichael Kruse       cuGetErrorString(err, &errStr); \
4678769ec4SMichael Kruse       DEBUGP("Target " GETNAME(TARGET_NAME) " RTL", "CUDA error is: %s\n", errStr); \
4778769ec4SMichael Kruse     } \
4878769ec4SMichael Kruse   } while (false)
49b305d26bSSergey Dmitriev #else // OMPTARGET_DEBUG
50b305d26bSSergey Dmitriev #define DP(...) {}
5178769ec4SMichael Kruse #define CUDA_ERR_STRING(err) {}
52b305d26bSSergey Dmitriev #endif // OMPTARGET_DEBUG
533de4cd12SGeorge Rokos 
543de4cd12SGeorge Rokos #include "../../common/elf_common.c"
553de4cd12SGeorge Rokos 
563de4cd12SGeorge Rokos /// Keep entries table per device.
573de4cd12SGeorge Rokos struct FuncOrGblEntryTy {
583de4cd12SGeorge Rokos   __tgt_target_table Table;
593de4cd12SGeorge Rokos   std::vector<__tgt_offload_entry> Entries;
603de4cd12SGeorge Rokos };
613de4cd12SGeorge Rokos 
623de4cd12SGeorge Rokos enum ExecutionModeType {
63c13df8e5SGeorge Rokos   SPMD, // constructors, destructors,
64c13df8e5SGeorge Rokos   // combined constructs (`teams distribute parallel for [simd]`)
65c13df8e5SGeorge Rokos   GENERIC, // everything else
663de4cd12SGeorge Rokos   NONE
673de4cd12SGeorge Rokos };
683de4cd12SGeorge Rokos 
69dc34b1c9SRon Lieberman /// Use a single entity to encode a kernel and a set of flags.
703de4cd12SGeorge Rokos struct KernelTy {
713de4cd12SGeorge Rokos   CUfunction Func;
723de4cd12SGeorge Rokos 
733de4cd12SGeorge Rokos   // execution mode of kernel
743de4cd12SGeorge Rokos   // 0 - SPMD mode (without master warp)
753de4cd12SGeorge Rokos   // 1 - Generic mode (with master warp)
763de4cd12SGeorge Rokos   int8_t ExecutionMode;
773de4cd12SGeorge Rokos 
783de4cd12SGeorge Rokos   KernelTy(CUfunction _Func, int8_t _ExecutionMode)
793de4cd12SGeorge Rokos       : Func(_Func), ExecutionMode(_ExecutionMode) {}
803de4cd12SGeorge Rokos };
813de4cd12SGeorge Rokos 
824c6a098aSKazuaki Ishizaki /// Device environment data
83feed674dSShilei Tian /// Manually sync with the deviceRTL side for now, move to a dedicated header
84feed674dSShilei Tian /// file later.
85e1c7a46dSGuansong Zhang struct omptarget_device_environmentTy {
86e1c7a46dSGuansong Zhang   int32_t debug_level;
87e1c7a46dSGuansong Zhang };
88e1c7a46dSGuansong Zhang 
893de4cd12SGeorge Rokos /// List that contains all the kernels.
903de4cd12SGeorge Rokos /// FIXME: we may need this to be per device and per library.
913de4cd12SGeorge Rokos std::list<KernelTy> KernelsList;
923de4cd12SGeorge Rokos 
93feed674dSShilei Tian namespace {
94feed674dSShilei Tian bool checkResult(CUresult Err, const char *ErrMsg) {
95feed674dSShilei Tian   if (Err == CUDA_SUCCESS)
96feed674dSShilei Tian     return true;
97feed674dSShilei Tian 
98feed674dSShilei Tian   DP(ErrMsg);
99feed674dSShilei Tian   CUDA_ERR_STRING(Err);
100feed674dSShilei Tian   return false;
101feed674dSShilei Tian }
102*4031bb98SShilei Tian 
103*4031bb98SShilei Tian // Structure contains per-device data
104*4031bb98SShilei Tian struct DeviceDataTy {
105*4031bb98SShilei Tian   std::list<FuncOrGblEntryTy> FuncGblEntries;
106*4031bb98SShilei Tian   CUcontext Context = nullptr;
107*4031bb98SShilei Tian   // Device properties
108*4031bb98SShilei Tian   int ThreadsPerBlock = 0;
109*4031bb98SShilei Tian   int BlocksPerGrid = 0;
110*4031bb98SShilei Tian   int WarpSize = 0;
111*4031bb98SShilei Tian   // OpenMP properties
112*4031bb98SShilei Tian   int NumTeams = 0;
113*4031bb98SShilei Tian   int NumThreads = 0;
114*4031bb98SShilei Tian };
115feed674dSShilei Tian 
116feed674dSShilei Tian class StreamManagerTy {
117feed674dSShilei Tian   int NumberOfDevices;
118*4031bb98SShilei Tian   // The initial size of stream pool
119*4031bb98SShilei Tian   int EnvNumInitialStreams;
120feed674dSShilei Tian   // Per-device stream mutex
121feed674dSShilei Tian   std::vector<std::unique_ptr<std::mutex>> StreamMtx;
122feed674dSShilei Tian   // Per-device stream Id indicates the next available stream in the pool
123feed674dSShilei Tian   std::vector<int> NextStreamId;
124feed674dSShilei Tian   // Per-device stream pool
125feed674dSShilei Tian   std::vector<std::vector<CUstream>> StreamPool;
126*4031bb98SShilei Tian   // Reference to per-device data
127*4031bb98SShilei Tian   std::vector<DeviceDataTy> &DeviceData;
128feed674dSShilei Tian 
129feed674dSShilei Tian   // If there is no CUstream left in the pool, we will resize the pool to
130feed674dSShilei Tian   // allocate more CUstream. This function should be called with device mutex,
131feed674dSShilei Tian   // and we do not resize to smaller one.
132feed674dSShilei Tian   void resizeStreamPool(const int DeviceId, const size_t NewSize) {
133feed674dSShilei Tian     std::vector<CUstream> &Pool = StreamPool[DeviceId];
134feed674dSShilei Tian     const size_t CurrentSize = Pool.size();
135feed674dSShilei Tian     assert(NewSize > CurrentSize && "new size is not larger than current size");
136feed674dSShilei Tian 
137*4031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
138*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) {
139feed674dSShilei Tian       // We will return if cannot switch to the right context in case of
140feed674dSShilei Tian       // creating bunch of streams that are not corresponding to the right
141feed674dSShilei Tian       // device. The offloading will fail later because selected CUstream is
142feed674dSShilei Tian       // nullptr.
143feed674dSShilei Tian       return;
144feed674dSShilei Tian     }
145feed674dSShilei Tian 
146*4031bb98SShilei Tian     Pool.resize(NewSize, nullptr);
147*4031bb98SShilei Tian 
148feed674dSShilei Tian     for (size_t I = CurrentSize; I < NewSize; ++I) {
149*4031bb98SShilei Tian       checkResult(cuStreamCreate(&Pool[I], CU_STREAM_NON_BLOCKING),
150*4031bb98SShilei Tian                   "Error returned from cuStreamCreate\n");
151feed674dSShilei Tian     }
152feed674dSShilei Tian   }
153feed674dSShilei Tian 
154feed674dSShilei Tian public:
155*4031bb98SShilei Tian   StreamManagerTy(const int NumberOfDevices,
156*4031bb98SShilei Tian                   std::vector<DeviceDataTy> &DeviceData)
157*4031bb98SShilei Tian       : NumberOfDevices(NumberOfDevices), EnvNumInitialStreams(32),
158*4031bb98SShilei Tian         DeviceData(DeviceData) {
159feed674dSShilei Tian     StreamPool.resize(NumberOfDevices);
160feed674dSShilei Tian     NextStreamId.resize(NumberOfDevices);
161feed674dSShilei Tian     StreamMtx.resize(NumberOfDevices);
162feed674dSShilei Tian 
163*4031bb98SShilei Tian     if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS"))
164*4031bb98SShilei Tian       EnvNumInitialStreams = std::stoi(EnvStr);
165feed674dSShilei Tian 
166feed674dSShilei Tian     // Initialize the next stream id
167feed674dSShilei Tian     std::fill(NextStreamId.begin(), NextStreamId.end(), 0);
168feed674dSShilei Tian 
169feed674dSShilei Tian     // Initialize stream mutex
170feed674dSShilei Tian     for (std::unique_ptr<std::mutex> &Ptr : StreamMtx)
171feed674dSShilei Tian       Ptr = std::make_unique<std::mutex>();
172feed674dSShilei Tian   }
173feed674dSShilei Tian 
174feed674dSShilei Tian   ~StreamManagerTy() {
175feed674dSShilei Tian     // Destroy streams
176feed674dSShilei Tian     for (int I = 0; I < NumberOfDevices; ++I) {
177*4031bb98SShilei Tian       checkResult(cuCtxSetCurrent(DeviceData[I].Context),
178*4031bb98SShilei Tian                   "Error returned from cuCtxSetCurrent\n");
179feed674dSShilei Tian 
180feed674dSShilei Tian       for (CUstream &S : StreamPool[I]) {
181*4031bb98SShilei Tian         if (S)
182*4031bb98SShilei Tian           checkResult(cuStreamDestroy(S),
183*4031bb98SShilei Tian                       "Error returned from cuStreamDestroy\n");
184feed674dSShilei Tian       }
185feed674dSShilei Tian     }
186feed674dSShilei Tian   }
187feed674dSShilei Tian 
188feed674dSShilei Tian   // Get a CUstream from pool. Per-device next stream id always points to the
189feed674dSShilei Tian   // next available CUstream. That means, CUstreams [0, id-1] have been
190feed674dSShilei Tian   // assigned, and [id,] are still available. If there is no CUstream left, we
191feed674dSShilei Tian   // will ask more CUstreams from CUDA RT. Each time a CUstream is assigned,
192feed674dSShilei Tian   // the id will increase one.
193feed674dSShilei Tian   // xxxxxs+++++++++
194feed674dSShilei Tian   //      ^
195feed674dSShilei Tian   //      id
196feed674dSShilei Tian   // After assignment, the pool becomes the following and s is assigned.
197feed674dSShilei Tian   // xxxxxs+++++++++
198feed674dSShilei Tian   //       ^
199feed674dSShilei Tian   //       id
200feed674dSShilei Tian   CUstream getStream(const int DeviceId) {
201feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
202feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
203feed674dSShilei Tian     // No CUstream left in the pool, we need to request from CUDA RT
204feed674dSShilei Tian     if (Id == StreamPool[DeviceId].size()) {
205feed674dSShilei Tian       // By default we double the stream pool every time
206feed674dSShilei Tian       resizeStreamPool(DeviceId, Id * 2);
207feed674dSShilei Tian     }
208feed674dSShilei Tian     return StreamPool[DeviceId][Id++];
209feed674dSShilei Tian   }
210feed674dSShilei Tian 
211feed674dSShilei Tian   // Return a CUstream back to pool. As mentioned above, per-device next
212feed674dSShilei Tian   // stream is always points to the next available CUstream, so when we return
213feed674dSShilei Tian   // a CUstream, we need to first decrease the id, and then copy the CUstream
214feed674dSShilei Tian   // back.
215feed674dSShilei Tian   // It is worth noting that, the order of streams return might be different
216feed674dSShilei Tian   // from that they're assigned, that saying, at some point, there might be
217feed674dSShilei Tian   // two identical CUstreams.
218feed674dSShilei Tian   // xxax+a+++++
219feed674dSShilei Tian   //     ^
220feed674dSShilei Tian   //     id
221feed674dSShilei Tian   // However, it doesn't matter, because they're always on the two sides of
222feed674dSShilei Tian   // id. The left one will in the end be overwritten by another CUstream.
223feed674dSShilei Tian   // Therefore, after several execution, the order of pool might be different
224feed674dSShilei Tian   // from its initial state.
225feed674dSShilei Tian   void returnStream(const int DeviceId, CUstream Stream) {
226feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
227feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
228feed674dSShilei Tian     assert(Id > 0 && "Wrong stream ID");
229feed674dSShilei Tian     StreamPool[DeviceId][--Id] = Stream;
230feed674dSShilei Tian   }
231feed674dSShilei Tian 
232*4031bb98SShilei Tian   bool initializeDeviceStreamPool(const int DeviceId) {
233*4031bb98SShilei Tian     assert(StreamPool[DeviceId].empty() && "stream pool has been initialized");
234*4031bb98SShilei Tian 
235*4031bb98SShilei Tian     resizeStreamPool(DeviceId, EnvNumInitialStreams);
236*4031bb98SShilei Tian 
237*4031bb98SShilei Tian     // Check the size of stream pool
238*4031bb98SShilei Tian     if (StreamPool[DeviceId].size() != EnvNumInitialStreams)
239*4031bb98SShilei Tian       return false;
240*4031bb98SShilei Tian 
241*4031bb98SShilei Tian     // Check whether each stream is valid
242*4031bb98SShilei Tian     for (CUstream &S : StreamPool[DeviceId])
243*4031bb98SShilei Tian       if (!S)
244*4031bb98SShilei Tian         return false;
245*4031bb98SShilei Tian 
246*4031bb98SShilei Tian     return true;
247feed674dSShilei Tian   }
248feed674dSShilei Tian };
249feed674dSShilei Tian 
250*4031bb98SShilei Tian class DeviceRTLTy {
2513de4cd12SGeorge Rokos   int NumberOfDevices;
252*4031bb98SShilei Tian   // OpenMP environment properties
2533de4cd12SGeorge Rokos   int EnvNumTeams;
2543de4cd12SGeorge Rokos   int EnvTeamLimit;
255*4031bb98SShilei Tian   // OpenMP requires flags
256c5fe030cSGheorghe-Teodor Bercea   int64_t RequiresFlags;
257c5fe030cSGheorghe-Teodor Bercea 
258*4031bb98SShilei Tian   static constexpr const int HardTeamLimit = 1U << 16U; // 64k
259*4031bb98SShilei Tian   static constexpr const int HardThreadLimit = 1024;
260*4031bb98SShilei Tian   static constexpr const int DefaultNumTeams = 128;
261*4031bb98SShilei Tian   static constexpr const int DefaultNumThreads = 128;
2623de4cd12SGeorge Rokos 
263*4031bb98SShilei Tian   std::unique_ptr<StreamManagerTy> StreamManager;
264*4031bb98SShilei Tian   std::vector<DeviceDataTy> DeviceData;
265*4031bb98SShilei Tian   std::vector<CUmodule> Modules;
266feed674dSShilei Tian 
2673de4cd12SGeorge Rokos   // Record entry point associated with device
268*4031bb98SShilei Tian   void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) {
269*4031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
2703de4cd12SGeorge Rokos     E.Entries.push_back(entry);
2713de4cd12SGeorge Rokos   }
2723de4cd12SGeorge Rokos 
2733de4cd12SGeorge Rokos   // Return true if the entry is associated with device
274*4031bb98SShilei Tian   bool findOffloadEntry(const int DeviceId, const void *Addr) const {
275*4031bb98SShilei Tian     for (const __tgt_offload_entry &Itr :
276*4031bb98SShilei Tian          DeviceData[DeviceId].FuncGblEntries.back().Entries)
277*4031bb98SShilei Tian       if (Itr.addr == Addr)
2783de4cd12SGeorge Rokos         return true;
2793de4cd12SGeorge Rokos 
2803de4cd12SGeorge Rokos     return false;
2813de4cd12SGeorge Rokos   }
2823de4cd12SGeorge Rokos 
2833de4cd12SGeorge Rokos   // Return the pointer to the target entries table
284*4031bb98SShilei Tian   __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
285*4031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
2863de4cd12SGeorge Rokos 
287*4031bb98SShilei Tian     if (E.Entries.empty())
288*4031bb98SShilei Tian       return nullptr;
2893de4cd12SGeorge Rokos 
2903de4cd12SGeorge Rokos     // Update table info according to the entries and return the pointer
291*4031bb98SShilei Tian     E.Table.EntriesBegin = E.Entries.data();
292*4031bb98SShilei Tian     E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
2933de4cd12SGeorge Rokos 
2943de4cd12SGeorge Rokos     return &E.Table;
2953de4cd12SGeorge Rokos   }
2963de4cd12SGeorge Rokos 
2973de4cd12SGeorge Rokos   // Clear entries table for a device
298*4031bb98SShilei Tian   void clearOffloadEntriesTable(const int DeviceId) {
299*4031bb98SShilei Tian     DeviceData[DeviceId].FuncGblEntries.emplace_back();
300*4031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
3013de4cd12SGeorge Rokos     E.Entries.clear();
302*4031bb98SShilei Tian     E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
3033de4cd12SGeorge Rokos   }
3043de4cd12SGeorge Rokos 
305*4031bb98SShilei Tian   CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfoPtr) const {
306*4031bb98SShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
307*4031bb98SShilei Tian 
308*4031bb98SShilei Tian     if (!AsyncInfoPtr->Queue)
309*4031bb98SShilei Tian       AsyncInfoPtr->Queue = StreamManager->getStream(DeviceId);
310*4031bb98SShilei Tian 
311*4031bb98SShilei Tian     return reinterpret_cast<CUstream>(AsyncInfoPtr->Queue);
312b305d26bSSergey Dmitriev   }
313*4031bb98SShilei Tian 
314*4031bb98SShilei Tian public:
315*4031bb98SShilei Tian   // This class should not be copied
316*4031bb98SShilei Tian   DeviceRTLTy(const DeviceRTLTy &) = delete;
317*4031bb98SShilei Tian   DeviceRTLTy(DeviceRTLTy &&) = delete;
318*4031bb98SShilei Tian 
319*4031bb98SShilei Tian   DeviceRTLTy()
320*4031bb98SShilei Tian       : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
321*4031bb98SShilei Tian         RequiresFlags(OMP_REQ_UNDEFINED) {
322*4031bb98SShilei Tian #ifdef OMPTARGET_DEBUG
323*4031bb98SShilei Tian     if (const char *EnvStr = getenv("LIBOMPTARGET_DEBUG"))
324*4031bb98SShilei Tian       DebugLevel = std::stoi(EnvStr);
325b305d26bSSergey Dmitriev #endif // OMPTARGET_DEBUG
326b305d26bSSergey Dmitriev 
3273de4cd12SGeorge Rokos     DP("Start initializing CUDA\n");
3283de4cd12SGeorge Rokos 
329*4031bb98SShilei Tian     CUresult Err = cuInit(0);
330*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuInit\n")) {
3313de4cd12SGeorge Rokos       return;
3323de4cd12SGeorge Rokos     }
3333de4cd12SGeorge Rokos 
334*4031bb98SShilei Tian     Err = cuDeviceGetCount(&NumberOfDevices);
335*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
3363de4cd12SGeorge Rokos       return;
3373de4cd12SGeorge Rokos 
3383de4cd12SGeorge Rokos     if (NumberOfDevices == 0) {
3393de4cd12SGeorge Rokos       DP("There are no devices supporting CUDA.\n");
3403de4cd12SGeorge Rokos       return;
3413de4cd12SGeorge Rokos     }
3423de4cd12SGeorge Rokos 
343*4031bb98SShilei Tian     DeviceData.resize(NumberOfDevices);
3443de4cd12SGeorge Rokos 
3453de4cd12SGeorge Rokos     // Get environment variables regarding teams
346*4031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
3473de4cd12SGeorge Rokos       // OMP_TEAM_LIMIT has been set
348*4031bb98SShilei Tian       EnvTeamLimit = std::stoi(EnvStr);
3493de4cd12SGeorge Rokos       DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
3503de4cd12SGeorge Rokos     }
351*4031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
3523de4cd12SGeorge Rokos       // OMP_NUM_TEAMS has been set
353*4031bb98SShilei Tian       EnvNumTeams = std::stoi(EnvStr);
3543de4cd12SGeorge Rokos       DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
3553de4cd12SGeorge Rokos     }
356c5fe030cSGheorghe-Teodor Bercea 
357feed674dSShilei Tian     StreamManager =
358*4031bb98SShilei Tian         std::make_unique<StreamManagerTy>(NumberOfDevices, DeviceData);
3593de4cd12SGeorge Rokos   }
3603de4cd12SGeorge Rokos 
361*4031bb98SShilei Tian   ~DeviceRTLTy() {
362feed674dSShilei Tian     // First destruct stream manager in case of Contexts is destructed before it
363feed674dSShilei Tian     StreamManager = nullptr;
364feed674dSShilei Tian 
365*4031bb98SShilei Tian     for (CUmodule &M : Modules)
366*4031bb98SShilei Tian       // Close module
367*4031bb98SShilei Tian       if (M)
368*4031bb98SShilei Tian         checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n");
369*4031bb98SShilei Tian 
370*4031bb98SShilei Tian     for (DeviceDataTy &D : DeviceData) {
371*4031bb98SShilei Tian       // Destroy context
372*4031bb98SShilei Tian       if (D.Context)
373*4031bb98SShilei Tian         checkResult(cuCtxDestroy(D.Context),
374*4031bb98SShilei Tian                     "Error returned from cuCtxDestroy\n");
3753de4cd12SGeorge Rokos     }
3763de4cd12SGeorge Rokos   }
3773de4cd12SGeorge Rokos 
378*4031bb98SShilei Tian   // Check whether a given DeviceId is valid
379*4031bb98SShilei Tian   bool isValidDeviceId(const int DeviceId) const {
380*4031bb98SShilei Tian     return DeviceId >= 0 && DeviceId < NumberOfDevices;
38132ed2927SShilei Tian   }
38232ed2927SShilei Tian 
383*4031bb98SShilei Tian   bool getNumOfDevices() const { return NumberOfDevices; }
384*4031bb98SShilei Tian 
385*4031bb98SShilei Tian   void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
386*4031bb98SShilei Tian 
387*4031bb98SShilei Tian   int initDevice(const int DeviceId) {
388*4031bb98SShilei Tian     CUdevice Device;
389*4031bb98SShilei Tian 
390*4031bb98SShilei Tian     DP("Getting device %d\n", DeviceId);
391*4031bb98SShilei Tian     CUresult Err = cuDeviceGet(&Device, DeviceId);
392*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
39332ed2927SShilei Tian       return OFFLOAD_FAIL;
3943de4cd12SGeorge Rokos 
3953de4cd12SGeorge Rokos     // Create the context and save it to use whenever this device is selected.
396*4031bb98SShilei Tian     Err = cuCtxCreate(&DeviceData[DeviceId].Context, CU_CTX_SCHED_BLOCKING_SYNC,
397*4031bb98SShilei Tian                       Device);
398*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxCreate\n"))
3993de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
4003de4cd12SGeorge Rokos 
401*4031bb98SShilei Tian     Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
402*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
403*4031bb98SShilei Tian       return OFFLOAD_FAIL;
404a5153dbcSJohannes Doerfert 
405feed674dSShilei Tian     // Initialize stream pool
406*4031bb98SShilei Tian     if (!StreamManager->initializeDeviceStreamPool(DeviceId))
407*4031bb98SShilei Tian       return OFFLOAD_FAIL;
408a5153dbcSJohannes Doerfert 
409bb51d398SJonas Hahnfeld     // Query attributes to determine number of threads/block and blocks/grid.
410*4031bb98SShilei Tian     int MaxGridDimX;
411*4031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
412*4031bb98SShilei Tian                                Device);
413*4031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
414*4031bb98SShilei Tian       DP("Error getting max grid dimension, use default value %d\n",
415*4031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
416*4031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
417*4031bb98SShilei Tian     } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) {
418*4031bb98SShilei Tian       DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
419*4031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
4203de4cd12SGeorge Rokos     } else {
4213de4cd12SGeorge Rokos       DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping "
422bb51d398SJonas Hahnfeld          "at the hard limit\n",
423*4031bb98SShilei Tian          MaxGridDimX, DeviceRTLTy::HardTeamLimit);
424*4031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit;
4253de4cd12SGeorge Rokos     }
4263de4cd12SGeorge Rokos 
427bb51d398SJonas Hahnfeld     // We are only exploiting threads along the x axis.
428*4031bb98SShilei Tian     int MaxBlockDimX;
429*4031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxBlockDimX,
430*4031bb98SShilei Tian                                CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
431*4031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
432*4031bb98SShilei Tian       DP("Error getting max block dimension, use default value %d\n",
433*4031bb98SShilei Tian          DeviceRTLTy::DefaultNumThreads);
434*4031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
435*4031bb98SShilei Tian     } else if (MaxBlockDimX <= DeviceRTLTy::HardThreadLimit) {
436*4031bb98SShilei Tian       DP("Using %d CUDA threads per block\n", MaxBlockDimX);
437*4031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
4383de4cd12SGeorge Rokos     } else {
439*4031bb98SShilei Tian       DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
440*4031bb98SShilei Tian          "capping at the hard limit\n",
441*4031bb98SShilei Tian          MaxBlockDimX, DeviceRTLTy::HardThreadLimit);
442*4031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
4433de4cd12SGeorge Rokos     }
4443de4cd12SGeorge Rokos 
445*4031bb98SShilei Tian     // Get and set warp size
446*4031bb98SShilei Tian     int WarpSize;
447*4031bb98SShilei Tian     Err =
448*4031bb98SShilei Tian         cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
449*4031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
450*4031bb98SShilei Tian       DP("Error getting warp size, assume default value 32\n");
451*4031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = 32;
452bb51d398SJonas Hahnfeld     } else {
453*4031bb98SShilei Tian       DP("Using warp size %d\n", WarpSize);
454*4031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = WarpSize;
4553de4cd12SGeorge Rokos     }
4563de4cd12SGeorge Rokos 
4573de4cd12SGeorge Rokos     // Adjust teams to the env variables
458*4031bb98SShilei Tian     if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
4593de4cd12SGeorge Rokos       DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
460*4031bb98SShilei Tian          EnvTeamLimit);
461*4031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
4623de4cd12SGeorge Rokos     }
4633de4cd12SGeorge Rokos 
4643de4cd12SGeorge Rokos     DP("Max number of CUDA blocks %d, threads %d & warp size %d\n",
465*4031bb98SShilei Tian        DeviceData[DeviceId].BlocksPerGrid, DeviceData[DeviceId].ThreadsPerBlock,
466*4031bb98SShilei Tian        DeviceData[DeviceId].WarpSize);
4673de4cd12SGeorge Rokos 
4683de4cd12SGeorge Rokos     // Set default number of teams
469*4031bb98SShilei Tian     if (EnvNumTeams > 0) {
4703de4cd12SGeorge Rokos       DP("Default number of teams set according to environment %d\n",
471*4031bb98SShilei Tian          EnvNumTeams);
472*4031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = EnvNumTeams;
4733de4cd12SGeorge Rokos     } else {
474*4031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
4753de4cd12SGeorge Rokos       DP("Default number of teams set according to library's default %d\n",
476*4031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
4773de4cd12SGeorge Rokos     }
478*4031bb98SShilei Tian 
479*4031bb98SShilei Tian     if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
4803de4cd12SGeorge Rokos       DP("Default number of teams exceeds device limit, capping at %d\n",
481*4031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
482*4031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
4833de4cd12SGeorge Rokos     }
4843de4cd12SGeorge Rokos 
4853de4cd12SGeorge Rokos     // Set default number of threads
486*4031bb98SShilei Tian     DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
4873de4cd12SGeorge Rokos     DP("Default number of threads set according to library's default %d\n",
488*4031bb98SShilei Tian        DeviceRTLTy::DefaultNumThreads);
489*4031bb98SShilei Tian     if (DeviceData[DeviceId].NumThreads >
490*4031bb98SShilei Tian         DeviceData[DeviceId].ThreadsPerBlock) {
4913de4cd12SGeorge Rokos       DP("Default number of threads exceeds device limit, capping at %d\n",
492*4031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
493*4031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].ThreadsPerBlock;
4943de4cd12SGeorge Rokos     }
4953de4cd12SGeorge Rokos 
4963de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
4973de4cd12SGeorge Rokos   }
4983de4cd12SGeorge Rokos 
499*4031bb98SShilei Tian   __tgt_target_table *loadBinary(const int DeviceId,
500*4031bb98SShilei Tian                                  const __tgt_device_image *Image) {
501*4031bb98SShilei Tian     // Set the context we are using
502*4031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
503*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
504*4031bb98SShilei Tian       return nullptr;
5053de4cd12SGeorge Rokos 
5063de4cd12SGeorge Rokos     // Clear the offload table as we are going to create a new one.
507*4031bb98SShilei Tian     clearOffloadEntriesTable(DeviceId);
5083de4cd12SGeorge Rokos 
5093de4cd12SGeorge Rokos     // Create the module and extract the function pointers.
510*4031bb98SShilei Tian     CUmodule Module;
511*4031bb98SShilei Tian     DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
512*4031bb98SShilei Tian     Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
513*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
514*4031bb98SShilei Tian       return nullptr;
5153de4cd12SGeorge Rokos 
5163de4cd12SGeorge Rokos     DP("CUDA module successfully loaded!\n");
517*4031bb98SShilei Tian 
518*4031bb98SShilei Tian     Modules.push_back(Module);
5193de4cd12SGeorge Rokos 
5203de4cd12SGeorge Rokos     // Find the symbols in the module by name.
521*4031bb98SShilei Tian     const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
522*4031bb98SShilei Tian     const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
5233de4cd12SGeorge Rokos 
524*4031bb98SShilei Tian     for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
525*4031bb98SShilei Tian       if (!E->addr) {
526*4031bb98SShilei Tian         // We return nullptr when something like this happens, the host should
527*4031bb98SShilei Tian         // have always something in the address to uniquely identify the target
528*4031bb98SShilei Tian         // region.
529*4031bb98SShilei Tian         DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
530*4031bb98SShilei Tian         return nullptr;
5313de4cd12SGeorge Rokos       }
5323de4cd12SGeorge Rokos 
533*4031bb98SShilei Tian       if (E->size) {
534*4031bb98SShilei Tian         __tgt_offload_entry Entry = *E;
535*4031bb98SShilei Tian         CUdeviceptr CUPtr;
536*4031bb98SShilei Tian         size_t CUSize;
537*4031bb98SShilei Tian         Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name);
538*4031bb98SShilei Tian         // We keep this style here because we need the name
539*4031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
540*4031bb98SShilei Tian           DP("Loading global '%s' (Failed)\n", E->name);
541*4031bb98SShilei Tian           CUDA_ERR_STRING(Err);
542*4031bb98SShilei Tian           return nullptr;
5433de4cd12SGeorge Rokos         }
5443de4cd12SGeorge Rokos 
545*4031bb98SShilei Tian         if (CUSize != E->size) {
546*4031bb98SShilei Tian           DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
547*4031bb98SShilei Tian              CUSize, E->size);
548*4031bb98SShilei Tian           return nullptr;
5493de4cd12SGeorge Rokos         }
5503de4cd12SGeorge Rokos 
5513de4cd12SGeorge Rokos         DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
552*4031bb98SShilei Tian            DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
553*4031bb98SShilei Tian 
554*4031bb98SShilei Tian         Entry.addr = (void *)(CUPtr);
5553de4cd12SGeorge Rokos 
556aace6d28SGheorghe-Teodor Bercea         // Note: In the current implementation declare target variables
557aace6d28SGheorghe-Teodor Bercea         // can either be link or to. This means that once unified
558aace6d28SGheorghe-Teodor Bercea         // memory is activated via the requires directive, the variable
559aace6d28SGheorghe-Teodor Bercea         // can be used directly from the host in both cases.
560aace6d28SGheorghe-Teodor Bercea         // TODO: when variables types other than to or link are added,
5614c6a098aSKazuaki Ishizaki         // the below condition should be changed to explicitly
562aace6d28SGheorghe-Teodor Bercea         // check for to and link variables types:
563*4031bb98SShilei Tian         // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
564*4031bb98SShilei Tian         // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
565*4031bb98SShilei Tian         if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
566aace6d28SGheorghe-Teodor Bercea           // If unified memory is present any target link or to variables
567c5fe030cSGheorghe-Teodor Bercea           // can access host addresses directly. There is no longer a
568c5fe030cSGheorghe-Teodor Bercea           // need for device copies.
569*4031bb98SShilei Tian           cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *));
570*4031bb98SShilei Tian           DP("Copy linked variable host address (" DPxMOD
571*4031bb98SShilei Tian              ") to device address (" DPxMOD ")\n",
572*4031bb98SShilei Tian              DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
573c5fe030cSGheorghe-Teodor Bercea         }
574c5fe030cSGheorghe-Teodor Bercea 
575*4031bb98SShilei Tian         addOffloadEntry(DeviceId, Entry);
5763de4cd12SGeorge Rokos 
5773de4cd12SGeorge Rokos         continue;
5783de4cd12SGeorge Rokos       }
5793de4cd12SGeorge Rokos 
580*4031bb98SShilei Tian       CUfunction Func;
581*4031bb98SShilei Tian       Err = cuModuleGetFunction(&Func, Module, E->name);
582*4031bb98SShilei Tian       // We keep this style here because we need the name
583*4031bb98SShilei Tian       if (Err != CUDA_SUCCESS) {
584*4031bb98SShilei Tian         DP("Loading '%s' (Failed)\n", E->name);
585*4031bb98SShilei Tian         CUDA_ERR_STRING(Err);
586*4031bb98SShilei Tian         return nullptr;
5873de4cd12SGeorge Rokos       }
5883de4cd12SGeorge Rokos 
5893de4cd12SGeorge Rokos       DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
590*4031bb98SShilei Tian          DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
5913de4cd12SGeorge Rokos 
5923de4cd12SGeorge Rokos       // default value GENERIC (in case symbol is missing from cubin file)
5933de4cd12SGeorge Rokos       int8_t ExecModeVal = ExecutionModeType::GENERIC;
594*4031bb98SShilei Tian       std::string ExecModeNameStr(E->name);
5953de4cd12SGeorge Rokos       ExecModeNameStr += "_exec_mode";
5963de4cd12SGeorge Rokos       const char *ExecModeName = ExecModeNameStr.c_str();
5973de4cd12SGeorge Rokos 
5983de4cd12SGeorge Rokos       CUdeviceptr ExecModePtr;
599*4031bb98SShilei Tian       size_t CUSize;
600*4031bb98SShilei Tian       Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName);
601*4031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
602*4031bb98SShilei Tian         if (CUSize != sizeof(int8_t)) {
6033de4cd12SGeorge Rokos           DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
604*4031bb98SShilei Tian              ExecModeName, CUSize, sizeof(int8_t));
605*4031bb98SShilei Tian           return nullptr;
6063de4cd12SGeorge Rokos         }
6073de4cd12SGeorge Rokos 
608*4031bb98SShilei Tian         Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize);
609*4031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
6103de4cd12SGeorge Rokos           DP("Error when copying data from device to host. Pointers: "
6113de4cd12SGeorge Rokos              "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
612*4031bb98SShilei Tian              DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
613*4031bb98SShilei Tian           CUDA_ERR_STRING(Err);
614*4031bb98SShilei Tian           return nullptr;
6153de4cd12SGeorge Rokos         }
6163de4cd12SGeorge Rokos 
6173de4cd12SGeorge Rokos         if (ExecModeVal < 0 || ExecModeVal > 1) {
6183de4cd12SGeorge Rokos           DP("Error wrong exec_mode value specified in cubin file: %d\n",
6193de4cd12SGeorge Rokos              ExecModeVal);
620*4031bb98SShilei Tian           return nullptr;
6213de4cd12SGeorge Rokos         }
6223de4cd12SGeorge Rokos       } else {
623*4031bb98SShilei Tian         DP("Loading global exec_mode '%s' - symbol missing, using default "
624*4031bb98SShilei Tian            "value GENERIC (1)\n",
625*4031bb98SShilei Tian            ExecModeName);
626*4031bb98SShilei Tian         CUDA_ERR_STRING(Err);
6273de4cd12SGeorge Rokos       }
6283de4cd12SGeorge Rokos 
629*4031bb98SShilei Tian       KernelsList.emplace_back(Func, ExecModeVal);
6303de4cd12SGeorge Rokos 
631*4031bb98SShilei Tian       __tgt_offload_entry Entry = *E;
632*4031bb98SShilei Tian       Entry.addr = &KernelsList.back();
633*4031bb98SShilei Tian       addOffloadEntry(DeviceId, Entry);
6343de4cd12SGeorge Rokos     }
6353de4cd12SGeorge Rokos 
636e1c7a46dSGuansong Zhang     // send device environment data to the device
637e1c7a46dSGuansong Zhang     {
638*4031bb98SShilei Tian       omptarget_device_environmentTy DeviceEnv{0};
639e1c7a46dSGuansong Zhang 
640e1c7a46dSGuansong Zhang #ifdef OMPTARGET_DEBUG
641*4031bb98SShilei Tian       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
642*4031bb98SShilei Tian         DeviceEnv.debug_level = std::stoi(EnvStr);
643e1c7a46dSGuansong Zhang #endif
644e1c7a46dSGuansong Zhang 
645*4031bb98SShilei Tian       const char *DeviceEnvName = "omptarget_device_environment";
646*4031bb98SShilei Tian       CUdeviceptr DeviceEnvPtr;
647*4031bb98SShilei Tian       size_t CUSize;
648e1c7a46dSGuansong Zhang 
649*4031bb98SShilei Tian       Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
650*4031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
651*4031bb98SShilei Tian         if (CUSize != sizeof(DeviceEnv)) {
652e1c7a46dSGuansong Zhang           DP("Global device_environment '%s' - size mismatch (%zu != %zu)\n",
653*4031bb98SShilei Tian              DeviceEnvName, CUSize, sizeof(int32_t));
654*4031bb98SShilei Tian           CUDA_ERR_STRING(Err);
655*4031bb98SShilei Tian           return nullptr;
656e1c7a46dSGuansong Zhang         }
657e1c7a46dSGuansong Zhang 
658*4031bb98SShilei Tian         Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
659*4031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
660e1c7a46dSGuansong Zhang           DP("Error when copying data from host to device. Pointers: "
661e1c7a46dSGuansong Zhang              "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
662*4031bb98SShilei Tian              DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
663*4031bb98SShilei Tian           CUDA_ERR_STRING(Err);
664*4031bb98SShilei Tian           return nullptr;
665e1c7a46dSGuansong Zhang         }
666e1c7a46dSGuansong Zhang 
667*4031bb98SShilei Tian         DP("Sending global device environment data %zu bytes\n", CUSize);
668e1c7a46dSGuansong Zhang       } else {
669*4031bb98SShilei Tian         DP("Finding global device environment '%s' - symbol missing.\n",
670*4031bb98SShilei Tian            DeviceEnvName);
671*4031bb98SShilei Tian         DP("Continue, considering this is a device RTL which does not accept "
672*4031bb98SShilei Tian            "environment setting.\n");
673e1c7a46dSGuansong Zhang       }
674e1c7a46dSGuansong Zhang     }
675e1c7a46dSGuansong Zhang 
676*4031bb98SShilei Tian     return getOffloadEntriesTable(DeviceId);
6773de4cd12SGeorge Rokos   }
6783de4cd12SGeorge Rokos 
679*4031bb98SShilei Tian   void *dataAlloc(const int DeviceId, const int64_t Size) const {
680*4031bb98SShilei Tian     if (Size == 0)
681*4031bb98SShilei Tian       return nullptr;
682*4031bb98SShilei Tian 
683*4031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
684*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
685*4031bb98SShilei Tian       return nullptr;
686*4031bb98SShilei Tian 
687*4031bb98SShilei Tian     CUdeviceptr DevicePtr;
688*4031bb98SShilei Tian     Err = cuMemAlloc(&DevicePtr, Size);
689*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuMemAlloc\n"))
690*4031bb98SShilei Tian       return nullptr;
691*4031bb98SShilei Tian 
692*4031bb98SShilei Tian     return (void *)DevicePtr;
6933de4cd12SGeorge Rokos   }
6943de4cd12SGeorge Rokos 
695*4031bb98SShilei Tian   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
696*4031bb98SShilei Tian                  const int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
697*4031bb98SShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
6983de4cd12SGeorge Rokos 
699*4031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
700*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
7013de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
7023de4cd12SGeorge Rokos 
703*4031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfoPtr);
7043de4cd12SGeorge Rokos 
705*4031bb98SShilei Tian     Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
706*4031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
707*4031bb98SShilei Tian       DP("Error when copying data from host to device. Pointers: host = " DPxMOD
708*4031bb98SShilei Tian          ", device = " DPxMOD ", size = %" PRId64 "\n",
709*4031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
710*4031bb98SShilei Tian       CUDA_ERR_STRING(Err);
7113de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
7123de4cd12SGeorge Rokos     }
7133de4cd12SGeorge Rokos 
7143de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
7153de4cd12SGeorge Rokos   }
7163de4cd12SGeorge Rokos 
717*4031bb98SShilei Tian   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
718*4031bb98SShilei Tian                    const int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
719*4031bb98SShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
720*4031bb98SShilei Tian 
721*4031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
722*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
72303ff643dSShilei Tian       return OFFLOAD_FAIL;
72403ff643dSShilei Tian 
725*4031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfoPtr);
72603ff643dSShilei Tian 
727*4031bb98SShilei Tian     Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
728*4031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
729*4031bb98SShilei Tian       DP("Error when copying data from device to host. Pointers: host = " DPxMOD
730*4031bb98SShilei Tian          ", device = " DPxMOD ", size = %" PRId64 "\n",
731*4031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
732*4031bb98SShilei Tian       CUDA_ERR_STRING(Err);
7333de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
7343de4cd12SGeorge Rokos     }
7353de4cd12SGeorge Rokos 
736*4031bb98SShilei Tian     return OFFLOAD_SUCCESS;
737*4031bb98SShilei Tian   }
738*4031bb98SShilei Tian 
739*4031bb98SShilei Tian   int dataDelete(const int DeviceId, void *TgtPtr) const {
740*4031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
741*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
742*4031bb98SShilei Tian       return OFFLOAD_FAIL;
743*4031bb98SShilei Tian 
744*4031bb98SShilei Tian     Err = cuMemFree((CUdeviceptr)TgtPtr);
745*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuMemFree\n"))
746*4031bb98SShilei Tian       return OFFLOAD_FAIL;
747*4031bb98SShilei Tian 
748*4031bb98SShilei Tian     return OFFLOAD_SUCCESS;
749*4031bb98SShilei Tian   }
750*4031bb98SShilei Tian 
751*4031bb98SShilei Tian   int runTargetTeamRegion(const int DeviceId, const void *TgtEntryPtr,
752*4031bb98SShilei Tian                           void **TgtArgs, ptrdiff_t *TgtOffsets,
753*4031bb98SShilei Tian                           const int ArgNum, const int TeamNum,
754*4031bb98SShilei Tian                           const int ThreadLimit,
755*4031bb98SShilei Tian                           const unsigned int LoopTripCount,
756*4031bb98SShilei Tian                           __tgt_async_info *AsyncInfo) const {
757*4031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
758*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
759*4031bb98SShilei Tian       return OFFLOAD_FAIL;
760*4031bb98SShilei Tian 
7613de4cd12SGeorge Rokos     // All args are references.
762*4031bb98SShilei Tian     std::vector<void *> Args(ArgNum);
763*4031bb98SShilei Tian     std::vector<void *> Ptrs(ArgNum);
7643de4cd12SGeorge Rokos 
765*4031bb98SShilei Tian     for (int I = 0; I < ArgNum; ++I) {
766*4031bb98SShilei Tian       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
767*4031bb98SShilei Tian       Args[I] = &Ptrs[I];
7681546d319SGeorge Rokos     }
7693de4cd12SGeorge Rokos 
770*4031bb98SShilei Tian     const KernelTy *KernelInfo =
771*4031bb98SShilei Tian         reinterpret_cast<const KernelTy *>(TgtEntryPtr);
7723de4cd12SGeorge Rokos 
773*4031bb98SShilei Tian     unsigned int CudaThreadsPerBlock;
774*4031bb98SShilei Tian     if (ThreadLimit > 0) {
775*4031bb98SShilei Tian       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
776*4031bb98SShilei Tian       CudaThreadsPerBlock = ThreadLimit;
7773de4cd12SGeorge Rokos       // Add master warp if necessary
7783de4cd12SGeorge Rokos       if (KernelInfo->ExecutionMode == GENERIC) {
779*4031bb98SShilei Tian         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
780*4031bb98SShilei Tian         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
7813de4cd12SGeorge Rokos       }
782c13df8e5SGeorge Rokos     } else {
783c13df8e5SGeorge Rokos       DP("Setting CUDA threads per block to default %d\n",
784*4031bb98SShilei Tian          DeviceData[DeviceId].NumThreads);
785*4031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
786c13df8e5SGeorge Rokos     }
7873de4cd12SGeorge Rokos 
788*4031bb98SShilei Tian     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
7893de4cd12SGeorge Rokos       DP("Threads per block capped at device limit %d\n",
790*4031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
791*4031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
7923de4cd12SGeorge Rokos     }
7933de4cd12SGeorge Rokos 
794*4031bb98SShilei Tian     int KernelLimit;
795*4031bb98SShilei Tian     Err = cuFuncGetAttribute(&KernelLimit,
796*4031bb98SShilei Tian                              CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
797*4031bb98SShilei Tian                              KernelInfo->Func);
798*4031bb98SShilei Tian     if (Err == CUDA_SUCCESS && KernelLimit < CudaThreadsPerBlock) {
799*4031bb98SShilei Tian       DP("Threads per block capped at kernel limit %d\n", KernelLimit);
800*4031bb98SShilei Tian       CudaThreadsPerBlock = KernelLimit;
8013de4cd12SGeorge Rokos     }
8023de4cd12SGeorge Rokos 
803*4031bb98SShilei Tian     unsigned int CudaBlocksPerGrid;
804*4031bb98SShilei Tian     if (TeamNum <= 0) {
805*4031bb98SShilei Tian       if (LoopTripCount > 0 && EnvNumTeams < 0) {
806c13df8e5SGeorge Rokos         if (KernelInfo->ExecutionMode == SPMD) {
807*4031bb98SShilei Tian           // We have a combined construct, i.e. `target teams distribute
808*4031bb98SShilei Tian           // parallel for [simd]`. We launch so many teams so that each thread
809*4031bb98SShilei Tian           // will execute one iteration of the loop. round up to the nearest
810*4031bb98SShilei Tian           // integer
811*4031bb98SShilei Tian           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
812c13df8e5SGeorge Rokos         } else {
813c13df8e5SGeorge Rokos           // If we reach this point, then we have a non-combined construct, i.e.
814c13df8e5SGeorge Rokos           // `teams distribute` with a nested `parallel for` and each team is
815c13df8e5SGeorge Rokos           // assigned one iteration of the `distribute` loop. E.g.:
816c13df8e5SGeorge Rokos           //
817c13df8e5SGeorge Rokos           // #pragma omp target teams distribute
818c13df8e5SGeorge Rokos           // for(...loop_tripcount...) {
819c13df8e5SGeorge Rokos           //   #pragma omp parallel for
820c13df8e5SGeorge Rokos           //   for(...) {}
821c13df8e5SGeorge Rokos           // }
822c13df8e5SGeorge Rokos           //
823c13df8e5SGeorge Rokos           // Threads within a team will execute the iterations of the `parallel`
824c13df8e5SGeorge Rokos           // loop.
825*4031bb98SShilei Tian           CudaBlocksPerGrid = LoopTripCount;
826c13df8e5SGeorge Rokos         }
827*4031bb98SShilei Tian         DP("Using %d teams due to loop trip count %" PRIu64
828*4031bb98SShilei Tian            " and number of threads per block %d\n",
829*4031bb98SShilei Tian            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
8303de4cd12SGeorge Rokos       } else {
831*4031bb98SShilei Tian         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
832*4031bb98SShilei Tian         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
8333de4cd12SGeorge Rokos       }
834*4031bb98SShilei Tian     } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) {
8353de4cd12SGeorge Rokos       DP("Capping number of teams to team limit %d\n",
836*4031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
837*4031bb98SShilei Tian       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
8383de4cd12SGeorge Rokos     } else {
839*4031bb98SShilei Tian       DP("Using requested number of teams %d\n", TeamNum);
840*4031bb98SShilei Tian       CudaBlocksPerGrid = TeamNum;
8413de4cd12SGeorge Rokos     }
8423de4cd12SGeorge Rokos 
8433de4cd12SGeorge Rokos     // Run on the device.
844*4031bb98SShilei Tian     DP("Launch kernel with %d blocks and %d threads\n", CudaBlocksPerGrid,
845*4031bb98SShilei Tian        CudaThreadsPerBlock);
8463de4cd12SGeorge Rokos 
847*4031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfo);
848*4031bb98SShilei Tian     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
849*4031bb98SShilei Tian                          /* gridDimZ */ 1, CudaThreadsPerBlock,
850*4031bb98SShilei Tian                          /* blockDimY */ 1, /* blockDimZ */ 1,
851*4031bb98SShilei Tian                          /* sharedMemBytes */ 0, Stream, &Args[0], nullptr);
852*4031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
853*4031bb98SShilei Tian       return OFFLOAD_FAIL;
854*4031bb98SShilei Tian 
855*4031bb98SShilei Tian     DP("Launch of entry point at " DPxMOD " successful!\n",
856*4031bb98SShilei Tian        DPxPTR(TgtEntryPtr));
857*4031bb98SShilei Tian 
858*4031bb98SShilei Tian     return OFFLOAD_SUCCESS;
859*4031bb98SShilei Tian   }
860*4031bb98SShilei Tian 
861*4031bb98SShilei Tian   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfoPtr) const {
862*4031bb98SShilei Tian     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfoPtr->Queue);
863*4031bb98SShilei Tian     CUresult Err = cuStreamSynchronize(Stream);
864*4031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
865*4031bb98SShilei Tian       DP("Error when synchronizing stream. stream = " DPxMOD
866*4031bb98SShilei Tian          ", async info ptr = " DPxMOD "\n",
867*4031bb98SShilei Tian          DPxPTR(Stream), DPxPTR(AsyncInfoPtr));
868*4031bb98SShilei Tian       CUDA_ERR_STRING(Err);
8693de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
8703de4cd12SGeorge Rokos     }
8713de4cd12SGeorge Rokos 
872*4031bb98SShilei Tian     // Once the stream is synchronized, return it to stream pool and reset
873*4031bb98SShilei Tian     // async_info. This is to make sure the synchronization only works for its
874*4031bb98SShilei Tian     // own tasks.
875*4031bb98SShilei Tian     StreamManager->returnStream(
876*4031bb98SShilei Tian         DeviceId, reinterpret_cast<CUstream>(AsyncInfoPtr->Queue));
877*4031bb98SShilei Tian     AsyncInfoPtr->Queue = nullptr;
8783de4cd12SGeorge Rokos 
8793de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
8803de4cd12SGeorge Rokos   }
881*4031bb98SShilei Tian };
882*4031bb98SShilei Tian 
883*4031bb98SShilei Tian DeviceRTLTy DeviceRTL;
884*4031bb98SShilei Tian } // namespace
885*4031bb98SShilei Tian 
886*4031bb98SShilei Tian // Exposed library API function
887*4031bb98SShilei Tian #ifdef __cplusplus
888*4031bb98SShilei Tian extern "C" {
889*4031bb98SShilei Tian #endif
890*4031bb98SShilei Tian 
891*4031bb98SShilei Tian int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
892*4031bb98SShilei Tian   return elf_check_machine(image, /* EM_CUDA */ 190);
893*4031bb98SShilei Tian }
894*4031bb98SShilei Tian 
895*4031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
896*4031bb98SShilei Tian 
897*4031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
898*4031bb98SShilei Tian   DP("Init requires flags to %ld\n", RequiresFlags);
899*4031bb98SShilei Tian   DeviceRTL.setRequiresFlag(RequiresFlags);
900*4031bb98SShilei Tian   return RequiresFlags;
901*4031bb98SShilei Tian }
902*4031bb98SShilei Tian 
903*4031bb98SShilei Tian int32_t __tgt_rtl_init_device(int32_t device_id) {
904*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
905*4031bb98SShilei Tian 
906*4031bb98SShilei Tian   return DeviceRTL.initDevice(device_id);
907*4031bb98SShilei Tian }
908*4031bb98SShilei Tian 
909*4031bb98SShilei Tian __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
910*4031bb98SShilei Tian                                           __tgt_device_image *image) {
911*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
912*4031bb98SShilei Tian 
913*4031bb98SShilei Tian   return DeviceRTL.loadBinary(device_id, image);
914*4031bb98SShilei Tian }
915*4031bb98SShilei Tian 
916*4031bb98SShilei Tian void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *) {
917*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
918*4031bb98SShilei Tian 
919*4031bb98SShilei Tian   return DeviceRTL.dataAlloc(device_id, size);
920*4031bb98SShilei Tian }
921*4031bb98SShilei Tian 
922*4031bb98SShilei Tian int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
923*4031bb98SShilei Tian                               int64_t size) {
924*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
925*4031bb98SShilei Tian 
926*4031bb98SShilei Tian   __tgt_async_info async_info;
927*4031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr,
928*4031bb98SShilei Tian                                                  size, &async_info);
929*4031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
930*4031bb98SShilei Tian     return OFFLOAD_FAIL;
931*4031bb98SShilei Tian 
932*4031bb98SShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
933*4031bb98SShilei Tian }
934*4031bb98SShilei Tian 
935*4031bb98SShilei Tian int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr,
936*4031bb98SShilei Tian                                     void *hst_ptr, int64_t size,
937*4031bb98SShilei Tian                                     __tgt_async_info *async_info_ptr) {
938*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
939*4031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
940*4031bb98SShilei Tian 
941*4031bb98SShilei Tian   return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size,
942*4031bb98SShilei Tian                               async_info_ptr);
943*4031bb98SShilei Tian }
944*4031bb98SShilei Tian 
945*4031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
946*4031bb98SShilei Tian                                 int64_t size) {
947*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
948*4031bb98SShilei Tian 
949*4031bb98SShilei Tian   __tgt_async_info async_info;
950*4031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr,
951*4031bb98SShilei Tian                                                    size, &async_info);
952*4031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
953*4031bb98SShilei Tian     return OFFLOAD_FAIL;
954*4031bb98SShilei Tian 
955*4031bb98SShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
956*4031bb98SShilei Tian }
957*4031bb98SShilei Tian 
958*4031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr,
959*4031bb98SShilei Tian                                       void *tgt_ptr, int64_t size,
960*4031bb98SShilei Tian                                       __tgt_async_info *async_info_ptr) {
961*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
962*4031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
963*4031bb98SShilei Tian 
964*4031bb98SShilei Tian   return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size,
965*4031bb98SShilei Tian                                 async_info_ptr);
966*4031bb98SShilei Tian }
967*4031bb98SShilei Tian 
968*4031bb98SShilei Tian int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
969*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
970*4031bb98SShilei Tian 
971*4031bb98SShilei Tian   return DeviceRTL.dataDelete(device_id, tgt_ptr);
972*4031bb98SShilei Tian }
973*4031bb98SShilei Tian 
974*4031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
975*4031bb98SShilei Tian                                          void **tgt_args,
976*4031bb98SShilei Tian                                          ptrdiff_t *tgt_offsets,
977*4031bb98SShilei Tian                                          int32_t arg_num, int32_t team_num,
978*4031bb98SShilei Tian                                          int32_t thread_limit,
979*4031bb98SShilei Tian                                          uint64_t loop_tripcount) {
980*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
981*4031bb98SShilei Tian 
982*4031bb98SShilei Tian   __tgt_async_info async_info;
983*4031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_team_region_async(
984*4031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
985*4031bb98SShilei Tian       thread_limit, loop_tripcount, &async_info);
986*4031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
987*4031bb98SShilei Tian     return OFFLOAD_FAIL;
988*4031bb98SShilei Tian 
989*4031bb98SShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
990*4031bb98SShilei Tian }
991*4031bb98SShilei Tian 
992*4031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async(
993*4031bb98SShilei Tian     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
994*4031bb98SShilei Tian     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
995*4031bb98SShilei Tian     int32_t thread_limit, uint64_t loop_tripcount,
996*4031bb98SShilei Tian     __tgt_async_info *async_info_ptr) {
997*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
998*4031bb98SShilei Tian 
999*4031bb98SShilei Tian   return DeviceRTL.runTargetTeamRegion(
1000*4031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
1001*4031bb98SShilei Tian       thread_limit, loop_tripcount, async_info_ptr);
1002*4031bb98SShilei Tian }
10033de4cd12SGeorge Rokos 
10043de4cd12SGeorge Rokos int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
100532ed2927SShilei Tian                                     void **tgt_args, ptrdiff_t *tgt_offsets,
100603ff643dSShilei Tian                                     int32_t arg_num) {
1007*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1008*4031bb98SShilei Tian 
100903ff643dSShilei Tian   __tgt_async_info async_info;
1010*4031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_region_async(
101103ff643dSShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &async_info);
101203ff643dSShilei Tian   if (rc != OFFLOAD_SUCCESS)
101303ff643dSShilei Tian     return OFFLOAD_FAIL;
101403ff643dSShilei Tian 
101503ff643dSShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
101603ff643dSShilei Tian }
101703ff643dSShilei Tian 
101803ff643dSShilei Tian int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
101903ff643dSShilei Tian                                           void *tgt_entry_ptr, void **tgt_args,
102003ff643dSShilei Tian                                           ptrdiff_t *tgt_offsets,
102132ed2927SShilei Tian                                           int32_t arg_num,
1022*4031bb98SShilei Tian                                           __tgt_async_info *async_info_ptr) {
1023*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1024*4031bb98SShilei Tian 
102503ff643dSShilei Tian   return __tgt_rtl_run_target_team_region_async(
1026*4031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
1027*4031bb98SShilei Tian       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
1028*4031bb98SShilei Tian       async_info_ptr);
102932ed2927SShilei Tian }
103032ed2927SShilei Tian 
1031*4031bb98SShilei Tian int32_t __tgt_rtl_synchronize(int32_t device_id,
1032*4031bb98SShilei Tian                               __tgt_async_info *async_info_ptr) {
1033*4031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1034*4031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
1035*4031bb98SShilei Tian   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
103632ed2927SShilei Tian 
1037*4031bb98SShilei Tian   return DeviceRTL.synchronize(device_id, async_info_ptr);
10383de4cd12SGeorge Rokos }
10393de4cd12SGeorge Rokos 
10403de4cd12SGeorge Rokos #ifdef __cplusplus
10413de4cd12SGeorge Rokos }
10423de4cd12SGeorge Rokos #endif
1043