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>
20a15f8589SJoseph Huber #include <unordered_map>
213de4cd12SGeorge Rokos #include <vector>
223de4cd12SGeorge Rokos 
23ae95ceebSJoseph Huber #include "Debug.h"
241546d319SGeorge Rokos #include "omptargetplugin.h"
253de4cd12SGeorge Rokos 
263de4cd12SGeorge Rokos #define TARGET_NAME CUDA
27ae95ceebSJoseph Huber #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL"
2878769ec4SMichael Kruse 
290871d6d5SShilei Tian #include "MemoryManager.h"
300871d6d5SShilei Tian 
3178769ec4SMichael Kruse // Utility for retrieving and printing CUDA error string.
32ae95ceebSJoseph Huber #ifdef OMPTARGET_DEBUG
3378769ec4SMichael Kruse #define CUDA_ERR_STRING(err)                                                   \
3478769ec4SMichael Kruse   do {                                                                         \
35ae95ceebSJoseph Huber     if (getDebugLevel() > 0) {                                                 \
3603111e5eSYe Luo       const char *errStr = nullptr;                                            \
3703111e5eSYe Luo       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
3803111e5eSYe Luo       if (errStr_status == CUDA_ERROR_INVALID_VALUE)                           \
392ce16810SJoseph Huber         REPORT("Unrecognized CUDA error code: %d\n", err);                     \
4003111e5eSYe Luo       else if (errStr_status == CUDA_SUCCESS)                                  \
412ce16810SJoseph Huber         REPORT("CUDA error is: %s\n", errStr);                                 \
4203111e5eSYe Luo       else {                                                                   \
432ce16810SJoseph Huber         REPORT("Unresolved CUDA error code: %d\n", err);                       \
442ce16810SJoseph Huber         REPORT("Unsuccessful cuGetErrorString return status: %d\n",            \
4503111e5eSYe Luo                errStr_status);                                                 \
4603111e5eSYe Luo       }                                                                        \
472ce16810SJoseph Huber     } else {                                                                   \
482ce16810SJoseph Huber       const char *errStr = nullptr;                                            \
492ce16810SJoseph Huber       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
502ce16810SJoseph Huber       if (errStr_status == CUDA_SUCCESS)                                       \
512ce16810SJoseph Huber         REPORT("%s \n", errStr);                                               \
5278769ec4SMichael Kruse     }                                                                          \
5378769ec4SMichael Kruse   } while (false)
54b305d26bSSergey Dmitriev #else // OMPTARGET_DEBUG
552ce16810SJoseph Huber #define CUDA_ERR_STRING(err)                                                   \
562ce16810SJoseph Huber   do {                                                                         \
572ce16810SJoseph Huber     const char *errStr = nullptr;                                              \
582ce16810SJoseph Huber     CUresult errStr_status = cuGetErrorString(err, &errStr);                   \
592ce16810SJoseph Huber     if (errStr_status == CUDA_SUCCESS)                                         \
602ce16810SJoseph Huber       REPORT("%s \n", errStr);                                                 \
612ce16810SJoseph Huber   } while (false)
62b305d26bSSergey Dmitriev #endif // OMPTARGET_DEBUG
633de4cd12SGeorge Rokos 
64a81c68aeSShilei Tian #include "elf_common.h"
653de4cd12SGeorge Rokos 
663de4cd12SGeorge Rokos /// Keep entries table per device.
673de4cd12SGeorge Rokos struct FuncOrGblEntryTy {
683de4cd12SGeorge Rokos   __tgt_target_table Table;
693de4cd12SGeorge Rokos   std::vector<__tgt_offload_entry> Entries;
703de4cd12SGeorge Rokos };
713de4cd12SGeorge Rokos 
723de4cd12SGeorge Rokos enum ExecutionModeType {
73c13df8e5SGeorge Rokos   SPMD,         // constructors, destructors,
74c13df8e5SGeorge Rokos                 // combined constructs (`teams distribute parallel for [simd]`)
75c13df8e5SGeorge Rokos   GENERIC,      // everything else
767d576392SJoseph Huber   SPMD_GENERIC, // Generic kernel with SPMD execution
773de4cd12SGeorge Rokos   NONE
783de4cd12SGeorge Rokos };
793de4cd12SGeorge Rokos 
80dc34b1c9SRon Lieberman /// Use a single entity to encode a kernel and a set of flags.
813de4cd12SGeorge Rokos struct KernelTy {
823de4cd12SGeorge Rokos   CUfunction Func;
833de4cd12SGeorge Rokos 
843de4cd12SGeorge Rokos   // execution mode of kernel
853de4cd12SGeorge Rokos   // 0 - SPMD mode (without master warp)
863de4cd12SGeorge Rokos   // 1 - Generic mode (with master warp)
877d576392SJoseph Huber   // 2 - SPMD mode execution with Generic mode semantics.
883de4cd12SGeorge Rokos   int8_t ExecutionMode;
893de4cd12SGeorge Rokos 
90aa27cfc1SJohannes Doerfert   /// Maximal number of threads per block for this kernel.
91aa27cfc1SJohannes Doerfert   int MaxThreadsPerBlock = 0;
92aa27cfc1SJohannes Doerfert 
933de4cd12SGeorge Rokos   KernelTy(CUfunction _Func, int8_t _ExecutionMode)
943de4cd12SGeorge Rokos       : Func(_Func), ExecutionMode(_ExecutionMode) {}
953de4cd12SGeorge Rokos };
963de4cd12SGeorge Rokos 
974c6a098aSKazuaki Ishizaki /// Device environment data
98feed674dSShilei Tian /// Manually sync with the deviceRTL side for now, move to a dedicated header
99feed674dSShilei Tian /// file later.
100e1c7a46dSGuansong Zhang struct omptarget_device_environmentTy {
101e1c7a46dSGuansong Zhang   int32_t debug_level;
102e1c7a46dSGuansong Zhang };
103e1c7a46dSGuansong Zhang 
104feed674dSShilei Tian namespace {
105feed674dSShilei Tian bool checkResult(CUresult Err, const char *ErrMsg) {
106feed674dSShilei Tian   if (Err == CUDA_SUCCESS)
107feed674dSShilei Tian     return true;
108feed674dSShilei Tian 
1092ce16810SJoseph Huber   REPORT("%s", ErrMsg);
110feed674dSShilei Tian   CUDA_ERR_STRING(Err);
111feed674dSShilei Tian   return false;
112feed674dSShilei Tian }
1134031bb98SShilei Tian 
114a014fbbcSShilei Tian int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size,
115a014fbbcSShilei Tian                CUstream Stream) {
11695f0d1edSJon Chesterfield   CUresult Err =
11795f0d1edSJon Chesterfield       cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream);
118a014fbbcSShilei Tian 
119a014fbbcSShilei Tian   if (Err != CUDA_SUCCESS) {
12029338459SJoseph Huber     DP("Error when copying data from device to device. Pointers: src "
121a014fbbcSShilei Tian        "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n",
122a014fbbcSShilei Tian        DPxPTR(SrcPtr), DPxPTR(DstPtr), Size);
123a014fbbcSShilei Tian     CUDA_ERR_STRING(Err);
124a014fbbcSShilei Tian     return OFFLOAD_FAIL;
125a014fbbcSShilei Tian   }
126a014fbbcSShilei Tian 
127a014fbbcSShilei Tian   return OFFLOAD_SUCCESS;
128a014fbbcSShilei Tian }
129a014fbbcSShilei Tian 
1304031bb98SShilei Tian // Structure contains per-device data
1314031bb98SShilei Tian struct DeviceDataTy {
1325272d29eSJohannes Doerfert   /// List that contains all the kernels.
1335272d29eSJohannes Doerfert   std::list<KernelTy> KernelsList;
1345272d29eSJohannes Doerfert 
1354031bb98SShilei Tian   std::list<FuncOrGblEntryTy> FuncGblEntries;
1365272d29eSJohannes Doerfert 
1374031bb98SShilei Tian   CUcontext Context = nullptr;
1384031bb98SShilei Tian   // Device properties
1394031bb98SShilei Tian   int ThreadsPerBlock = 0;
1404031bb98SShilei Tian   int BlocksPerGrid = 0;
1414031bb98SShilei Tian   int WarpSize = 0;
1424031bb98SShilei Tian   // OpenMP properties
1434031bb98SShilei Tian   int NumTeams = 0;
1444031bb98SShilei Tian   int NumThreads = 0;
1454031bb98SShilei Tian };
146feed674dSShilei Tian 
147feed674dSShilei Tian class StreamManagerTy {
148feed674dSShilei Tian   int NumberOfDevices;
1494031bb98SShilei Tian   // The initial size of stream pool
1504031bb98SShilei Tian   int EnvNumInitialStreams;
151feed674dSShilei Tian   // Per-device stream mutex
152feed674dSShilei Tian   std::vector<std::unique_ptr<std::mutex>> StreamMtx;
153feed674dSShilei Tian   // Per-device stream Id indicates the next available stream in the pool
154feed674dSShilei Tian   std::vector<int> NextStreamId;
155feed674dSShilei Tian   // Per-device stream pool
156feed674dSShilei Tian   std::vector<std::vector<CUstream>> StreamPool;
1574031bb98SShilei Tian   // Reference to per-device data
1584031bb98SShilei Tian   std::vector<DeviceDataTy> &DeviceData;
159feed674dSShilei Tian 
160feed674dSShilei Tian   // If there is no CUstream left in the pool, we will resize the pool to
161feed674dSShilei Tian   // allocate more CUstream. This function should be called with device mutex,
162feed674dSShilei Tian   // and we do not resize to smaller one.
163feed674dSShilei Tian   void resizeStreamPool(const int DeviceId, const size_t NewSize) {
164feed674dSShilei Tian     std::vector<CUstream> &Pool = StreamPool[DeviceId];
165feed674dSShilei Tian     const size_t CurrentSize = Pool.size();
166feed674dSShilei Tian     assert(NewSize > CurrentSize && "new size is not larger than current size");
167feed674dSShilei Tian 
1684031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
1694031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) {
170feed674dSShilei Tian       // We will return if cannot switch to the right context in case of
171feed674dSShilei Tian       // creating bunch of streams that are not corresponding to the right
172feed674dSShilei Tian       // device. The offloading will fail later because selected CUstream is
173feed674dSShilei Tian       // nullptr.
174feed674dSShilei Tian       return;
175feed674dSShilei Tian     }
176feed674dSShilei Tian 
1774031bb98SShilei Tian     Pool.resize(NewSize, nullptr);
1784031bb98SShilei Tian 
179feed674dSShilei Tian     for (size_t I = CurrentSize; I < NewSize; ++I) {
1804031bb98SShilei Tian       checkResult(cuStreamCreate(&Pool[I], CU_STREAM_NON_BLOCKING),
1814031bb98SShilei Tian                   "Error returned from cuStreamCreate\n");
182feed674dSShilei Tian     }
183feed674dSShilei Tian   }
184feed674dSShilei Tian 
185feed674dSShilei Tian public:
1864031bb98SShilei Tian   StreamManagerTy(const int NumberOfDevices,
1874031bb98SShilei Tian                   std::vector<DeviceDataTy> &DeviceData)
1884031bb98SShilei Tian       : NumberOfDevices(NumberOfDevices), EnvNumInitialStreams(32),
1894031bb98SShilei Tian         DeviceData(DeviceData) {
190feed674dSShilei Tian     StreamPool.resize(NumberOfDevices);
191feed674dSShilei Tian     NextStreamId.resize(NumberOfDevices);
192feed674dSShilei Tian     StreamMtx.resize(NumberOfDevices);
193feed674dSShilei Tian 
1944031bb98SShilei Tian     if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS"))
1954031bb98SShilei Tian       EnvNumInitialStreams = std::stoi(EnvStr);
196feed674dSShilei Tian 
197feed674dSShilei Tian     // Initialize the next stream id
198feed674dSShilei Tian     std::fill(NextStreamId.begin(), NextStreamId.end(), 0);
199feed674dSShilei Tian 
200feed674dSShilei Tian     // Initialize stream mutex
201feed674dSShilei Tian     for (std::unique_ptr<std::mutex> &Ptr : StreamMtx)
202feed674dSShilei Tian       Ptr = std::make_unique<std::mutex>();
203feed674dSShilei Tian   }
204feed674dSShilei Tian 
205feed674dSShilei Tian   ~StreamManagerTy() {
206feed674dSShilei Tian     // Destroy streams
207feed674dSShilei Tian     for (int I = 0; I < NumberOfDevices; ++I) {
2084031bb98SShilei Tian       checkResult(cuCtxSetCurrent(DeviceData[I].Context),
2094031bb98SShilei Tian                   "Error returned from cuCtxSetCurrent\n");
210feed674dSShilei Tian 
211feed674dSShilei Tian       for (CUstream &S : StreamPool[I]) {
2124031bb98SShilei Tian         if (S)
21395f0d1edSJon Chesterfield           checkResult(cuStreamDestroy(S),
21495f0d1edSJon Chesterfield                       "Error returned from cuStreamDestroy\n");
215feed674dSShilei Tian       }
216feed674dSShilei Tian     }
217feed674dSShilei Tian   }
218feed674dSShilei Tian 
219feed674dSShilei Tian   // Get a CUstream from pool. Per-device next stream id always points to the
220feed674dSShilei Tian   // next available CUstream. That means, CUstreams [0, id-1] have been
221feed674dSShilei Tian   // assigned, and [id,] are still available. If there is no CUstream left, we
222feed674dSShilei Tian   // will ask more CUstreams from CUDA RT. Each time a CUstream is assigned,
223feed674dSShilei Tian   // the id will increase one.
224feed674dSShilei Tian   // xxxxxs+++++++++
225feed674dSShilei Tian   //      ^
226feed674dSShilei Tian   //      id
227feed674dSShilei Tian   // After assignment, the pool becomes the following and s is assigned.
228feed674dSShilei Tian   // xxxxxs+++++++++
229feed674dSShilei Tian   //       ^
230feed674dSShilei Tian   //       id
231feed674dSShilei Tian   CUstream getStream(const int DeviceId) {
232feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
233feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
234feed674dSShilei Tian     // No CUstream left in the pool, we need to request from CUDA RT
235ad94fce8SJohannes Doerfert     if (Id == static_cast<int>(StreamPool[DeviceId].size())) {
236feed674dSShilei Tian       // By default we double the stream pool every time
237feed674dSShilei Tian       resizeStreamPool(DeviceId, Id * 2);
238feed674dSShilei Tian     }
239feed674dSShilei Tian     return StreamPool[DeviceId][Id++];
240feed674dSShilei Tian   }
241feed674dSShilei Tian 
242feed674dSShilei Tian   // Return a CUstream back to pool. As mentioned above, per-device next
243feed674dSShilei Tian   // stream is always points to the next available CUstream, so when we return
244feed674dSShilei Tian   // a CUstream, we need to first decrease the id, and then copy the CUstream
245feed674dSShilei Tian   // back.
246feed674dSShilei Tian   // It is worth noting that, the order of streams return might be different
247feed674dSShilei Tian   // from that they're assigned, that saying, at some point, there might be
248feed674dSShilei Tian   // two identical CUstreams.
249feed674dSShilei Tian   // xxax+a+++++
250feed674dSShilei Tian   //     ^
251feed674dSShilei Tian   //     id
252feed674dSShilei Tian   // However, it doesn't matter, because they're always on the two sides of
253feed674dSShilei Tian   // id. The left one will in the end be overwritten by another CUstream.
254feed674dSShilei Tian   // Therefore, after several execution, the order of pool might be different
255feed674dSShilei Tian   // from its initial state.
256feed674dSShilei Tian   void returnStream(const int DeviceId, CUstream Stream) {
257feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
258feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
259feed674dSShilei Tian     assert(Id > 0 && "Wrong stream ID");
260feed674dSShilei Tian     StreamPool[DeviceId][--Id] = Stream;
261feed674dSShilei Tian   }
262feed674dSShilei Tian 
2634031bb98SShilei Tian   bool initializeDeviceStreamPool(const int DeviceId) {
2644031bb98SShilei Tian     assert(StreamPool[DeviceId].empty() && "stream pool has been initialized");
2654031bb98SShilei Tian 
2664031bb98SShilei Tian     resizeStreamPool(DeviceId, EnvNumInitialStreams);
2674031bb98SShilei Tian 
2684031bb98SShilei Tian     // Check the size of stream pool
269ad94fce8SJohannes Doerfert     if (static_cast<int>(StreamPool[DeviceId].size()) != EnvNumInitialStreams)
2704031bb98SShilei Tian       return false;
2714031bb98SShilei Tian 
2724031bb98SShilei Tian     // Check whether each stream is valid
2734031bb98SShilei Tian     for (CUstream &S : StreamPool[DeviceId])
2744031bb98SShilei Tian       if (!S)
2754031bb98SShilei Tian         return false;
2764031bb98SShilei Tian 
2774031bb98SShilei Tian     return true;
278feed674dSShilei Tian   }
279feed674dSShilei Tian };
280feed674dSShilei Tian 
2814031bb98SShilei Tian class DeviceRTLTy {
2823de4cd12SGeorge Rokos   int NumberOfDevices;
2834031bb98SShilei Tian   // OpenMP environment properties
2843de4cd12SGeorge Rokos   int EnvNumTeams;
2853de4cd12SGeorge Rokos   int EnvTeamLimit;
286422adaa8SJoseph Huber   int EnvTeamThreadLimit;
2874031bb98SShilei Tian   // OpenMP requires flags
288c5fe030cSGheorghe-Teodor Bercea   int64_t RequiresFlags;
289c5fe030cSGheorghe-Teodor Bercea 
2904031bb98SShilei Tian   static constexpr const int HardTeamLimit = 1U << 16U; // 64k
2914031bb98SShilei Tian   static constexpr const int HardThreadLimit = 1024;
2924031bb98SShilei Tian   static constexpr const int DefaultNumTeams = 128;
2934031bb98SShilei Tian   static constexpr const int DefaultNumThreads = 128;
2943de4cd12SGeorge Rokos 
2954031bb98SShilei Tian   std::unique_ptr<StreamManagerTy> StreamManager;
2964031bb98SShilei Tian   std::vector<DeviceDataTy> DeviceData;
2974031bb98SShilei Tian   std::vector<CUmodule> Modules;
298feed674dSShilei Tian 
2990871d6d5SShilei Tian   /// A class responsible for interacting with device native runtime library to
3000871d6d5SShilei Tian   /// allocate and free memory.
3010871d6d5SShilei Tian   class CUDADeviceAllocatorTy : public DeviceAllocatorTy {
3020871d6d5SShilei Tian     const int DeviceId;
3030871d6d5SShilei Tian     const std::vector<DeviceDataTy> &DeviceData;
304a15f8589SJoseph Huber     std::unordered_map<void *, TargetAllocTy> HostPinnedAllocs;
3050871d6d5SShilei Tian 
3060871d6d5SShilei Tian   public:
3070871d6d5SShilei Tian     CUDADeviceAllocatorTy(int DeviceId, std::vector<DeviceDataTy> &DeviceData)
3080871d6d5SShilei Tian         : DeviceId(DeviceId), DeviceData(DeviceData) {}
3090871d6d5SShilei Tian 
310a15f8589SJoseph Huber     void *allocate(size_t Size, void *, TargetAllocTy Kind) override {
3110871d6d5SShilei Tian       if (Size == 0)
3120871d6d5SShilei Tian         return nullptr;
3130871d6d5SShilei Tian 
3140871d6d5SShilei Tian       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
3150871d6d5SShilei Tian       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
3160871d6d5SShilei Tian         return nullptr;
3170871d6d5SShilei Tian 
318a15f8589SJoseph Huber       void *MemAlloc = nullptr;
319a15f8589SJoseph Huber       switch (Kind) {
320a15f8589SJoseph Huber       case TARGET_ALLOC_DEFAULT:
321a15f8589SJoseph Huber       case TARGET_ALLOC_DEVICE:
3220871d6d5SShilei Tian         CUdeviceptr DevicePtr;
32395f0d1edSJon Chesterfield         Err = cuMemAlloc(&DevicePtr, Size);
324a15f8589SJoseph Huber         MemAlloc = (void *)DevicePtr;
32595f0d1edSJon Chesterfield         if (!checkResult(Err, "Error returned from cuMemAlloc\n"))
3260871d6d5SShilei Tian           return nullptr;
327a15f8589SJoseph Huber         break;
328a15f8589SJoseph Huber       case TARGET_ALLOC_HOST:
329a15f8589SJoseph Huber         void *HostPtr;
330a15f8589SJoseph Huber         Err = cuMemAllocHost(&HostPtr, Size);
331a15f8589SJoseph Huber         MemAlloc = HostPtr;
332a15f8589SJoseph Huber         if (!checkResult(Err, "Error returned from cuMemAllocHost\n"))
333a15f8589SJoseph Huber           return nullptr;
334a15f8589SJoseph Huber         HostPinnedAllocs[MemAlloc] = Kind;
335a15f8589SJoseph Huber         break;
336a15f8589SJoseph Huber       case TARGET_ALLOC_SHARED:
337a15f8589SJoseph Huber         CUdeviceptr SharedPtr;
338a15f8589SJoseph Huber         Err = cuMemAllocManaged(&SharedPtr, Size, CU_MEM_ATTACH_GLOBAL);
339a15f8589SJoseph Huber         MemAlloc = (void *)SharedPtr;
340a15f8589SJoseph Huber         if (!checkResult(Err, "Error returned from cuMemAllocManaged\n"))
341a15f8589SJoseph Huber           return nullptr;
342a15f8589SJoseph Huber         break;
343a15f8589SJoseph Huber       }
3440871d6d5SShilei Tian 
345a15f8589SJoseph Huber       return MemAlloc;
3460871d6d5SShilei Tian     }
3470871d6d5SShilei Tian 
3480871d6d5SShilei Tian     int free(void *TgtPtr) override {
3490871d6d5SShilei Tian       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
3500871d6d5SShilei Tian       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
3510871d6d5SShilei Tian         return OFFLOAD_FAIL;
3520871d6d5SShilei Tian 
353a15f8589SJoseph Huber       // Host pinned memory must be freed differently.
354a15f8589SJoseph Huber       TargetAllocTy Kind =
355a15f8589SJoseph Huber           (HostPinnedAllocs.find(TgtPtr) == HostPinnedAllocs.end())
356a15f8589SJoseph Huber               ? TARGET_ALLOC_DEFAULT
357a15f8589SJoseph Huber               : TARGET_ALLOC_HOST;
358a15f8589SJoseph Huber       switch (Kind) {
359a15f8589SJoseph Huber       case TARGET_ALLOC_DEFAULT:
360a15f8589SJoseph Huber       case TARGET_ALLOC_DEVICE:
361a15f8589SJoseph Huber       case TARGET_ALLOC_SHARED:
36295f0d1edSJon Chesterfield         Err = cuMemFree((CUdeviceptr)TgtPtr);
36395f0d1edSJon Chesterfield         if (!checkResult(Err, "Error returned from cuMemFree\n"))
3640871d6d5SShilei Tian           return OFFLOAD_FAIL;
365a15f8589SJoseph Huber         break;
366a15f8589SJoseph Huber       case TARGET_ALLOC_HOST:
367a15f8589SJoseph Huber         Err = cuMemFreeHost(TgtPtr);
368a15f8589SJoseph Huber         if (!checkResult(Err, "Error returned from cuMemFreeHost\n"))
369a15f8589SJoseph Huber           return OFFLOAD_FAIL;
370a15f8589SJoseph Huber         break;
371a15f8589SJoseph Huber       }
3720871d6d5SShilei Tian 
3730871d6d5SShilei Tian       return OFFLOAD_SUCCESS;
3740871d6d5SShilei Tian     }
3750871d6d5SShilei Tian   };
3760871d6d5SShilei Tian 
3770871d6d5SShilei Tian   /// A vector of device allocators
3780871d6d5SShilei Tian   std::vector<CUDADeviceAllocatorTy> DeviceAllocators;
3790871d6d5SShilei Tian 
3800871d6d5SShilei Tian   /// A vector of memory managers. Since the memory manager is non-copyable and
3810871d6d5SShilei Tian   // non-removable, we wrap them into std::unique_ptr.
3820871d6d5SShilei Tian   std::vector<std::unique_ptr<MemoryManagerTy>> MemoryManagers;
3830871d6d5SShilei Tian 
3840871d6d5SShilei Tian   /// Whether use memory manager
3850871d6d5SShilei Tian   bool UseMemoryManager = true;
3860871d6d5SShilei Tian 
3873de4cd12SGeorge Rokos   // Record entry point associated with device
3884031bb98SShilei Tian   void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) {
3894031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
3903de4cd12SGeorge Rokos     E.Entries.push_back(entry);
3913de4cd12SGeorge Rokos   }
3923de4cd12SGeorge Rokos 
393ae209397SJoseph Huber   // Return a pointer to the entry associated with the pointer
394ae209397SJoseph Huber   const __tgt_offload_entry *getOffloadEntry(const int DeviceId,
395ae209397SJoseph Huber                                              const void *Addr) const {
3964031bb98SShilei Tian     for (const __tgt_offload_entry &Itr :
3974031bb98SShilei Tian          DeviceData[DeviceId].FuncGblEntries.back().Entries)
3984031bb98SShilei Tian       if (Itr.addr == Addr)
399ae209397SJoseph Huber         return &Itr;
4003de4cd12SGeorge Rokos 
401ae209397SJoseph Huber     return nullptr;
4023de4cd12SGeorge Rokos   }
4033de4cd12SGeorge Rokos 
4043de4cd12SGeorge Rokos   // Return the pointer to the target entries table
4054031bb98SShilei Tian   __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
4064031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
4073de4cd12SGeorge Rokos 
4084031bb98SShilei Tian     if (E.Entries.empty())
4094031bb98SShilei Tian       return nullptr;
4103de4cd12SGeorge Rokos 
4113de4cd12SGeorge Rokos     // Update table info according to the entries and return the pointer
4124031bb98SShilei Tian     E.Table.EntriesBegin = E.Entries.data();
4134031bb98SShilei Tian     E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
4143de4cd12SGeorge Rokos 
4153de4cd12SGeorge Rokos     return &E.Table;
4163de4cd12SGeorge Rokos   }
4173de4cd12SGeorge Rokos 
4183de4cd12SGeorge Rokos   // Clear entries table for a device
4194031bb98SShilei Tian   void clearOffloadEntriesTable(const int DeviceId) {
4204031bb98SShilei Tian     DeviceData[DeviceId].FuncGblEntries.emplace_back();
4214031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
4223de4cd12SGeorge Rokos     E.Entries.clear();
4234031bb98SShilei Tian     E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
4243de4cd12SGeorge Rokos   }
4253de4cd12SGeorge Rokos 
4265449fbb5SJohannes Doerfert   CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfo) const {
4275449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
4284031bb98SShilei Tian 
4295449fbb5SJohannes Doerfert     if (!AsyncInfo->Queue)
4305449fbb5SJohannes Doerfert       AsyncInfo->Queue = StreamManager->getStream(DeviceId);
4314031bb98SShilei Tian 
4325449fbb5SJohannes Doerfert     return reinterpret_cast<CUstream>(AsyncInfo->Queue);
433b305d26bSSergey Dmitriev   }
4344031bb98SShilei Tian 
4354031bb98SShilei Tian public:
4364031bb98SShilei Tian   // This class should not be copied
4374031bb98SShilei Tian   DeviceRTLTy(const DeviceRTLTy &) = delete;
4384031bb98SShilei Tian   DeviceRTLTy(DeviceRTLTy &&) = delete;
4394031bb98SShilei Tian 
4404031bb98SShilei Tian   DeviceRTLTy()
4414031bb98SShilei Tian       : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
442422adaa8SJoseph Huber         EnvTeamThreadLimit(-1), RequiresFlags(OMP_REQ_UNDEFINED) {
443b305d26bSSergey Dmitriev 
4443de4cd12SGeorge Rokos     DP("Start initializing CUDA\n");
4453de4cd12SGeorge Rokos 
4464031bb98SShilei Tian     CUresult Err = cuInit(0);
4477baff00eSJon Chesterfield     if (Err == CUDA_ERROR_INVALID_HANDLE) {
4487baff00eSJon Chesterfield       // Can't call cuGetErrorString if dlsym failed
4497baff00eSJon Chesterfield       DP("Failed to load CUDA shared library\n");
4507baff00eSJon Chesterfield       return;
4517baff00eSJon Chesterfield     }
4524031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuInit\n")) {
4533de4cd12SGeorge Rokos       return;
4543de4cd12SGeorge Rokos     }
4553de4cd12SGeorge Rokos 
4564031bb98SShilei Tian     Err = cuDeviceGetCount(&NumberOfDevices);
4574031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
4583de4cd12SGeorge Rokos       return;
4593de4cd12SGeorge Rokos 
4603de4cd12SGeorge Rokos     if (NumberOfDevices == 0) {
4613de4cd12SGeorge Rokos       DP("There are no devices supporting CUDA.\n");
4623de4cd12SGeorge Rokos       return;
4633de4cd12SGeorge Rokos     }
4643de4cd12SGeorge Rokos 
4654031bb98SShilei Tian     DeviceData.resize(NumberOfDevices);
4663de4cd12SGeorge Rokos 
4673de4cd12SGeorge Rokos     // Get environment variables regarding teams
4684031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
4693de4cd12SGeorge Rokos       // OMP_TEAM_LIMIT has been set
4704031bb98SShilei Tian       EnvTeamLimit = std::stoi(EnvStr);
4713de4cd12SGeorge Rokos       DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
4723de4cd12SGeorge Rokos     }
473422adaa8SJoseph Huber     if (const char *EnvStr = getenv("OMP_TEAMS_THREAD_LIMIT")) {
474422adaa8SJoseph Huber       // OMP_TEAMS_THREAD_LIMIT has been set
475422adaa8SJoseph Huber       EnvTeamThreadLimit = std::stoi(EnvStr);
476422adaa8SJoseph Huber       DP("Parsed OMP_TEAMS_THREAD_LIMIT=%d\n", EnvTeamThreadLimit);
477422adaa8SJoseph Huber     }
4784031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
4793de4cd12SGeorge Rokos       // OMP_NUM_TEAMS has been set
4804031bb98SShilei Tian       EnvNumTeams = std::stoi(EnvStr);
4813de4cd12SGeorge Rokos       DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
4823de4cd12SGeorge Rokos     }
483c5fe030cSGheorghe-Teodor Bercea 
484feed674dSShilei Tian     StreamManager =
4854031bb98SShilei Tian         std::make_unique<StreamManagerTy>(NumberOfDevices, DeviceData);
4860871d6d5SShilei Tian 
4870871d6d5SShilei Tian     for (int I = 0; I < NumberOfDevices; ++I)
4880871d6d5SShilei Tian       DeviceAllocators.emplace_back(I, DeviceData);
4890871d6d5SShilei Tian 
4900871d6d5SShilei Tian     // Get the size threshold from environment variable
4910871d6d5SShilei Tian     std::pair<size_t, bool> Res = MemoryManagerTy::getSizeThresholdFromEnv();
4920871d6d5SShilei Tian     UseMemoryManager = Res.second;
4930871d6d5SShilei Tian     size_t MemoryManagerThreshold = Res.first;
4940871d6d5SShilei Tian 
4950871d6d5SShilei Tian     if (UseMemoryManager)
4960871d6d5SShilei Tian       for (int I = 0; I < NumberOfDevices; ++I)
4970871d6d5SShilei Tian         MemoryManagers.emplace_back(std::make_unique<MemoryManagerTy>(
4980871d6d5SShilei Tian             DeviceAllocators[I], MemoryManagerThreshold));
4993de4cd12SGeorge Rokos   }
5003de4cd12SGeorge Rokos 
5014031bb98SShilei Tian   ~DeviceRTLTy() {
5020871d6d5SShilei Tian     // We first destruct memory managers in case that its dependent data are
5030871d6d5SShilei Tian     // destroyed before it.
5040871d6d5SShilei Tian     for (auto &M : MemoryManagers)
5050871d6d5SShilei Tian       M.release();
5060871d6d5SShilei Tian 
507feed674dSShilei Tian     StreamManager = nullptr;
508feed674dSShilei Tian 
5094031bb98SShilei Tian     for (CUmodule &M : Modules)
5104031bb98SShilei Tian       // Close module
5114031bb98SShilei Tian       if (M)
5124031bb98SShilei Tian         checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n");
5134031bb98SShilei Tian 
5144031bb98SShilei Tian     for (DeviceDataTy &D : DeviceData) {
5154031bb98SShilei Tian       // Destroy context
516c5348aecSYe Luo       if (D.Context) {
517c5348aecSYe Luo         checkResult(cuCtxSetCurrent(D.Context),
518c5348aecSYe Luo                     "Error returned from cuCtxSetCurrent\n");
519c5348aecSYe Luo         CUdevice Device;
520c5348aecSYe Luo         checkResult(cuCtxGetDevice(&Device),
521c5348aecSYe Luo                     "Error returned from cuCtxGetDevice\n");
52295f0d1edSJon Chesterfield         checkResult(cuDevicePrimaryCtxRelease(Device),
52395f0d1edSJon Chesterfield                     "Error returned from cuDevicePrimaryCtxRelease\n");
524c5348aecSYe Luo       }
5253de4cd12SGeorge Rokos     }
5263de4cd12SGeorge Rokos   }
5273de4cd12SGeorge Rokos 
5284031bb98SShilei Tian   // Check whether a given DeviceId is valid
5294031bb98SShilei Tian   bool isValidDeviceId(const int DeviceId) const {
5304031bb98SShilei Tian     return DeviceId >= 0 && DeviceId < NumberOfDevices;
53132ed2927SShilei Tian   }
53232ed2927SShilei Tian 
533cb038927SShilei Tian   int getNumOfDevices() const { return NumberOfDevices; }
5344031bb98SShilei Tian 
5354031bb98SShilei Tian   void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
5364031bb98SShilei Tian 
5374031bb98SShilei Tian   int initDevice(const int DeviceId) {
5384031bb98SShilei Tian     CUdevice Device;
5394031bb98SShilei Tian 
5404031bb98SShilei Tian     DP("Getting device %d\n", DeviceId);
5414031bb98SShilei Tian     CUresult Err = cuDeviceGet(&Device, DeviceId);
5424031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
54332ed2927SShilei Tian       return OFFLOAD_FAIL;
5443de4cd12SGeorge Rokos 
545c5348aecSYe Luo     // Query the current flags of the primary context and set its flags if
546c5348aecSYe Luo     // it is inactive
547c5348aecSYe Luo     unsigned int FormerPrimaryCtxFlags = 0;
548c5348aecSYe Luo     int FormerPrimaryCtxIsActive = 0;
549c5348aecSYe Luo     Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags,
550c5348aecSYe Luo                                      &FormerPrimaryCtxIsActive);
551c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n"))
552c5348aecSYe Luo       return OFFLOAD_FAIL;
553c5348aecSYe Luo 
554c5348aecSYe Luo     if (FormerPrimaryCtxIsActive) {
555c5348aecSYe Luo       DP("The primary context is active, no change to its flags\n");
556c5348aecSYe Luo       if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) !=
557c5348aecSYe Luo           CU_CTX_SCHED_BLOCKING_SYNC)
558c5348aecSYe Luo         DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n");
559c5348aecSYe Luo     } else {
560c5348aecSYe Luo       DP("The primary context is inactive, set its flags to "
561c5348aecSYe Luo          "CU_CTX_SCHED_BLOCKING_SYNC\n");
56295f0d1edSJon Chesterfield       Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC);
56395f0d1edSJon Chesterfield       if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n"))
564c5348aecSYe Luo         return OFFLOAD_FAIL;
565c5348aecSYe Luo     }
566c5348aecSYe Luo 
567c5348aecSYe Luo     // Retain the per device primary context and save it to use whenever this
568c5348aecSYe Luo     // device is selected.
569c5348aecSYe Luo     Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device);
570c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n"))
5713de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
5723de4cd12SGeorge Rokos 
5734031bb98SShilei Tian     Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
5744031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
5754031bb98SShilei Tian       return OFFLOAD_FAIL;
576a5153dbcSJohannes Doerfert 
577feed674dSShilei Tian     // Initialize stream pool
5784031bb98SShilei Tian     if (!StreamManager->initializeDeviceStreamPool(DeviceId))
5794031bb98SShilei Tian       return OFFLOAD_FAIL;
580a5153dbcSJohannes Doerfert 
581bb51d398SJonas Hahnfeld     // Query attributes to determine number of threads/block and blocks/grid.
5824031bb98SShilei Tian     int MaxGridDimX;
5834031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
5844031bb98SShilei Tian                                Device);
5854031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
5864031bb98SShilei Tian       DP("Error getting max grid dimension, use default value %d\n",
5874031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
5884031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
5894031bb98SShilei Tian     } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) {
5904031bb98SShilei Tian       DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
5914031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
5923de4cd12SGeorge Rokos     } else {
5933de4cd12SGeorge Rokos       DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping "
594bb51d398SJonas Hahnfeld          "at the hard limit\n",
5954031bb98SShilei Tian          MaxGridDimX, DeviceRTLTy::HardTeamLimit);
5964031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit;
5973de4cd12SGeorge Rokos     }
5983de4cd12SGeorge Rokos 
599bb51d398SJonas Hahnfeld     // We are only exploiting threads along the x axis.
6004031bb98SShilei Tian     int MaxBlockDimX;
6014031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxBlockDimX,
6024031bb98SShilei Tian                                CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
6034031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
6044031bb98SShilei Tian       DP("Error getting max block dimension, use default value %d\n",
6054031bb98SShilei Tian          DeviceRTLTy::DefaultNumThreads);
6064031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
607422adaa8SJoseph Huber     } else {
6084031bb98SShilei Tian       DP("Using %d CUDA threads per block\n", MaxBlockDimX);
6094031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
610422adaa8SJoseph Huber 
611422adaa8SJoseph Huber       if (EnvTeamThreadLimit > 0 &&
612422adaa8SJoseph Huber           DeviceData[DeviceId].ThreadsPerBlock > EnvTeamThreadLimit) {
613422adaa8SJoseph Huber         DP("Max CUDA threads per block %d exceeds the thread limit %d set by "
614422adaa8SJoseph Huber            "OMP_TEAMS_THREAD_LIMIT, capping at the limit\n",
615422adaa8SJoseph Huber            DeviceData[DeviceId].ThreadsPerBlock, EnvTeamThreadLimit);
616422adaa8SJoseph Huber         DeviceData[DeviceId].ThreadsPerBlock = EnvTeamThreadLimit;
617422adaa8SJoseph Huber       }
618422adaa8SJoseph Huber       if (DeviceData[DeviceId].ThreadsPerBlock > DeviceRTLTy::HardThreadLimit) {
6194031bb98SShilei Tian         DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
6204031bb98SShilei Tian            "capping at the hard limit\n",
621422adaa8SJoseph Huber            DeviceData[DeviceId].ThreadsPerBlock, DeviceRTLTy::HardThreadLimit);
6224031bb98SShilei Tian         DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
6233de4cd12SGeorge Rokos       }
624422adaa8SJoseph Huber     }
6253de4cd12SGeorge Rokos 
6264031bb98SShilei Tian     // Get and set warp size
6274031bb98SShilei Tian     int WarpSize;
6284031bb98SShilei Tian     Err =
6294031bb98SShilei Tian         cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
6304031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
6314031bb98SShilei Tian       DP("Error getting warp size, assume default value 32\n");
6324031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = 32;
633bb51d398SJonas Hahnfeld     } else {
6344031bb98SShilei Tian       DP("Using warp size %d\n", WarpSize);
6354031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = WarpSize;
6363de4cd12SGeorge Rokos     }
6373de4cd12SGeorge Rokos 
6383de4cd12SGeorge Rokos     // Adjust teams to the env variables
6394031bb98SShilei Tian     if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
6403de4cd12SGeorge Rokos       DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
6414031bb98SShilei Tian          EnvTeamLimit);
6424031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
6433de4cd12SGeorge Rokos     }
6443de4cd12SGeorge Rokos 
645119a9ea1SJoseph Huber     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
646ae209397SJoseph Huber          "Device supports up to %d CUDA blocks and %d threads with a "
647ae209397SJoseph Huber          "warp size of %d\n",
648ae209397SJoseph Huber          DeviceData[DeviceId].BlocksPerGrid,
649ae209397SJoseph Huber          DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize);
6503de4cd12SGeorge Rokos 
6513de4cd12SGeorge Rokos     // Set default number of teams
6524031bb98SShilei Tian     if (EnvNumTeams > 0) {
6533de4cd12SGeorge Rokos       DP("Default number of teams set according to environment %d\n",
6544031bb98SShilei Tian          EnvNumTeams);
6554031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = EnvNumTeams;
6563de4cd12SGeorge Rokos     } else {
6574031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
6583de4cd12SGeorge Rokos       DP("Default number of teams set according to library's default %d\n",
6594031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
6603de4cd12SGeorge Rokos     }
6614031bb98SShilei Tian 
6624031bb98SShilei Tian     if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
6633de4cd12SGeorge Rokos       DP("Default number of teams exceeds device limit, capping at %d\n",
6644031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
6654031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
6663de4cd12SGeorge Rokos     }
6673de4cd12SGeorge Rokos 
6683de4cd12SGeorge Rokos     // Set default number of threads
6694031bb98SShilei Tian     DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
6703de4cd12SGeorge Rokos     DP("Default number of threads set according to library's default %d\n",
6714031bb98SShilei Tian        DeviceRTLTy::DefaultNumThreads);
6724031bb98SShilei Tian     if (DeviceData[DeviceId].NumThreads >
6734031bb98SShilei Tian         DeviceData[DeviceId].ThreadsPerBlock) {
6743de4cd12SGeorge Rokos       DP("Default number of threads exceeds device limit, capping at %d\n",
6754031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
6764031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].ThreadsPerBlock;
6773de4cd12SGeorge Rokos     }
6783de4cd12SGeorge Rokos 
6793de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
6803de4cd12SGeorge Rokos   }
6813de4cd12SGeorge Rokos 
6824031bb98SShilei Tian   __tgt_target_table *loadBinary(const int DeviceId,
6834031bb98SShilei Tian                                  const __tgt_device_image *Image) {
6844031bb98SShilei Tian     // Set the context we are using
6854031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
6864031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
6874031bb98SShilei Tian       return nullptr;
6883de4cd12SGeorge Rokos 
6893de4cd12SGeorge Rokos     // Clear the offload table as we are going to create a new one.
6904031bb98SShilei Tian     clearOffloadEntriesTable(DeviceId);
6913de4cd12SGeorge Rokos 
6923de4cd12SGeorge Rokos     // Create the module and extract the function pointers.
6934031bb98SShilei Tian     CUmodule Module;
6944031bb98SShilei Tian     DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
6954031bb98SShilei Tian     Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
6964031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
6974031bb98SShilei Tian       return nullptr;
6983de4cd12SGeorge Rokos 
6993de4cd12SGeorge Rokos     DP("CUDA module successfully loaded!\n");
7004031bb98SShilei Tian 
7014031bb98SShilei Tian     Modules.push_back(Module);
7023de4cd12SGeorge Rokos 
7033de4cd12SGeorge Rokos     // Find the symbols in the module by name.
7044031bb98SShilei Tian     const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
7054031bb98SShilei Tian     const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
7063de4cd12SGeorge Rokos 
7075272d29eSJohannes Doerfert     std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList;
7084031bb98SShilei Tian     for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
7094031bb98SShilei Tian       if (!E->addr) {
7104031bb98SShilei Tian         // We return nullptr when something like this happens, the host should
7114031bb98SShilei Tian         // have always something in the address to uniquely identify the target
7124031bb98SShilei Tian         // region.
7134031bb98SShilei Tian         DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
7144031bb98SShilei Tian         return nullptr;
7153de4cd12SGeorge Rokos       }
7163de4cd12SGeorge Rokos 
7174031bb98SShilei Tian       if (E->size) {
7184031bb98SShilei Tian         __tgt_offload_entry Entry = *E;
7194031bb98SShilei Tian         CUdeviceptr CUPtr;
7204031bb98SShilei Tian         size_t CUSize;
72195f0d1edSJon Chesterfield         Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name);
7224031bb98SShilei Tian         // We keep this style here because we need the name
7234031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
7242ce16810SJoseph Huber           REPORT("Loading global '%s' Failed\n", E->name);
7254031bb98SShilei Tian           CUDA_ERR_STRING(Err);
7264031bb98SShilei Tian           return nullptr;
7273de4cd12SGeorge Rokos         }
7283de4cd12SGeorge Rokos 
7294031bb98SShilei Tian         if (CUSize != E->size) {
7304031bb98SShilei Tian           DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
7314031bb98SShilei Tian              CUSize, E->size);
7324031bb98SShilei Tian           return nullptr;
7333de4cd12SGeorge Rokos         }
7343de4cd12SGeorge Rokos 
7353de4cd12SGeorge Rokos         DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
7364031bb98SShilei Tian            DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
7374031bb98SShilei Tian 
7384031bb98SShilei Tian         Entry.addr = (void *)(CUPtr);
7393de4cd12SGeorge Rokos 
740aace6d28SGheorghe-Teodor Bercea         // Note: In the current implementation declare target variables
741aace6d28SGheorghe-Teodor Bercea         // can either be link or to. This means that once unified
742aace6d28SGheorghe-Teodor Bercea         // memory is activated via the requires directive, the variable
743aace6d28SGheorghe-Teodor Bercea         // can be used directly from the host in both cases.
744aace6d28SGheorghe-Teodor Bercea         // TODO: when variables types other than to or link are added,
7454c6a098aSKazuaki Ishizaki         // the below condition should be changed to explicitly
746aace6d28SGheorghe-Teodor Bercea         // check for to and link variables types:
7474031bb98SShilei Tian         // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
7484031bb98SShilei Tian         // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
7494031bb98SShilei Tian         if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
750aace6d28SGheorghe-Teodor Bercea           // If unified memory is present any target link or to variables
751c5fe030cSGheorghe-Teodor Bercea           // can access host addresses directly. There is no longer a
752c5fe030cSGheorghe-Teodor Bercea           // need for device copies.
75395f0d1edSJon Chesterfield           cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *));
7544031bb98SShilei Tian           DP("Copy linked variable host address (" DPxMOD
7554031bb98SShilei Tian              ") to device address (" DPxMOD ")\n",
7564031bb98SShilei Tian              DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
757c5fe030cSGheorghe-Teodor Bercea         }
758c5fe030cSGheorghe-Teodor Bercea 
7594031bb98SShilei Tian         addOffloadEntry(DeviceId, Entry);
7603de4cd12SGeorge Rokos 
7613de4cd12SGeorge Rokos         continue;
7623de4cd12SGeorge Rokos       }
7633de4cd12SGeorge Rokos 
7644031bb98SShilei Tian       CUfunction Func;
7654031bb98SShilei Tian       Err = cuModuleGetFunction(&Func, Module, E->name);
7664031bb98SShilei Tian       // We keep this style here because we need the name
7674031bb98SShilei Tian       if (Err != CUDA_SUCCESS) {
7682ce16810SJoseph Huber         REPORT("Loading '%s' Failed\n", E->name);
7694031bb98SShilei Tian         CUDA_ERR_STRING(Err);
7704031bb98SShilei Tian         return nullptr;
7713de4cd12SGeorge Rokos       }
7723de4cd12SGeorge Rokos 
7733de4cd12SGeorge Rokos       DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
7744031bb98SShilei Tian          DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
7753de4cd12SGeorge Rokos 
7763de4cd12SGeorge Rokos       // default value GENERIC (in case symbol is missing from cubin file)
7773de4cd12SGeorge Rokos       int8_t ExecModeVal = ExecutionModeType::GENERIC;
7784031bb98SShilei Tian       std::string ExecModeNameStr(E->name);
7793de4cd12SGeorge Rokos       ExecModeNameStr += "_exec_mode";
7803de4cd12SGeorge Rokos       const char *ExecModeName = ExecModeNameStr.c_str();
7813de4cd12SGeorge Rokos 
7823de4cd12SGeorge Rokos       CUdeviceptr ExecModePtr;
7834031bb98SShilei Tian       size_t CUSize;
78495f0d1edSJon Chesterfield       Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName);
7854031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
7864031bb98SShilei Tian         if (CUSize != sizeof(int8_t)) {
7873de4cd12SGeorge Rokos           DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
7884031bb98SShilei Tian              ExecModeName, CUSize, sizeof(int8_t));
7894031bb98SShilei Tian           return nullptr;
7903de4cd12SGeorge Rokos         }
7913de4cd12SGeorge Rokos 
79295f0d1edSJon Chesterfield         Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize);
7934031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
7942ce16810SJoseph Huber           REPORT("Error when copying data from device to host. Pointers: "
7953de4cd12SGeorge Rokos                  "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
7964031bb98SShilei Tian                  DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
7974031bb98SShilei Tian           CUDA_ERR_STRING(Err);
7984031bb98SShilei Tian           return nullptr;
7993de4cd12SGeorge Rokos         }
8003de4cd12SGeorge Rokos 
8017d576392SJoseph Huber         if (ExecModeVal < 0 || ExecModeVal > 2) {
8023de4cd12SGeorge Rokos           DP("Error wrong exec_mode value specified in cubin file: %d\n",
8033de4cd12SGeorge Rokos              ExecModeVal);
8044031bb98SShilei Tian           return nullptr;
8053de4cd12SGeorge Rokos         }
8063de4cd12SGeorge Rokos       } else {
8072ce16810SJoseph Huber         REPORT("Loading global exec_mode '%s' - symbol missing, using default "
8084031bb98SShilei Tian                "value GENERIC (1)\n",
8094031bb98SShilei Tian                ExecModeName);
8104031bb98SShilei Tian         CUDA_ERR_STRING(Err);
8113de4cd12SGeorge Rokos       }
8123de4cd12SGeorge Rokos 
8134031bb98SShilei Tian       KernelsList.emplace_back(Func, ExecModeVal);
8143de4cd12SGeorge Rokos 
8154031bb98SShilei Tian       __tgt_offload_entry Entry = *E;
8164031bb98SShilei Tian       Entry.addr = &KernelsList.back();
8174031bb98SShilei Tian       addOffloadEntry(DeviceId, Entry);
8183de4cd12SGeorge Rokos     }
8193de4cd12SGeorge Rokos 
820e1c7a46dSGuansong Zhang     // send device environment data to the device
821e1c7a46dSGuansong Zhang     {
8224031bb98SShilei Tian       omptarget_device_environmentTy DeviceEnv{0};
823e1c7a46dSGuansong Zhang 
824e1c7a46dSGuansong Zhang #ifdef OMPTARGET_DEBUG
8254031bb98SShilei Tian       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
8264031bb98SShilei Tian         DeviceEnv.debug_level = std::stoi(EnvStr);
827e1c7a46dSGuansong Zhang #endif
828e1c7a46dSGuansong Zhang 
8294031bb98SShilei Tian       const char *DeviceEnvName = "omptarget_device_environment";
8304031bb98SShilei Tian       CUdeviceptr DeviceEnvPtr;
8314031bb98SShilei Tian       size_t CUSize;
832e1c7a46dSGuansong Zhang 
83395f0d1edSJon Chesterfield       Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
8344031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
8354031bb98SShilei Tian         if (CUSize != sizeof(DeviceEnv)) {
8362ce16810SJoseph Huber           REPORT(
8372ce16810SJoseph Huber               "Global device_environment '%s' - size mismatch (%zu != %zu)\n",
8384031bb98SShilei Tian               DeviceEnvName, CUSize, sizeof(int32_t));
8394031bb98SShilei Tian           CUDA_ERR_STRING(Err);
8404031bb98SShilei Tian           return nullptr;
841e1c7a46dSGuansong Zhang         }
842e1c7a46dSGuansong Zhang 
84395f0d1edSJon Chesterfield         Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
8444031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
8452ce16810SJoseph Huber           REPORT("Error when copying data from host to device. Pointers: "
846e1c7a46dSGuansong Zhang                  "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
8474031bb98SShilei Tian                  DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
8484031bb98SShilei Tian           CUDA_ERR_STRING(Err);
8494031bb98SShilei Tian           return nullptr;
850e1c7a46dSGuansong Zhang         }
851e1c7a46dSGuansong Zhang 
8524031bb98SShilei Tian         DP("Sending global device environment data %zu bytes\n", CUSize);
853e1c7a46dSGuansong Zhang       } else {
8544031bb98SShilei Tian         DP("Finding global device environment '%s' - symbol missing.\n",
8554031bb98SShilei Tian            DeviceEnvName);
8564031bb98SShilei Tian         DP("Continue, considering this is a device RTL which does not accept "
8574031bb98SShilei Tian            "environment setting.\n");
858e1c7a46dSGuansong Zhang       }
859e1c7a46dSGuansong Zhang     }
860e1c7a46dSGuansong Zhang 
8614031bb98SShilei Tian     return getOffloadEntriesTable(DeviceId);
8623de4cd12SGeorge Rokos   }
8633de4cd12SGeorge Rokos 
864a15f8589SJoseph Huber   void *dataAlloc(const int DeviceId, const int64_t Size,
865a15f8589SJoseph Huber                   const TargetAllocTy Kind) {
866a15f8589SJoseph Huber     switch (Kind) {
867a15f8589SJoseph Huber     case TARGET_ALLOC_DEFAULT:
868a15f8589SJoseph Huber     case TARGET_ALLOC_DEVICE:
8690871d6d5SShilei Tian       if (UseMemoryManager)
8700871d6d5SShilei Tian         return MemoryManagers[DeviceId]->allocate(Size, nullptr);
871a15f8589SJoseph Huber       else
872a15f8589SJoseph Huber         return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
873a15f8589SJoseph Huber     case TARGET_ALLOC_HOST:
874a15f8589SJoseph Huber     case TARGET_ALLOC_SHARED:
875a15f8589SJoseph Huber       return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
876a15f8589SJoseph Huber     }
8774031bb98SShilei Tian 
878a15f8589SJoseph Huber     REPORT("Invalid target data allocation kind or requested allocator not "
879a15f8589SJoseph Huber            "implemented yet\n");
880a15f8589SJoseph Huber 
881a15f8589SJoseph Huber     return nullptr;
8823de4cd12SGeorge Rokos   }
8833de4cd12SGeorge Rokos 
8844031bb98SShilei Tian   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
8855449fbb5SJohannes Doerfert                  const int64_t Size, __tgt_async_info *AsyncInfo) const {
8865449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
8873de4cd12SGeorge Rokos 
8884031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
8894031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
8903de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
8913de4cd12SGeorge Rokos 
8925449fbb5SJohannes Doerfert     CUstream Stream = getStream(DeviceId, AsyncInfo);
8933de4cd12SGeorge Rokos 
89495f0d1edSJon Chesterfield     Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
8954031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
89629338459SJoseph Huber       DP("Error when copying data from host to device. Pointers: host "
8972ce16810SJoseph Huber          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
8984031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
8994031bb98SShilei Tian       CUDA_ERR_STRING(Err);
9003de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
9013de4cd12SGeorge Rokos     }
9023de4cd12SGeorge Rokos 
9033de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
9043de4cd12SGeorge Rokos   }
9053de4cd12SGeorge Rokos 
9064031bb98SShilei Tian   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
9075449fbb5SJohannes Doerfert                    const int64_t Size, __tgt_async_info *AsyncInfo) const {
9085449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
9094031bb98SShilei Tian 
9104031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
9114031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
91203ff643dSShilei Tian       return OFFLOAD_FAIL;
91303ff643dSShilei Tian 
9145449fbb5SJohannes Doerfert     CUstream Stream = getStream(DeviceId, AsyncInfo);
91503ff643dSShilei Tian 
91695f0d1edSJon Chesterfield     Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
9174031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
91829338459SJoseph Huber       DP("Error when copying data from device to host. Pointers: host "
9192ce16810SJoseph Huber          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
9204031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
9214031bb98SShilei Tian       CUDA_ERR_STRING(Err);
9223de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
9233de4cd12SGeorge Rokos     }
9243de4cd12SGeorge Rokos 
9254031bb98SShilei Tian     return OFFLOAD_SUCCESS;
9264031bb98SShilei Tian   }
9274031bb98SShilei Tian 
928a014fbbcSShilei Tian   int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
9295449fbb5SJohannes Doerfert                    int64_t Size, __tgt_async_info *AsyncInfo) const {
9305449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
931a014fbbcSShilei Tian 
932a014fbbcSShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context);
933a014fbbcSShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
934a014fbbcSShilei Tian       return OFFLOAD_FAIL;
935a014fbbcSShilei Tian 
9365449fbb5SJohannes Doerfert     CUstream Stream = getStream(SrcDevId, AsyncInfo);
937a014fbbcSShilei Tian 
938a014fbbcSShilei Tian     // If they are two devices, we try peer to peer copy first
939a014fbbcSShilei Tian     if (SrcDevId != DstDevId) {
940a014fbbcSShilei Tian       int CanAccessPeer = 0;
941a014fbbcSShilei Tian       Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
942a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
9432ce16810SJoseph Huber         REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
944a014fbbcSShilei Tian                ", dst = %" PRId32 "\n",
945a014fbbcSShilei Tian                SrcDevId, DstDevId);
946a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
947a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
948a014fbbcSShilei Tian       }
949a014fbbcSShilei Tian 
950a014fbbcSShilei Tian       if (!CanAccessPeer) {
951a014fbbcSShilei Tian         DP("P2P memcpy not supported so fall back to D2D memcpy");
952a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
953a014fbbcSShilei Tian       }
954a014fbbcSShilei Tian 
955a014fbbcSShilei Tian       Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
956a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
9572ce16810SJoseph Huber         REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
958a014fbbcSShilei Tian                ", dst = %" PRId32 "\n",
959a014fbbcSShilei Tian                SrcDevId, DstDevId);
960a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
961a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
962a014fbbcSShilei Tian       }
963a014fbbcSShilei Tian 
964a014fbbcSShilei Tian       Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
965a014fbbcSShilei Tian                               (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context,
966a014fbbcSShilei Tian                               Size, Stream);
967a014fbbcSShilei Tian       if (Err == CUDA_SUCCESS)
968a014fbbcSShilei Tian         return OFFLOAD_SUCCESS;
969a014fbbcSShilei Tian 
97029338459SJoseph Huber       DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
97129338459SJoseph Huber          ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32 "\n",
97245bb073dSYe Luo          DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
973a014fbbcSShilei Tian       CUDA_ERR_STRING(Err);
974a014fbbcSShilei Tian     }
975a014fbbcSShilei Tian 
976a014fbbcSShilei Tian     return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
977a014fbbcSShilei Tian   }
978a014fbbcSShilei Tian 
9790871d6d5SShilei Tian   int dataDelete(const int DeviceId, void *TgtPtr) {
9800871d6d5SShilei Tian     if (UseMemoryManager)
9810871d6d5SShilei Tian       return MemoryManagers[DeviceId]->free(TgtPtr);
9824031bb98SShilei Tian 
9830871d6d5SShilei Tian     return DeviceAllocators[DeviceId].free(TgtPtr);
9844031bb98SShilei Tian   }
9854031bb98SShilei Tian 
986aa27cfc1SJohannes Doerfert   int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
987aa27cfc1SJohannes Doerfert                           ptrdiff_t *TgtOffsets, const int ArgNum,
988aa27cfc1SJohannes Doerfert                           const int TeamNum, const int ThreadLimit,
9894031bb98SShilei Tian                           const unsigned int LoopTripCount,
9904031bb98SShilei Tian                           __tgt_async_info *AsyncInfo) const {
9914031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
9924031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
9934031bb98SShilei Tian       return OFFLOAD_FAIL;
9944031bb98SShilei Tian 
9953de4cd12SGeorge Rokos     // All args are references.
9964031bb98SShilei Tian     std::vector<void *> Args(ArgNum);
9974031bb98SShilei Tian     std::vector<void *> Ptrs(ArgNum);
9983de4cd12SGeorge Rokos 
9994031bb98SShilei Tian     for (int I = 0; I < ArgNum; ++I) {
10004031bb98SShilei Tian       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
10014031bb98SShilei Tian       Args[I] = &Ptrs[I];
10021546d319SGeorge Rokos     }
10033de4cd12SGeorge Rokos 
1004aa27cfc1SJohannes Doerfert     KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
10053de4cd12SGeorge Rokos 
1006aa27cfc1SJohannes Doerfert     int CudaThreadsPerBlock;
10074031bb98SShilei Tian     if (ThreadLimit > 0) {
10084031bb98SShilei Tian       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
10094031bb98SShilei Tian       CudaThreadsPerBlock = ThreadLimit;
10103de4cd12SGeorge Rokos       // Add master warp if necessary
10113de4cd12SGeorge Rokos       if (KernelInfo->ExecutionMode == GENERIC) {
10124031bb98SShilei Tian         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
10134031bb98SShilei Tian         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
10143de4cd12SGeorge Rokos       }
1015c13df8e5SGeorge Rokos     } else {
1016c13df8e5SGeorge Rokos       DP("Setting CUDA threads per block to default %d\n",
10174031bb98SShilei Tian          DeviceData[DeviceId].NumThreads);
10184031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
1019c13df8e5SGeorge Rokos     }
10203de4cd12SGeorge Rokos 
10214031bb98SShilei Tian     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
10223de4cd12SGeorge Rokos       DP("Threads per block capped at device limit %d\n",
10234031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
10244031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
10253de4cd12SGeorge Rokos     }
10263de4cd12SGeorge Rokos 
1027aa27cfc1SJohannes Doerfert     if (!KernelInfo->MaxThreadsPerBlock) {
1028aa27cfc1SJohannes Doerfert       Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
10294031bb98SShilei Tian                                CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
10304031bb98SShilei Tian                                KernelInfo->Func);
1031aa27cfc1SJohannes Doerfert       if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
1032aa27cfc1SJohannes Doerfert         return OFFLOAD_FAIL;
1033aa27cfc1SJohannes Doerfert     }
1034aa27cfc1SJohannes Doerfert 
1035aa27cfc1SJohannes Doerfert     if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
1036aa27cfc1SJohannes Doerfert       DP("Threads per block capped at kernel limit %d\n",
1037aa27cfc1SJohannes Doerfert          KernelInfo->MaxThreadsPerBlock);
1038aa27cfc1SJohannes Doerfert       CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
10393de4cd12SGeorge Rokos     }
10403de4cd12SGeorge Rokos 
10414031bb98SShilei Tian     unsigned int CudaBlocksPerGrid;
10424031bb98SShilei Tian     if (TeamNum <= 0) {
10434031bb98SShilei Tian       if (LoopTripCount > 0 && EnvNumTeams < 0) {
1044c13df8e5SGeorge Rokos         if (KernelInfo->ExecutionMode == SPMD) {
10454031bb98SShilei Tian           // We have a combined construct, i.e. `target teams distribute
10464031bb98SShilei Tian           // parallel for [simd]`. We launch so many teams so that each thread
10474031bb98SShilei Tian           // will execute one iteration of the loop. round up to the nearest
10484031bb98SShilei Tian           // integer
10494031bb98SShilei Tian           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
10507d576392SJoseph Huber         } else if (KernelInfo->ExecutionMode == GENERIC) {
1051c13df8e5SGeorge Rokos           // If we reach this point, then we have a non-combined construct, i.e.
1052c13df8e5SGeorge Rokos           // `teams distribute` with a nested `parallel for` and each team is
1053c13df8e5SGeorge Rokos           // assigned one iteration of the `distribute` loop. E.g.:
1054c13df8e5SGeorge Rokos           //
1055c13df8e5SGeorge Rokos           // #pragma omp target teams distribute
1056c13df8e5SGeorge Rokos           // for(...loop_tripcount...) {
1057c13df8e5SGeorge Rokos           //   #pragma omp parallel for
1058c13df8e5SGeorge Rokos           //   for(...) {}
1059c13df8e5SGeorge Rokos           // }
1060c13df8e5SGeorge Rokos           //
1061c13df8e5SGeorge Rokos           // Threads within a team will execute the iterations of the `parallel`
1062c13df8e5SGeorge Rokos           // loop.
10634031bb98SShilei Tian           CudaBlocksPerGrid = LoopTripCount;
10647d576392SJoseph Huber         } else if (KernelInfo->ExecutionMode == SPMD_GENERIC) {
10657d576392SJoseph Huber           // If we reach this point, then we are executing a kernel that was
10667d576392SJoseph Huber           // transformed from Generic-mode to SPMD-mode. This kernel has
10677d576392SJoseph Huber           // SPMD-mode execution, but needs its blocks to be scheduled
10687d576392SJoseph Huber           // differently because the current loop trip count only applies to the
10697d576392SJoseph Huber           // `teams distribute` region and will create var too few blocks using
10707d576392SJoseph Huber           // the regular SPMD-mode method.
10717d576392SJoseph Huber           CudaBlocksPerGrid = LoopTripCount;
1072*a158d366SJoseph Huber         } else {
1073*a158d366SJoseph Huber           REPORT("Unknown execution mode: %d\n", KernelInfo->ExecutionMode);
1074*a158d366SJoseph Huber           return OFFLOAD_FAIL;
1075c13df8e5SGeorge Rokos         }
107645bb073dSYe Luo         DP("Using %d teams due to loop trip count %" PRIu32
10774031bb98SShilei Tian            " and number of threads per block %d\n",
10784031bb98SShilei Tian            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
10793de4cd12SGeorge Rokos       } else {
10804031bb98SShilei Tian         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
10814031bb98SShilei Tian         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
10823de4cd12SGeorge Rokos       }
10834031bb98SShilei Tian     } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) {
10843de4cd12SGeorge Rokos       DP("Capping number of teams to team limit %d\n",
10854031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
10864031bb98SShilei Tian       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
10873de4cd12SGeorge Rokos     } else {
10884031bb98SShilei Tian       DP("Using requested number of teams %d\n", TeamNum);
10894031bb98SShilei Tian       CudaBlocksPerGrid = TeamNum;
10903de4cd12SGeorge Rokos     }
10913de4cd12SGeorge Rokos 
1092119a9ea1SJoseph Huber     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
1093ae209397SJoseph Huber          "Launching kernel %s with %d blocks and %d threads in %s "
1094ae209397SJoseph Huber          "mode\n",
1095ae209397SJoseph Huber          (getOffloadEntry(DeviceId, TgtEntryPtr))
1096ae209397SJoseph Huber              ? getOffloadEntry(DeviceId, TgtEntryPtr)->name
1097ae209397SJoseph Huber              : "(null)",
1098ae209397SJoseph Huber          CudaBlocksPerGrid, CudaThreadsPerBlock,
10997d576392SJoseph Huber          (KernelInfo->ExecutionMode != SPMD
11007d576392SJoseph Huber              ? (KernelInfo->ExecutionMode == GENERIC ? "Generic" : "SPMD-Generic")
11017d576392SJoseph Huber              : "SPMD"));
11023de4cd12SGeorge Rokos 
11034031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfo);
11044031bb98SShilei Tian     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
11054031bb98SShilei Tian                          /* gridDimZ */ 1, CudaThreadsPerBlock,
11064031bb98SShilei Tian                          /* blockDimY */ 1, /* blockDimZ */ 1,
11074031bb98SShilei Tian                          /* sharedMemBytes */ 0, Stream, &Args[0], nullptr);
11084031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
11094031bb98SShilei Tian       return OFFLOAD_FAIL;
11104031bb98SShilei Tian 
11114031bb98SShilei Tian     DP("Launch of entry point at " DPxMOD " successful!\n",
11124031bb98SShilei Tian        DPxPTR(TgtEntryPtr));
11134031bb98SShilei Tian 
11144031bb98SShilei Tian     return OFFLOAD_SUCCESS;
11154031bb98SShilei Tian   }
11164031bb98SShilei Tian 
11175449fbb5SJohannes Doerfert   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfo) const {
11185449fbb5SJohannes Doerfert     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
11194031bb98SShilei Tian     CUresult Err = cuStreamSynchronize(Stream);
11203de4cd12SGeorge Rokos 
11214031bb98SShilei Tian     // Once the stream is synchronized, return it to stream pool and reset
11225449fbb5SJohannes Doerfert     // AsyncInfo. This is to make sure the synchronization only works for its
11234031bb98SShilei Tian     // own tasks.
11245449fbb5SJohannes Doerfert     StreamManager->returnStream(DeviceId,
11255449fbb5SJohannes Doerfert                                 reinterpret_cast<CUstream>(AsyncInfo->Queue));
11265449fbb5SJohannes Doerfert     AsyncInfo->Queue = nullptr;
11273de4cd12SGeorge Rokos 
112816064e71SJoseph Huber     if (Err != CUDA_SUCCESS) {
112929338459SJoseph Huber       DP("Error when synchronizing stream. stream = " DPxMOD
113016064e71SJoseph Huber          ", async info ptr = " DPxMOD "\n",
113116064e71SJoseph Huber          DPxPTR(Stream), DPxPTR(AsyncInfo));
113216064e71SJoseph Huber       CUDA_ERR_STRING(Err);
113316064e71SJoseph Huber     }
113416064e71SJoseph Huber     return (Err == CUDA_SUCCESS) ? OFFLOAD_SUCCESS : OFFLOAD_FAIL;
11353de4cd12SGeorge Rokos   }
11364031bb98SShilei Tian };
11374031bb98SShilei Tian 
11384031bb98SShilei Tian DeviceRTLTy DeviceRTL;
11394031bb98SShilei Tian } // namespace
11404031bb98SShilei Tian 
11414031bb98SShilei Tian // Exposed library API function
11424031bb98SShilei Tian #ifdef __cplusplus
11434031bb98SShilei Tian extern "C" {
11444031bb98SShilei Tian #endif
11454031bb98SShilei Tian 
11464031bb98SShilei Tian int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
11474031bb98SShilei Tian   return elf_check_machine(image, /* EM_CUDA */ 190);
11484031bb98SShilei Tian }
11494031bb98SShilei Tian 
11504031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
11514031bb98SShilei Tian 
11524031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
115340470eb2SGeorge Rokos   DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
11544031bb98SShilei Tian   DeviceRTL.setRequiresFlag(RequiresFlags);
11554031bb98SShilei Tian   return RequiresFlags;
11564031bb98SShilei Tian }
11574031bb98SShilei Tian 
1158a014fbbcSShilei Tian int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) {
1159a014fbbcSShilei Tian   if (DeviceRTL.isValidDeviceId(src_dev_id) &&
1160a014fbbcSShilei Tian       DeviceRTL.isValidDeviceId(dst_dev_id))
1161a014fbbcSShilei Tian     return 1;
1162a014fbbcSShilei Tian 
1163a014fbbcSShilei Tian   return 0;
1164a014fbbcSShilei Tian }
1165a014fbbcSShilei Tian 
11664031bb98SShilei Tian int32_t __tgt_rtl_init_device(int32_t device_id) {
11674031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11684031bb98SShilei Tian 
11694031bb98SShilei Tian   return DeviceRTL.initDevice(device_id);
11704031bb98SShilei Tian }
11714031bb98SShilei Tian 
11724031bb98SShilei Tian __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
11734031bb98SShilei Tian                                           __tgt_device_image *image) {
11744031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11754031bb98SShilei Tian 
11764031bb98SShilei Tian   return DeviceRTL.loadBinary(device_id, image);
11774031bb98SShilei Tian }
11784031bb98SShilei Tian 
11792468fdd9SGeorge Rokos void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *,
11802468fdd9SGeorge Rokos                            int32_t kind) {
11814031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11824031bb98SShilei Tian 
1183a15f8589SJoseph Huber   return DeviceRTL.dataAlloc(device_id, size, (TargetAllocTy)kind);
11844031bb98SShilei Tian }
11854031bb98SShilei Tian 
11864031bb98SShilei Tian int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
11874031bb98SShilei Tian                               int64_t size) {
11884031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11894031bb98SShilei Tian 
11905449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
11914031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr,
11925449fbb5SJohannes Doerfert                                                  size, &AsyncInfo);
11934031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
11944031bb98SShilei Tian     return OFFLOAD_FAIL;
11954031bb98SShilei Tian 
11965449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
11974031bb98SShilei Tian }
11984031bb98SShilei Tian 
11994031bb98SShilei Tian int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr,
12004031bb98SShilei Tian                                     void *hst_ptr, int64_t size,
12014031bb98SShilei Tian                                     __tgt_async_info *async_info_ptr) {
12024031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
12034031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
12044031bb98SShilei Tian 
12054031bb98SShilei Tian   return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size,
12064031bb98SShilei Tian                               async_info_ptr);
12074031bb98SShilei Tian }
12084031bb98SShilei Tian 
12094031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
12104031bb98SShilei Tian                                 int64_t size) {
12114031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
12124031bb98SShilei Tian 
12135449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
12144031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr,
12155449fbb5SJohannes Doerfert                                                    size, &AsyncInfo);
12164031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
12174031bb98SShilei Tian     return OFFLOAD_FAIL;
12184031bb98SShilei Tian 
12195449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
12204031bb98SShilei Tian }
12214031bb98SShilei Tian 
12224031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr,
12234031bb98SShilei Tian                                       void *tgt_ptr, int64_t size,
12244031bb98SShilei Tian                                       __tgt_async_info *async_info_ptr) {
12254031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
12264031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
12274031bb98SShilei Tian 
12284031bb98SShilei Tian   return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size,
12294031bb98SShilei Tian                                 async_info_ptr);
12304031bb98SShilei Tian }
12314031bb98SShilei Tian 
1232a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr,
1233a014fbbcSShilei Tian                                       int dst_dev_id, void *dst_ptr,
1234a014fbbcSShilei Tian                                       int64_t size,
12355449fbb5SJohannes Doerfert                                       __tgt_async_info *AsyncInfo) {
1236a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1237a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
12385449fbb5SJohannes Doerfert   assert(AsyncInfo && "AsyncInfo is nullptr");
1239a014fbbcSShilei Tian 
1240a014fbbcSShilei Tian   return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size,
12415449fbb5SJohannes Doerfert                                 AsyncInfo);
1242a014fbbcSShilei Tian }
1243a014fbbcSShilei Tian 
1244a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr,
1245a014fbbcSShilei Tian                                 int32_t dst_dev_id, void *dst_ptr,
1246a014fbbcSShilei Tian                                 int64_t size) {
1247a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1248a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1249a014fbbcSShilei Tian 
12505449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
1251a014fbbcSShilei Tian   const int32_t rc = __tgt_rtl_data_exchange_async(
12525449fbb5SJohannes Doerfert       src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &AsyncInfo);
1253a014fbbcSShilei Tian   if (rc != OFFLOAD_SUCCESS)
1254a014fbbcSShilei Tian     return OFFLOAD_FAIL;
1255a014fbbcSShilei Tian 
12565449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(src_dev_id, &AsyncInfo);
1257a014fbbcSShilei Tian }
1258a014fbbcSShilei Tian 
12594031bb98SShilei Tian int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
12604031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
12614031bb98SShilei Tian 
12624031bb98SShilei Tian   return DeviceRTL.dataDelete(device_id, tgt_ptr);
12634031bb98SShilei Tian }
12644031bb98SShilei Tian 
12654031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
12664031bb98SShilei Tian                                          void **tgt_args,
12674031bb98SShilei Tian                                          ptrdiff_t *tgt_offsets,
12684031bb98SShilei Tian                                          int32_t arg_num, int32_t team_num,
12694031bb98SShilei Tian                                          int32_t thread_limit,
12704031bb98SShilei Tian                                          uint64_t loop_tripcount) {
12714031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
12724031bb98SShilei Tian 
12735449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
12744031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_team_region_async(
12754031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
12765449fbb5SJohannes Doerfert       thread_limit, loop_tripcount, &AsyncInfo);
12774031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
12784031bb98SShilei Tian     return OFFLOAD_FAIL;
12794031bb98SShilei Tian 
12805449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
12814031bb98SShilei Tian }
12824031bb98SShilei Tian 
12834031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async(
12844031bb98SShilei Tian     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
12854031bb98SShilei Tian     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
12864031bb98SShilei Tian     int32_t thread_limit, uint64_t loop_tripcount,
12874031bb98SShilei Tian     __tgt_async_info *async_info_ptr) {
12884031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
12894031bb98SShilei Tian 
12904031bb98SShilei Tian   return DeviceRTL.runTargetTeamRegion(
12914031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
12924031bb98SShilei Tian       thread_limit, loop_tripcount, async_info_ptr);
12934031bb98SShilei Tian }
12943de4cd12SGeorge Rokos 
12953de4cd12SGeorge Rokos int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
129632ed2927SShilei Tian                                     void **tgt_args, ptrdiff_t *tgt_offsets,
129703ff643dSShilei Tian                                     int32_t arg_num) {
12984031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
12994031bb98SShilei Tian 
13005449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
13014031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_region_async(
13025449fbb5SJohannes Doerfert       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &AsyncInfo);
130303ff643dSShilei Tian   if (rc != OFFLOAD_SUCCESS)
130403ff643dSShilei Tian     return OFFLOAD_FAIL;
130503ff643dSShilei Tian 
13065449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
130703ff643dSShilei Tian }
130803ff643dSShilei Tian 
130903ff643dSShilei Tian int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
131003ff643dSShilei Tian                                           void *tgt_entry_ptr, void **tgt_args,
131103ff643dSShilei Tian                                           ptrdiff_t *tgt_offsets,
131232ed2927SShilei Tian                                           int32_t arg_num,
13134031bb98SShilei Tian                                           __tgt_async_info *async_info_ptr) {
13144031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
13154031bb98SShilei Tian 
131603ff643dSShilei Tian   return __tgt_rtl_run_target_team_region_async(
13174031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
13184031bb98SShilei Tian       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
13194031bb98SShilei Tian       async_info_ptr);
132032ed2927SShilei Tian }
132132ed2927SShilei Tian 
13224031bb98SShilei Tian int32_t __tgt_rtl_synchronize(int32_t device_id,
13234031bb98SShilei Tian                               __tgt_async_info *async_info_ptr) {
13244031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
13254031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
13264031bb98SShilei Tian   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
132732ed2927SShilei Tian 
13284031bb98SShilei Tian   return DeviceRTL.synchronize(device_id, async_info_ptr);
13293de4cd12SGeorge Rokos }
13303de4cd12SGeorge Rokos 
13312b6f2008SJoseph Huber void __tgt_rtl_set_info_flag(uint32_t NewInfoLevel) {
133259b68490SJoseph Huber   std::atomic<uint32_t> &InfoLevel = getInfoLevelInternal();
13332b6f2008SJoseph Huber   InfoLevel.store(NewInfoLevel);
13342b6f2008SJoseph Huber }
13352b6f2008SJoseph Huber 
13363de4cd12SGeorge Rokos #ifdef __cplusplus
13373de4cd12SGeorge Rokos }
13383de4cd12SGeorge Rokos #endif
1339