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 
22*ae95ceebSJoseph Huber #include "Debug.h"
231546d319SGeorge Rokos #include "omptargetplugin.h"
243de4cd12SGeorge Rokos 
253de4cd12SGeorge Rokos #define TARGET_NAME CUDA
26*ae95ceebSJoseph Huber #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL"
2778769ec4SMichael Kruse 
2878769ec4SMichael Kruse // Utility for retrieving and printing CUDA error string.
29*ae95ceebSJoseph Huber #ifdef OMPTARGET_DEBUG
3078769ec4SMichael Kruse #define CUDA_ERR_STRING(err)                                                   \
3178769ec4SMichael Kruse   do {                                                                         \
32*ae95ceebSJoseph Huber     if (getDebugLevel() > 0) {                                                      \
3378769ec4SMichael Kruse       const char *errStr;                                                      \
3478769ec4SMichael Kruse       cuGetErrorString(err, &errStr);                                          \
35*ae95ceebSJoseph Huber       DP("CUDA error is: %s\n", errStr);                                       \
3678769ec4SMichael Kruse     }                                                                          \
3778769ec4SMichael Kruse   } while (false)
38b305d26bSSergey Dmitriev #else // OMPTARGET_DEBUG
3978769ec4SMichael Kruse #define CUDA_ERR_STRING(err) {}
40b305d26bSSergey Dmitriev #endif // OMPTARGET_DEBUG
413de4cd12SGeorge Rokos 
423de4cd12SGeorge Rokos #include "../../common/elf_common.c"
433de4cd12SGeorge Rokos 
443de4cd12SGeorge Rokos /// Keep entries table per device.
453de4cd12SGeorge Rokos struct FuncOrGblEntryTy {
463de4cd12SGeorge Rokos   __tgt_target_table Table;
473de4cd12SGeorge Rokos   std::vector<__tgt_offload_entry> Entries;
483de4cd12SGeorge Rokos };
493de4cd12SGeorge Rokos 
503de4cd12SGeorge Rokos enum ExecutionModeType {
51c13df8e5SGeorge Rokos   SPMD, // constructors, destructors,
52c13df8e5SGeorge Rokos   // combined constructs (`teams distribute parallel for [simd]`)
53c13df8e5SGeorge Rokos   GENERIC, // everything else
543de4cd12SGeorge Rokos   NONE
553de4cd12SGeorge Rokos };
563de4cd12SGeorge Rokos 
57dc34b1c9SRon Lieberman /// Use a single entity to encode a kernel and a set of flags.
583de4cd12SGeorge Rokos struct KernelTy {
593de4cd12SGeorge Rokos   CUfunction Func;
603de4cd12SGeorge Rokos 
613de4cd12SGeorge Rokos   // execution mode of kernel
623de4cd12SGeorge Rokos   // 0 - SPMD mode (without master warp)
633de4cd12SGeorge Rokos   // 1 - Generic mode (with master warp)
643de4cd12SGeorge Rokos   int8_t ExecutionMode;
653de4cd12SGeorge Rokos 
66aa27cfc1SJohannes Doerfert   /// Maximal number of threads per block for this kernel.
67aa27cfc1SJohannes Doerfert   int MaxThreadsPerBlock = 0;
68aa27cfc1SJohannes Doerfert 
693de4cd12SGeorge Rokos   KernelTy(CUfunction _Func, int8_t _ExecutionMode)
703de4cd12SGeorge Rokos       : Func(_Func), ExecutionMode(_ExecutionMode) {}
713de4cd12SGeorge Rokos };
723de4cd12SGeorge Rokos 
734c6a098aSKazuaki Ishizaki /// Device environment data
74feed674dSShilei Tian /// Manually sync with the deviceRTL side for now, move to a dedicated header
75feed674dSShilei Tian /// file later.
76e1c7a46dSGuansong Zhang struct omptarget_device_environmentTy {
77e1c7a46dSGuansong Zhang   int32_t debug_level;
78e1c7a46dSGuansong Zhang };
79e1c7a46dSGuansong Zhang 
80feed674dSShilei Tian namespace {
81feed674dSShilei Tian bool checkResult(CUresult Err, const char *ErrMsg) {
82feed674dSShilei Tian   if (Err == CUDA_SUCCESS)
83feed674dSShilei Tian     return true;
84feed674dSShilei Tian 
8545bb073dSYe Luo   DP("%s", ErrMsg);
86feed674dSShilei Tian   CUDA_ERR_STRING(Err);
87feed674dSShilei Tian   return false;
88feed674dSShilei Tian }
894031bb98SShilei Tian 
90a014fbbcSShilei Tian int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size,
91a014fbbcSShilei Tian                CUstream Stream) {
92a014fbbcSShilei Tian   CUresult Err =
93a014fbbcSShilei Tian       cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream);
94a014fbbcSShilei Tian 
95a014fbbcSShilei Tian   if (Err != CUDA_SUCCESS) {
96a014fbbcSShilei Tian     DP("Error when copying data from device to device. Pointers: src "
97a014fbbcSShilei Tian        "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n",
98a014fbbcSShilei Tian        DPxPTR(SrcPtr), DPxPTR(DstPtr), Size);
99a014fbbcSShilei Tian     CUDA_ERR_STRING(Err);
100a014fbbcSShilei Tian     return OFFLOAD_FAIL;
101a014fbbcSShilei Tian   }
102a014fbbcSShilei Tian 
103a014fbbcSShilei Tian   return OFFLOAD_SUCCESS;
104a014fbbcSShilei Tian }
105a014fbbcSShilei Tian 
1064031bb98SShilei Tian // Structure contains per-device data
1074031bb98SShilei Tian struct DeviceDataTy {
1085272d29eSJohannes Doerfert   /// List that contains all the kernels.
1095272d29eSJohannes Doerfert   std::list<KernelTy> KernelsList;
1105272d29eSJohannes Doerfert 
1114031bb98SShilei Tian   std::list<FuncOrGblEntryTy> FuncGblEntries;
1125272d29eSJohannes Doerfert 
1134031bb98SShilei Tian   CUcontext Context = nullptr;
1144031bb98SShilei Tian   // Device properties
1154031bb98SShilei Tian   int ThreadsPerBlock = 0;
1164031bb98SShilei Tian   int BlocksPerGrid = 0;
1174031bb98SShilei Tian   int WarpSize = 0;
1184031bb98SShilei Tian   // OpenMP properties
1194031bb98SShilei Tian   int NumTeams = 0;
1204031bb98SShilei Tian   int NumThreads = 0;
1214031bb98SShilei Tian };
122feed674dSShilei Tian 
123feed674dSShilei Tian class StreamManagerTy {
124feed674dSShilei Tian   int NumberOfDevices;
1254031bb98SShilei Tian   // The initial size of stream pool
1264031bb98SShilei Tian   int EnvNumInitialStreams;
127feed674dSShilei Tian   // Per-device stream mutex
128feed674dSShilei Tian   std::vector<std::unique_ptr<std::mutex>> StreamMtx;
129feed674dSShilei Tian   // Per-device stream Id indicates the next available stream in the pool
130feed674dSShilei Tian   std::vector<int> NextStreamId;
131feed674dSShilei Tian   // Per-device stream pool
132feed674dSShilei Tian   std::vector<std::vector<CUstream>> StreamPool;
1334031bb98SShilei Tian   // Reference to per-device data
1344031bb98SShilei Tian   std::vector<DeviceDataTy> &DeviceData;
135feed674dSShilei Tian 
136feed674dSShilei Tian   // If there is no CUstream left in the pool, we will resize the pool to
137feed674dSShilei Tian   // allocate more CUstream. This function should be called with device mutex,
138feed674dSShilei Tian   // and we do not resize to smaller one.
139feed674dSShilei Tian   void resizeStreamPool(const int DeviceId, const size_t NewSize) {
140feed674dSShilei Tian     std::vector<CUstream> &Pool = StreamPool[DeviceId];
141feed674dSShilei Tian     const size_t CurrentSize = Pool.size();
142feed674dSShilei Tian     assert(NewSize > CurrentSize && "new size is not larger than current size");
143feed674dSShilei Tian 
1444031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
1454031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) {
146feed674dSShilei Tian       // We will return if cannot switch to the right context in case of
147feed674dSShilei Tian       // creating bunch of streams that are not corresponding to the right
148feed674dSShilei Tian       // device. The offloading will fail later because selected CUstream is
149feed674dSShilei Tian       // nullptr.
150feed674dSShilei Tian       return;
151feed674dSShilei Tian     }
152feed674dSShilei Tian 
1534031bb98SShilei Tian     Pool.resize(NewSize, nullptr);
1544031bb98SShilei Tian 
155feed674dSShilei Tian     for (size_t I = CurrentSize; I < NewSize; ++I) {
1564031bb98SShilei Tian       checkResult(cuStreamCreate(&Pool[I], CU_STREAM_NON_BLOCKING),
1574031bb98SShilei Tian                   "Error returned from cuStreamCreate\n");
158feed674dSShilei Tian     }
159feed674dSShilei Tian   }
160feed674dSShilei Tian 
161feed674dSShilei Tian public:
1624031bb98SShilei Tian   StreamManagerTy(const int NumberOfDevices,
1634031bb98SShilei Tian                   std::vector<DeviceDataTy> &DeviceData)
1644031bb98SShilei Tian       : NumberOfDevices(NumberOfDevices), EnvNumInitialStreams(32),
1654031bb98SShilei Tian         DeviceData(DeviceData) {
166feed674dSShilei Tian     StreamPool.resize(NumberOfDevices);
167feed674dSShilei Tian     NextStreamId.resize(NumberOfDevices);
168feed674dSShilei Tian     StreamMtx.resize(NumberOfDevices);
169feed674dSShilei Tian 
1704031bb98SShilei Tian     if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS"))
1714031bb98SShilei Tian       EnvNumInitialStreams = std::stoi(EnvStr);
172feed674dSShilei Tian 
173feed674dSShilei Tian     // Initialize the next stream id
174feed674dSShilei Tian     std::fill(NextStreamId.begin(), NextStreamId.end(), 0);
175feed674dSShilei Tian 
176feed674dSShilei Tian     // Initialize stream mutex
177feed674dSShilei Tian     for (std::unique_ptr<std::mutex> &Ptr : StreamMtx)
178feed674dSShilei Tian       Ptr = std::make_unique<std::mutex>();
179feed674dSShilei Tian   }
180feed674dSShilei Tian 
181feed674dSShilei Tian   ~StreamManagerTy() {
182feed674dSShilei Tian     // Destroy streams
183feed674dSShilei Tian     for (int I = 0; I < NumberOfDevices; ++I) {
1844031bb98SShilei Tian       checkResult(cuCtxSetCurrent(DeviceData[I].Context),
1854031bb98SShilei Tian                   "Error returned from cuCtxSetCurrent\n");
186feed674dSShilei Tian 
187feed674dSShilei Tian       for (CUstream &S : StreamPool[I]) {
1884031bb98SShilei Tian         if (S)
1894031bb98SShilei Tian           checkResult(cuStreamDestroy(S),
1904031bb98SShilei Tian                       "Error returned from cuStreamDestroy\n");
191feed674dSShilei Tian       }
192feed674dSShilei Tian     }
193feed674dSShilei Tian   }
194feed674dSShilei Tian 
195feed674dSShilei Tian   // Get a CUstream from pool. Per-device next stream id always points to the
196feed674dSShilei Tian   // next available CUstream. That means, CUstreams [0, id-1] have been
197feed674dSShilei Tian   // assigned, and [id,] are still available. If there is no CUstream left, we
198feed674dSShilei Tian   // will ask more CUstreams from CUDA RT. Each time a CUstream is assigned,
199feed674dSShilei Tian   // the id will increase one.
200feed674dSShilei Tian   // xxxxxs+++++++++
201feed674dSShilei Tian   //      ^
202feed674dSShilei Tian   //      id
203feed674dSShilei Tian   // After assignment, the pool becomes the following and s is assigned.
204feed674dSShilei Tian   // xxxxxs+++++++++
205feed674dSShilei Tian   //       ^
206feed674dSShilei Tian   //       id
207feed674dSShilei Tian   CUstream getStream(const int DeviceId) {
208feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
209feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
210feed674dSShilei Tian     // No CUstream left in the pool, we need to request from CUDA RT
211feed674dSShilei Tian     if (Id == StreamPool[DeviceId].size()) {
212feed674dSShilei Tian       // By default we double the stream pool every time
213feed674dSShilei Tian       resizeStreamPool(DeviceId, Id * 2);
214feed674dSShilei Tian     }
215feed674dSShilei Tian     return StreamPool[DeviceId][Id++];
216feed674dSShilei Tian   }
217feed674dSShilei Tian 
218feed674dSShilei Tian   // Return a CUstream back to pool. As mentioned above, per-device next
219feed674dSShilei Tian   // stream is always points to the next available CUstream, so when we return
220feed674dSShilei Tian   // a CUstream, we need to first decrease the id, and then copy the CUstream
221feed674dSShilei Tian   // back.
222feed674dSShilei Tian   // It is worth noting that, the order of streams return might be different
223feed674dSShilei Tian   // from that they're assigned, that saying, at some point, there might be
224feed674dSShilei Tian   // two identical CUstreams.
225feed674dSShilei Tian   // xxax+a+++++
226feed674dSShilei Tian   //     ^
227feed674dSShilei Tian   //     id
228feed674dSShilei Tian   // However, it doesn't matter, because they're always on the two sides of
229feed674dSShilei Tian   // id. The left one will in the end be overwritten by another CUstream.
230feed674dSShilei Tian   // Therefore, after several execution, the order of pool might be different
231feed674dSShilei Tian   // from its initial state.
232feed674dSShilei Tian   void returnStream(const int DeviceId, CUstream Stream) {
233feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
234feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
235feed674dSShilei Tian     assert(Id > 0 && "Wrong stream ID");
236feed674dSShilei Tian     StreamPool[DeviceId][--Id] = Stream;
237feed674dSShilei Tian   }
238feed674dSShilei Tian 
2394031bb98SShilei Tian   bool initializeDeviceStreamPool(const int DeviceId) {
2404031bb98SShilei Tian     assert(StreamPool[DeviceId].empty() && "stream pool has been initialized");
2414031bb98SShilei Tian 
2424031bb98SShilei Tian     resizeStreamPool(DeviceId, EnvNumInitialStreams);
2434031bb98SShilei Tian 
2444031bb98SShilei Tian     // Check the size of stream pool
2454031bb98SShilei Tian     if (StreamPool[DeviceId].size() != EnvNumInitialStreams)
2464031bb98SShilei Tian       return false;
2474031bb98SShilei Tian 
2484031bb98SShilei Tian     // Check whether each stream is valid
2494031bb98SShilei Tian     for (CUstream &S : StreamPool[DeviceId])
2504031bb98SShilei Tian       if (!S)
2514031bb98SShilei Tian         return false;
2524031bb98SShilei Tian 
2534031bb98SShilei Tian     return true;
254feed674dSShilei Tian   }
255feed674dSShilei Tian };
256feed674dSShilei Tian 
2574031bb98SShilei Tian class DeviceRTLTy {
2583de4cd12SGeorge Rokos   int NumberOfDevices;
2594031bb98SShilei Tian   // OpenMP environment properties
2603de4cd12SGeorge Rokos   int EnvNumTeams;
2613de4cd12SGeorge Rokos   int EnvTeamLimit;
2624031bb98SShilei Tian   // OpenMP requires flags
263c5fe030cSGheorghe-Teodor Bercea   int64_t RequiresFlags;
264c5fe030cSGheorghe-Teodor Bercea 
2654031bb98SShilei Tian   static constexpr const int HardTeamLimit = 1U << 16U; // 64k
2664031bb98SShilei Tian   static constexpr const int HardThreadLimit = 1024;
2674031bb98SShilei Tian   static constexpr const int DefaultNumTeams = 128;
2684031bb98SShilei Tian   static constexpr const int DefaultNumThreads = 128;
2693de4cd12SGeorge Rokos 
2704031bb98SShilei Tian   std::unique_ptr<StreamManagerTy> StreamManager;
2714031bb98SShilei Tian   std::vector<DeviceDataTy> DeviceData;
2724031bb98SShilei Tian   std::vector<CUmodule> Modules;
273feed674dSShilei Tian 
2743de4cd12SGeorge Rokos   // Record entry point associated with device
2754031bb98SShilei Tian   void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) {
2764031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
2773de4cd12SGeorge Rokos     E.Entries.push_back(entry);
2783de4cd12SGeorge Rokos   }
2793de4cd12SGeorge Rokos 
2803de4cd12SGeorge Rokos   // Return true if the entry is associated with device
2814031bb98SShilei Tian   bool findOffloadEntry(const int DeviceId, const void *Addr) const {
2824031bb98SShilei Tian     for (const __tgt_offload_entry &Itr :
2834031bb98SShilei Tian          DeviceData[DeviceId].FuncGblEntries.back().Entries)
2844031bb98SShilei Tian       if (Itr.addr == Addr)
2853de4cd12SGeorge Rokos         return true;
2863de4cd12SGeorge Rokos 
2873de4cd12SGeorge Rokos     return false;
2883de4cd12SGeorge Rokos   }
2893de4cd12SGeorge Rokos 
2903de4cd12SGeorge Rokos   // Return the pointer to the target entries table
2914031bb98SShilei Tian   __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
2924031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
2933de4cd12SGeorge Rokos 
2944031bb98SShilei Tian     if (E.Entries.empty())
2954031bb98SShilei Tian       return nullptr;
2963de4cd12SGeorge Rokos 
2973de4cd12SGeorge Rokos     // Update table info according to the entries and return the pointer
2984031bb98SShilei Tian     E.Table.EntriesBegin = E.Entries.data();
2994031bb98SShilei Tian     E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
3003de4cd12SGeorge Rokos 
3013de4cd12SGeorge Rokos     return &E.Table;
3023de4cd12SGeorge Rokos   }
3033de4cd12SGeorge Rokos 
3043de4cd12SGeorge Rokos   // Clear entries table for a device
3054031bb98SShilei Tian   void clearOffloadEntriesTable(const int DeviceId) {
3064031bb98SShilei Tian     DeviceData[DeviceId].FuncGblEntries.emplace_back();
3074031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
3083de4cd12SGeorge Rokos     E.Entries.clear();
3094031bb98SShilei Tian     E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
3103de4cd12SGeorge Rokos   }
3113de4cd12SGeorge Rokos 
3124031bb98SShilei Tian   CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfoPtr) const {
3134031bb98SShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
3144031bb98SShilei Tian 
3154031bb98SShilei Tian     if (!AsyncInfoPtr->Queue)
3164031bb98SShilei Tian       AsyncInfoPtr->Queue = StreamManager->getStream(DeviceId);
3174031bb98SShilei Tian 
3184031bb98SShilei Tian     return reinterpret_cast<CUstream>(AsyncInfoPtr->Queue);
319b305d26bSSergey Dmitriev   }
3204031bb98SShilei Tian 
3214031bb98SShilei Tian public:
3224031bb98SShilei Tian   // This class should not be copied
3234031bb98SShilei Tian   DeviceRTLTy(const DeviceRTLTy &) = delete;
3244031bb98SShilei Tian   DeviceRTLTy(DeviceRTLTy &&) = delete;
3254031bb98SShilei Tian 
3264031bb98SShilei Tian   DeviceRTLTy()
3274031bb98SShilei Tian       : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
3284031bb98SShilei Tian         RequiresFlags(OMP_REQ_UNDEFINED) {
329b305d26bSSergey Dmitriev 
3303de4cd12SGeorge Rokos     DP("Start initializing CUDA\n");
3313de4cd12SGeorge Rokos 
3324031bb98SShilei Tian     CUresult Err = cuInit(0);
3334031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuInit\n")) {
3343de4cd12SGeorge Rokos       return;
3353de4cd12SGeorge Rokos     }
3363de4cd12SGeorge Rokos 
3374031bb98SShilei Tian     Err = cuDeviceGetCount(&NumberOfDevices);
3384031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
3393de4cd12SGeorge Rokos       return;
3403de4cd12SGeorge Rokos 
3413de4cd12SGeorge Rokos     if (NumberOfDevices == 0) {
3423de4cd12SGeorge Rokos       DP("There are no devices supporting CUDA.\n");
3433de4cd12SGeorge Rokos       return;
3443de4cd12SGeorge Rokos     }
3453de4cd12SGeorge Rokos 
3464031bb98SShilei Tian     DeviceData.resize(NumberOfDevices);
3473de4cd12SGeorge Rokos 
3483de4cd12SGeorge Rokos     // Get environment variables regarding teams
3494031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
3503de4cd12SGeorge Rokos       // OMP_TEAM_LIMIT has been set
3514031bb98SShilei Tian       EnvTeamLimit = std::stoi(EnvStr);
3523de4cd12SGeorge Rokos       DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
3533de4cd12SGeorge Rokos     }
3544031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
3553de4cd12SGeorge Rokos       // OMP_NUM_TEAMS has been set
3564031bb98SShilei Tian       EnvNumTeams = std::stoi(EnvStr);
3573de4cd12SGeorge Rokos       DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
3583de4cd12SGeorge Rokos     }
359c5fe030cSGheorghe-Teodor Bercea 
360feed674dSShilei Tian     StreamManager =
3614031bb98SShilei Tian         std::make_unique<StreamManagerTy>(NumberOfDevices, DeviceData);
3623de4cd12SGeorge Rokos   }
3633de4cd12SGeorge Rokos 
3644031bb98SShilei Tian   ~DeviceRTLTy() {
365feed674dSShilei Tian     // First destruct stream manager in case of Contexts is destructed before it
366feed674dSShilei Tian     StreamManager = nullptr;
367feed674dSShilei Tian 
3684031bb98SShilei Tian     for (CUmodule &M : Modules)
3694031bb98SShilei Tian       // Close module
3704031bb98SShilei Tian       if (M)
3714031bb98SShilei Tian         checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n");
3724031bb98SShilei Tian 
3734031bb98SShilei Tian     for (DeviceDataTy &D : DeviceData) {
3744031bb98SShilei Tian       // Destroy context
375c5348aecSYe Luo       if (D.Context) {
376c5348aecSYe Luo         checkResult(cuCtxSetCurrent(D.Context),
377c5348aecSYe Luo                     "Error returned from cuCtxSetCurrent\n");
378c5348aecSYe Luo         CUdevice Device;
379c5348aecSYe Luo         checkResult(cuCtxGetDevice(&Device),
380c5348aecSYe Luo                     "Error returned from cuCtxGetDevice\n");
381c5348aecSYe Luo         checkResult(cuDevicePrimaryCtxRelease(Device),
382c5348aecSYe Luo                     "Error returned from cuDevicePrimaryCtxRelease\n");
383c5348aecSYe Luo       }
3843de4cd12SGeorge Rokos     }
3853de4cd12SGeorge Rokos   }
3863de4cd12SGeorge Rokos 
3874031bb98SShilei Tian   // Check whether a given DeviceId is valid
3884031bb98SShilei Tian   bool isValidDeviceId(const int DeviceId) const {
3894031bb98SShilei Tian     return DeviceId >= 0 && DeviceId < NumberOfDevices;
39032ed2927SShilei Tian   }
39132ed2927SShilei Tian 
392cb038927SShilei Tian   int getNumOfDevices() const { return NumberOfDevices; }
3934031bb98SShilei Tian 
3944031bb98SShilei Tian   void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
3954031bb98SShilei Tian 
3964031bb98SShilei Tian   int initDevice(const int DeviceId) {
3974031bb98SShilei Tian     CUdevice Device;
3984031bb98SShilei Tian 
3994031bb98SShilei Tian     DP("Getting device %d\n", DeviceId);
4004031bb98SShilei Tian     CUresult Err = cuDeviceGet(&Device, DeviceId);
4014031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
40232ed2927SShilei Tian       return OFFLOAD_FAIL;
4033de4cd12SGeorge Rokos 
404c5348aecSYe Luo     // Query the current flags of the primary context and set its flags if
405c5348aecSYe Luo     // it is inactive
406c5348aecSYe Luo     unsigned int FormerPrimaryCtxFlags = 0;
407c5348aecSYe Luo     int FormerPrimaryCtxIsActive = 0;
408c5348aecSYe Luo     Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags,
409c5348aecSYe Luo                                      &FormerPrimaryCtxIsActive);
410c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n"))
411c5348aecSYe Luo       return OFFLOAD_FAIL;
412c5348aecSYe Luo 
413c5348aecSYe Luo     if (FormerPrimaryCtxIsActive) {
414c5348aecSYe Luo       DP("The primary context is active, no change to its flags\n");
415c5348aecSYe Luo       if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) !=
416c5348aecSYe Luo           CU_CTX_SCHED_BLOCKING_SYNC)
417c5348aecSYe Luo         DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n");
418c5348aecSYe Luo     } else {
419c5348aecSYe Luo       DP("The primary context is inactive, set its flags to "
420c5348aecSYe Luo          "CU_CTX_SCHED_BLOCKING_SYNC\n");
421c5348aecSYe Luo       Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC);
422c5348aecSYe Luo       if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n"))
423c5348aecSYe Luo         return OFFLOAD_FAIL;
424c5348aecSYe Luo     }
425c5348aecSYe Luo 
426c5348aecSYe Luo     // Retain the per device primary context and save it to use whenever this
427c5348aecSYe Luo     // device is selected.
428c5348aecSYe Luo     Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device);
429c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n"))
4303de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
4313de4cd12SGeorge Rokos 
4324031bb98SShilei Tian     Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
4334031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
4344031bb98SShilei Tian       return OFFLOAD_FAIL;
435a5153dbcSJohannes Doerfert 
436feed674dSShilei Tian     // Initialize stream pool
4374031bb98SShilei Tian     if (!StreamManager->initializeDeviceStreamPool(DeviceId))
4384031bb98SShilei Tian       return OFFLOAD_FAIL;
439a5153dbcSJohannes Doerfert 
440bb51d398SJonas Hahnfeld     // Query attributes to determine number of threads/block and blocks/grid.
4414031bb98SShilei Tian     int MaxGridDimX;
4424031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
4434031bb98SShilei Tian                                Device);
4444031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
4454031bb98SShilei Tian       DP("Error getting max grid dimension, use default value %d\n",
4464031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
4474031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
4484031bb98SShilei Tian     } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) {
4494031bb98SShilei Tian       DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
4504031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
4513de4cd12SGeorge Rokos     } else {
4523de4cd12SGeorge Rokos       DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping "
453bb51d398SJonas Hahnfeld          "at the hard limit\n",
4544031bb98SShilei Tian          MaxGridDimX, DeviceRTLTy::HardTeamLimit);
4554031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit;
4563de4cd12SGeorge Rokos     }
4573de4cd12SGeorge Rokos 
458bb51d398SJonas Hahnfeld     // We are only exploiting threads along the x axis.
4594031bb98SShilei Tian     int MaxBlockDimX;
4604031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxBlockDimX,
4614031bb98SShilei Tian                                CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
4624031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
4634031bb98SShilei Tian       DP("Error getting max block dimension, use default value %d\n",
4644031bb98SShilei Tian          DeviceRTLTy::DefaultNumThreads);
4654031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
4664031bb98SShilei Tian     } else if (MaxBlockDimX <= DeviceRTLTy::HardThreadLimit) {
4674031bb98SShilei Tian       DP("Using %d CUDA threads per block\n", MaxBlockDimX);
4684031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
4693de4cd12SGeorge Rokos     } else {
4704031bb98SShilei Tian       DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
4714031bb98SShilei Tian          "capping at the hard limit\n",
4724031bb98SShilei Tian          MaxBlockDimX, DeviceRTLTy::HardThreadLimit);
4734031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
4743de4cd12SGeorge Rokos     }
4753de4cd12SGeorge Rokos 
4764031bb98SShilei Tian     // Get and set warp size
4774031bb98SShilei Tian     int WarpSize;
4784031bb98SShilei Tian     Err =
4794031bb98SShilei Tian         cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
4804031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
4814031bb98SShilei Tian       DP("Error getting warp size, assume default value 32\n");
4824031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = 32;
483bb51d398SJonas Hahnfeld     } else {
4844031bb98SShilei Tian       DP("Using warp size %d\n", WarpSize);
4854031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = WarpSize;
4863de4cd12SGeorge Rokos     }
4873de4cd12SGeorge Rokos 
4883de4cd12SGeorge Rokos     // Adjust teams to the env variables
4894031bb98SShilei Tian     if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
4903de4cd12SGeorge Rokos       DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
4914031bb98SShilei Tian          EnvTeamLimit);
4924031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
4933de4cd12SGeorge Rokos     }
4943de4cd12SGeorge Rokos 
4953de4cd12SGeorge Rokos     DP("Max number of CUDA blocks %d, threads %d & warp size %d\n",
4964031bb98SShilei Tian        DeviceData[DeviceId].BlocksPerGrid, DeviceData[DeviceId].ThreadsPerBlock,
4974031bb98SShilei Tian        DeviceData[DeviceId].WarpSize);
4983de4cd12SGeorge Rokos 
4993de4cd12SGeorge Rokos     // Set default number of teams
5004031bb98SShilei Tian     if (EnvNumTeams > 0) {
5013de4cd12SGeorge Rokos       DP("Default number of teams set according to environment %d\n",
5024031bb98SShilei Tian          EnvNumTeams);
5034031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = EnvNumTeams;
5043de4cd12SGeorge Rokos     } else {
5054031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
5063de4cd12SGeorge Rokos       DP("Default number of teams set according to library's default %d\n",
5074031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
5083de4cd12SGeorge Rokos     }
5094031bb98SShilei Tian 
5104031bb98SShilei Tian     if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
5113de4cd12SGeorge Rokos       DP("Default number of teams exceeds device limit, capping at %d\n",
5124031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
5134031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
5143de4cd12SGeorge Rokos     }
5153de4cd12SGeorge Rokos 
5163de4cd12SGeorge Rokos     // Set default number of threads
5174031bb98SShilei Tian     DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
5183de4cd12SGeorge Rokos     DP("Default number of threads set according to library's default %d\n",
5194031bb98SShilei Tian        DeviceRTLTy::DefaultNumThreads);
5204031bb98SShilei Tian     if (DeviceData[DeviceId].NumThreads >
5214031bb98SShilei Tian         DeviceData[DeviceId].ThreadsPerBlock) {
5223de4cd12SGeorge Rokos       DP("Default number of threads exceeds device limit, capping at %d\n",
5234031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
5244031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].ThreadsPerBlock;
5253de4cd12SGeorge Rokos     }
5263de4cd12SGeorge Rokos 
5273de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
5283de4cd12SGeorge Rokos   }
5293de4cd12SGeorge Rokos 
5304031bb98SShilei Tian   __tgt_target_table *loadBinary(const int DeviceId,
5314031bb98SShilei Tian                                  const __tgt_device_image *Image) {
5324031bb98SShilei Tian     // Set the context we are using
5334031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
5344031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
5354031bb98SShilei Tian       return nullptr;
5363de4cd12SGeorge Rokos 
5373de4cd12SGeorge Rokos     // Clear the offload table as we are going to create a new one.
5384031bb98SShilei Tian     clearOffloadEntriesTable(DeviceId);
5393de4cd12SGeorge Rokos 
5403de4cd12SGeorge Rokos     // Create the module and extract the function pointers.
5414031bb98SShilei Tian     CUmodule Module;
5424031bb98SShilei Tian     DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
5434031bb98SShilei Tian     Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
5444031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
5454031bb98SShilei Tian       return nullptr;
5463de4cd12SGeorge Rokos 
5473de4cd12SGeorge Rokos     DP("CUDA module successfully loaded!\n");
5484031bb98SShilei Tian 
5494031bb98SShilei Tian     Modules.push_back(Module);
5503de4cd12SGeorge Rokos 
5513de4cd12SGeorge Rokos     // Find the symbols in the module by name.
5524031bb98SShilei Tian     const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
5534031bb98SShilei Tian     const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
5543de4cd12SGeorge Rokos 
5555272d29eSJohannes Doerfert     std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList;
5564031bb98SShilei Tian     for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
5574031bb98SShilei Tian       if (!E->addr) {
5584031bb98SShilei Tian         // We return nullptr when something like this happens, the host should
5594031bb98SShilei Tian         // have always something in the address to uniquely identify the target
5604031bb98SShilei Tian         // region.
5614031bb98SShilei Tian         DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
5624031bb98SShilei Tian         return nullptr;
5633de4cd12SGeorge Rokos       }
5643de4cd12SGeorge Rokos 
5654031bb98SShilei Tian       if (E->size) {
5664031bb98SShilei Tian         __tgt_offload_entry Entry = *E;
5674031bb98SShilei Tian         CUdeviceptr CUPtr;
5684031bb98SShilei Tian         size_t CUSize;
5694031bb98SShilei Tian         Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name);
5704031bb98SShilei Tian         // We keep this style here because we need the name
5714031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
5724031bb98SShilei Tian           DP("Loading global '%s' (Failed)\n", E->name);
5734031bb98SShilei Tian           CUDA_ERR_STRING(Err);
5744031bb98SShilei Tian           return nullptr;
5753de4cd12SGeorge Rokos         }
5763de4cd12SGeorge Rokos 
5774031bb98SShilei Tian         if (CUSize != E->size) {
5784031bb98SShilei Tian           DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
5794031bb98SShilei Tian              CUSize, E->size);
5804031bb98SShilei Tian           return nullptr;
5813de4cd12SGeorge Rokos         }
5823de4cd12SGeorge Rokos 
5833de4cd12SGeorge Rokos         DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
5844031bb98SShilei Tian            DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
5854031bb98SShilei Tian 
5864031bb98SShilei Tian         Entry.addr = (void *)(CUPtr);
5873de4cd12SGeorge Rokos 
588aace6d28SGheorghe-Teodor Bercea         // Note: In the current implementation declare target variables
589aace6d28SGheorghe-Teodor Bercea         // can either be link or to. This means that once unified
590aace6d28SGheorghe-Teodor Bercea         // memory is activated via the requires directive, the variable
591aace6d28SGheorghe-Teodor Bercea         // can be used directly from the host in both cases.
592aace6d28SGheorghe-Teodor Bercea         // TODO: when variables types other than to or link are added,
5934c6a098aSKazuaki Ishizaki         // the below condition should be changed to explicitly
594aace6d28SGheorghe-Teodor Bercea         // check for to and link variables types:
5954031bb98SShilei Tian         // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
5964031bb98SShilei Tian         // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
5974031bb98SShilei Tian         if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
598aace6d28SGheorghe-Teodor Bercea           // If unified memory is present any target link or to variables
599c5fe030cSGheorghe-Teodor Bercea           // can access host addresses directly. There is no longer a
600c5fe030cSGheorghe-Teodor Bercea           // need for device copies.
6014031bb98SShilei Tian           cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *));
6024031bb98SShilei Tian           DP("Copy linked variable host address (" DPxMOD
6034031bb98SShilei Tian              ") to device address (" DPxMOD ")\n",
6044031bb98SShilei Tian              DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
605c5fe030cSGheorghe-Teodor Bercea         }
606c5fe030cSGheorghe-Teodor Bercea 
6074031bb98SShilei Tian         addOffloadEntry(DeviceId, Entry);
6083de4cd12SGeorge Rokos 
6093de4cd12SGeorge Rokos         continue;
6103de4cd12SGeorge Rokos       }
6113de4cd12SGeorge Rokos 
6124031bb98SShilei Tian       CUfunction Func;
6134031bb98SShilei Tian       Err = cuModuleGetFunction(&Func, Module, E->name);
6144031bb98SShilei Tian       // We keep this style here because we need the name
6154031bb98SShilei Tian       if (Err != CUDA_SUCCESS) {
6164031bb98SShilei Tian         DP("Loading '%s' (Failed)\n", E->name);
6174031bb98SShilei Tian         CUDA_ERR_STRING(Err);
6184031bb98SShilei Tian         return nullptr;
6193de4cd12SGeorge Rokos       }
6203de4cd12SGeorge Rokos 
6213de4cd12SGeorge Rokos       DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
6224031bb98SShilei Tian          DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
6233de4cd12SGeorge Rokos 
6243de4cd12SGeorge Rokos       // default value GENERIC (in case symbol is missing from cubin file)
6253de4cd12SGeorge Rokos       int8_t ExecModeVal = ExecutionModeType::GENERIC;
6264031bb98SShilei Tian       std::string ExecModeNameStr(E->name);
6273de4cd12SGeorge Rokos       ExecModeNameStr += "_exec_mode";
6283de4cd12SGeorge Rokos       const char *ExecModeName = ExecModeNameStr.c_str();
6293de4cd12SGeorge Rokos 
6303de4cd12SGeorge Rokos       CUdeviceptr ExecModePtr;
6314031bb98SShilei Tian       size_t CUSize;
6324031bb98SShilei Tian       Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName);
6334031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
6344031bb98SShilei Tian         if (CUSize != sizeof(int8_t)) {
6353de4cd12SGeorge Rokos           DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
6364031bb98SShilei Tian              ExecModeName, CUSize, sizeof(int8_t));
6374031bb98SShilei Tian           return nullptr;
6383de4cd12SGeorge Rokos         }
6393de4cd12SGeorge Rokos 
6404031bb98SShilei Tian         Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize);
6414031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
6423de4cd12SGeorge Rokos           DP("Error when copying data from device to host. Pointers: "
6433de4cd12SGeorge Rokos              "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
6444031bb98SShilei Tian              DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
6454031bb98SShilei Tian           CUDA_ERR_STRING(Err);
6464031bb98SShilei Tian           return nullptr;
6473de4cd12SGeorge Rokos         }
6483de4cd12SGeorge Rokos 
6493de4cd12SGeorge Rokos         if (ExecModeVal < 0 || ExecModeVal > 1) {
6503de4cd12SGeorge Rokos           DP("Error wrong exec_mode value specified in cubin file: %d\n",
6513de4cd12SGeorge Rokos              ExecModeVal);
6524031bb98SShilei Tian           return nullptr;
6533de4cd12SGeorge Rokos         }
6543de4cd12SGeorge Rokos       } else {
6554031bb98SShilei Tian         DP("Loading global exec_mode '%s' - symbol missing, using default "
6564031bb98SShilei Tian            "value GENERIC (1)\n",
6574031bb98SShilei Tian            ExecModeName);
6584031bb98SShilei Tian         CUDA_ERR_STRING(Err);
6593de4cd12SGeorge Rokos       }
6603de4cd12SGeorge Rokos 
6614031bb98SShilei Tian       KernelsList.emplace_back(Func, ExecModeVal);
6623de4cd12SGeorge Rokos 
6634031bb98SShilei Tian       __tgt_offload_entry Entry = *E;
6644031bb98SShilei Tian       Entry.addr = &KernelsList.back();
6654031bb98SShilei Tian       addOffloadEntry(DeviceId, Entry);
6663de4cd12SGeorge Rokos     }
6673de4cd12SGeorge Rokos 
668e1c7a46dSGuansong Zhang     // send device environment data to the device
669e1c7a46dSGuansong Zhang     {
6704031bb98SShilei Tian       omptarget_device_environmentTy DeviceEnv{0};
671e1c7a46dSGuansong Zhang 
672e1c7a46dSGuansong Zhang #ifdef OMPTARGET_DEBUG
6734031bb98SShilei Tian       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
6744031bb98SShilei Tian         DeviceEnv.debug_level = std::stoi(EnvStr);
675e1c7a46dSGuansong Zhang #endif
676e1c7a46dSGuansong Zhang 
6774031bb98SShilei Tian       const char *DeviceEnvName = "omptarget_device_environment";
6784031bb98SShilei Tian       CUdeviceptr DeviceEnvPtr;
6794031bb98SShilei Tian       size_t CUSize;
680e1c7a46dSGuansong Zhang 
6814031bb98SShilei Tian       Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
6824031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
6834031bb98SShilei Tian         if (CUSize != sizeof(DeviceEnv)) {
684e1c7a46dSGuansong Zhang           DP("Global device_environment '%s' - size mismatch (%zu != %zu)\n",
6854031bb98SShilei Tian              DeviceEnvName, CUSize, sizeof(int32_t));
6864031bb98SShilei Tian           CUDA_ERR_STRING(Err);
6874031bb98SShilei Tian           return nullptr;
688e1c7a46dSGuansong Zhang         }
689e1c7a46dSGuansong Zhang 
6904031bb98SShilei Tian         Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
6914031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
692e1c7a46dSGuansong Zhang           DP("Error when copying data from host to device. Pointers: "
693e1c7a46dSGuansong Zhang              "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
6944031bb98SShilei Tian              DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
6954031bb98SShilei Tian           CUDA_ERR_STRING(Err);
6964031bb98SShilei Tian           return nullptr;
697e1c7a46dSGuansong Zhang         }
698e1c7a46dSGuansong Zhang 
6994031bb98SShilei Tian         DP("Sending global device environment data %zu bytes\n", CUSize);
700e1c7a46dSGuansong Zhang       } else {
7014031bb98SShilei Tian         DP("Finding global device environment '%s' - symbol missing.\n",
7024031bb98SShilei Tian            DeviceEnvName);
7034031bb98SShilei Tian         DP("Continue, considering this is a device RTL which does not accept "
7044031bb98SShilei Tian            "environment setting.\n");
705e1c7a46dSGuansong Zhang       }
706e1c7a46dSGuansong Zhang     }
707e1c7a46dSGuansong Zhang 
7084031bb98SShilei Tian     return getOffloadEntriesTable(DeviceId);
7093de4cd12SGeorge Rokos   }
7103de4cd12SGeorge Rokos 
7114031bb98SShilei Tian   void *dataAlloc(const int DeviceId, const int64_t Size) const {
7124031bb98SShilei Tian     if (Size == 0)
7134031bb98SShilei Tian       return nullptr;
7144031bb98SShilei Tian 
7154031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
7164031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
7174031bb98SShilei Tian       return nullptr;
7184031bb98SShilei Tian 
7194031bb98SShilei Tian     CUdeviceptr DevicePtr;
7204031bb98SShilei Tian     Err = cuMemAlloc(&DevicePtr, Size);
7214031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuMemAlloc\n"))
7224031bb98SShilei Tian       return nullptr;
7234031bb98SShilei Tian 
7244031bb98SShilei Tian     return (void *)DevicePtr;
7253de4cd12SGeorge Rokos   }
7263de4cd12SGeorge Rokos 
7274031bb98SShilei Tian   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
7284031bb98SShilei Tian                  const int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
7294031bb98SShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
7303de4cd12SGeorge Rokos 
7314031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
7324031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
7333de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
7343de4cd12SGeorge Rokos 
7354031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfoPtr);
7363de4cd12SGeorge Rokos 
7374031bb98SShilei Tian     Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
7384031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
7394031bb98SShilei Tian       DP("Error when copying data from host to device. Pointers: host = " DPxMOD
7404031bb98SShilei Tian          ", device = " DPxMOD ", size = %" PRId64 "\n",
7414031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
7424031bb98SShilei Tian       CUDA_ERR_STRING(Err);
7433de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
7443de4cd12SGeorge Rokos     }
7453de4cd12SGeorge Rokos 
7463de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
7473de4cd12SGeorge Rokos   }
7483de4cd12SGeorge Rokos 
7494031bb98SShilei Tian   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
7504031bb98SShilei Tian                    const int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
7514031bb98SShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
7524031bb98SShilei Tian 
7534031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
7544031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
75503ff643dSShilei Tian       return OFFLOAD_FAIL;
75603ff643dSShilei Tian 
7574031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfoPtr);
75803ff643dSShilei Tian 
7594031bb98SShilei Tian     Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
7604031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
7614031bb98SShilei Tian       DP("Error when copying data from device to host. Pointers: host = " DPxMOD
7624031bb98SShilei Tian          ", device = " DPxMOD ", size = %" PRId64 "\n",
7634031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
7644031bb98SShilei Tian       CUDA_ERR_STRING(Err);
7653de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
7663de4cd12SGeorge Rokos     }
7673de4cd12SGeorge Rokos 
7684031bb98SShilei Tian     return OFFLOAD_SUCCESS;
7694031bb98SShilei Tian   }
7704031bb98SShilei Tian 
771a014fbbcSShilei Tian   int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
772a014fbbcSShilei Tian                    int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
773a014fbbcSShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
774a014fbbcSShilei Tian 
775a014fbbcSShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context);
776a014fbbcSShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
777a014fbbcSShilei Tian       return OFFLOAD_FAIL;
778a014fbbcSShilei Tian 
779a014fbbcSShilei Tian     CUstream Stream = getStream(SrcDevId, AsyncInfoPtr);
780a014fbbcSShilei Tian 
781a014fbbcSShilei Tian     // If they are two devices, we try peer to peer copy first
782a014fbbcSShilei Tian     if (SrcDevId != DstDevId) {
783a014fbbcSShilei Tian       int CanAccessPeer = 0;
784a014fbbcSShilei Tian       Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
785a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
786a014fbbcSShilei Tian         DP("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
787a014fbbcSShilei Tian            ", dst = %" PRId32 "\n",
788a014fbbcSShilei Tian            SrcDevId, DstDevId);
789a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
790a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
791a014fbbcSShilei Tian       }
792a014fbbcSShilei Tian 
793a014fbbcSShilei Tian       if (!CanAccessPeer) {
794a014fbbcSShilei Tian         DP("P2P memcpy not supported so fall back to D2D memcpy");
795a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
796a014fbbcSShilei Tian       }
797a014fbbcSShilei Tian 
798a014fbbcSShilei Tian       Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
799a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
800a014fbbcSShilei Tian         DP("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
801a014fbbcSShilei Tian            ", dst = %" PRId32 "\n",
802a014fbbcSShilei Tian            SrcDevId, DstDevId);
803a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
804a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
805a014fbbcSShilei Tian       }
806a014fbbcSShilei Tian 
807a014fbbcSShilei Tian       Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
808a014fbbcSShilei Tian                               (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context,
809a014fbbcSShilei Tian                               Size, Stream);
810a014fbbcSShilei Tian       if (Err == CUDA_SUCCESS)
811a014fbbcSShilei Tian         return OFFLOAD_SUCCESS;
812a014fbbcSShilei Tian 
813a014fbbcSShilei Tian       DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
81445bb073dSYe Luo          ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32 "\n",
81545bb073dSYe Luo          DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
816a014fbbcSShilei Tian       CUDA_ERR_STRING(Err);
817a014fbbcSShilei Tian     }
818a014fbbcSShilei Tian 
819a014fbbcSShilei Tian     return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
820a014fbbcSShilei Tian   }
821a014fbbcSShilei Tian 
8224031bb98SShilei Tian   int dataDelete(const int DeviceId, void *TgtPtr) const {
8234031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
8244031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
8254031bb98SShilei Tian       return OFFLOAD_FAIL;
8264031bb98SShilei Tian 
8274031bb98SShilei Tian     Err = cuMemFree((CUdeviceptr)TgtPtr);
8284031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuMemFree\n"))
8294031bb98SShilei Tian       return OFFLOAD_FAIL;
8304031bb98SShilei Tian 
8314031bb98SShilei Tian     return OFFLOAD_SUCCESS;
8324031bb98SShilei Tian   }
8334031bb98SShilei Tian 
834aa27cfc1SJohannes Doerfert   int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
835aa27cfc1SJohannes Doerfert                           ptrdiff_t *TgtOffsets, const int ArgNum,
836aa27cfc1SJohannes Doerfert                           const int TeamNum, const int ThreadLimit,
8374031bb98SShilei Tian                           const unsigned int LoopTripCount,
8384031bb98SShilei Tian                           __tgt_async_info *AsyncInfo) const {
8394031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
8404031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
8414031bb98SShilei Tian       return OFFLOAD_FAIL;
8424031bb98SShilei Tian 
8433de4cd12SGeorge Rokos     // All args are references.
8444031bb98SShilei Tian     std::vector<void *> Args(ArgNum);
8454031bb98SShilei Tian     std::vector<void *> Ptrs(ArgNum);
8463de4cd12SGeorge Rokos 
8474031bb98SShilei Tian     for (int I = 0; I < ArgNum; ++I) {
8484031bb98SShilei Tian       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
8494031bb98SShilei Tian       Args[I] = &Ptrs[I];
8501546d319SGeorge Rokos     }
8513de4cd12SGeorge Rokos 
852aa27cfc1SJohannes Doerfert     KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
8533de4cd12SGeorge Rokos 
854aa27cfc1SJohannes Doerfert     int CudaThreadsPerBlock;
8554031bb98SShilei Tian     if (ThreadLimit > 0) {
8564031bb98SShilei Tian       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
8574031bb98SShilei Tian       CudaThreadsPerBlock = ThreadLimit;
8583de4cd12SGeorge Rokos       // Add master warp if necessary
8593de4cd12SGeorge Rokos       if (KernelInfo->ExecutionMode == GENERIC) {
8604031bb98SShilei Tian         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
8614031bb98SShilei Tian         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
8623de4cd12SGeorge Rokos       }
863c13df8e5SGeorge Rokos     } else {
864c13df8e5SGeorge Rokos       DP("Setting CUDA threads per block to default %d\n",
8654031bb98SShilei Tian          DeviceData[DeviceId].NumThreads);
8664031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
867c13df8e5SGeorge Rokos     }
8683de4cd12SGeorge Rokos 
8694031bb98SShilei Tian     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
8703de4cd12SGeorge Rokos       DP("Threads per block capped at device limit %d\n",
8714031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
8724031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
8733de4cd12SGeorge Rokos     }
8743de4cd12SGeorge Rokos 
875aa27cfc1SJohannes Doerfert     if (!KernelInfo->MaxThreadsPerBlock) {
876aa27cfc1SJohannes Doerfert       Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
8774031bb98SShilei Tian                                CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
8784031bb98SShilei Tian                                KernelInfo->Func);
879aa27cfc1SJohannes Doerfert       if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
880aa27cfc1SJohannes Doerfert         return OFFLOAD_FAIL;
881aa27cfc1SJohannes Doerfert     }
882aa27cfc1SJohannes Doerfert 
883aa27cfc1SJohannes Doerfert     if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
884aa27cfc1SJohannes Doerfert       DP("Threads per block capped at kernel limit %d\n",
885aa27cfc1SJohannes Doerfert          KernelInfo->MaxThreadsPerBlock);
886aa27cfc1SJohannes Doerfert       CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
8873de4cd12SGeorge Rokos     }
8883de4cd12SGeorge Rokos 
8894031bb98SShilei Tian     unsigned int CudaBlocksPerGrid;
8904031bb98SShilei Tian     if (TeamNum <= 0) {
8914031bb98SShilei Tian       if (LoopTripCount > 0 && EnvNumTeams < 0) {
892c13df8e5SGeorge Rokos         if (KernelInfo->ExecutionMode == SPMD) {
8934031bb98SShilei Tian           // We have a combined construct, i.e. `target teams distribute
8944031bb98SShilei Tian           // parallel for [simd]`. We launch so many teams so that each thread
8954031bb98SShilei Tian           // will execute one iteration of the loop. round up to the nearest
8964031bb98SShilei Tian           // integer
8974031bb98SShilei Tian           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
898c13df8e5SGeorge Rokos         } else {
899c13df8e5SGeorge Rokos           // If we reach this point, then we have a non-combined construct, i.e.
900c13df8e5SGeorge Rokos           // `teams distribute` with a nested `parallel for` and each team is
901c13df8e5SGeorge Rokos           // assigned one iteration of the `distribute` loop. E.g.:
902c13df8e5SGeorge Rokos           //
903c13df8e5SGeorge Rokos           // #pragma omp target teams distribute
904c13df8e5SGeorge Rokos           // for(...loop_tripcount...) {
905c13df8e5SGeorge Rokos           //   #pragma omp parallel for
906c13df8e5SGeorge Rokos           //   for(...) {}
907c13df8e5SGeorge Rokos           // }
908c13df8e5SGeorge Rokos           //
909c13df8e5SGeorge Rokos           // Threads within a team will execute the iterations of the `parallel`
910c13df8e5SGeorge Rokos           // loop.
9114031bb98SShilei Tian           CudaBlocksPerGrid = LoopTripCount;
912c13df8e5SGeorge Rokos         }
91345bb073dSYe Luo         DP("Using %d teams due to loop trip count %" PRIu32
9144031bb98SShilei Tian            " and number of threads per block %d\n",
9154031bb98SShilei Tian            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
9163de4cd12SGeorge Rokos       } else {
9174031bb98SShilei Tian         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
9184031bb98SShilei Tian         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
9193de4cd12SGeorge Rokos       }
9204031bb98SShilei Tian     } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) {
9213de4cd12SGeorge Rokos       DP("Capping number of teams to team limit %d\n",
9224031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
9234031bb98SShilei Tian       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
9243de4cd12SGeorge Rokos     } else {
9254031bb98SShilei Tian       DP("Using requested number of teams %d\n", TeamNum);
9264031bb98SShilei Tian       CudaBlocksPerGrid = TeamNum;
9273de4cd12SGeorge Rokos     }
9283de4cd12SGeorge Rokos 
9293de4cd12SGeorge Rokos     // Run on the device.
9304031bb98SShilei Tian     DP("Launch kernel with %d blocks and %d threads\n", CudaBlocksPerGrid,
9314031bb98SShilei Tian        CudaThreadsPerBlock);
9323de4cd12SGeorge Rokos 
9334031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfo);
9344031bb98SShilei Tian     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
9354031bb98SShilei Tian                          /* gridDimZ */ 1, CudaThreadsPerBlock,
9364031bb98SShilei Tian                          /* blockDimY */ 1, /* blockDimZ */ 1,
9374031bb98SShilei Tian                          /* sharedMemBytes */ 0, Stream, &Args[0], nullptr);
9384031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
9394031bb98SShilei Tian       return OFFLOAD_FAIL;
9404031bb98SShilei Tian 
9414031bb98SShilei Tian     DP("Launch of entry point at " DPxMOD " successful!\n",
9424031bb98SShilei Tian        DPxPTR(TgtEntryPtr));
9434031bb98SShilei Tian 
9444031bb98SShilei Tian     return OFFLOAD_SUCCESS;
9454031bb98SShilei Tian   }
9464031bb98SShilei Tian 
9474031bb98SShilei Tian   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfoPtr) const {
9484031bb98SShilei Tian     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfoPtr->Queue);
9494031bb98SShilei Tian     CUresult Err = cuStreamSynchronize(Stream);
9504031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
9514031bb98SShilei Tian       DP("Error when synchronizing stream. stream = " DPxMOD
9524031bb98SShilei Tian          ", async info ptr = " DPxMOD "\n",
9534031bb98SShilei Tian          DPxPTR(Stream), DPxPTR(AsyncInfoPtr));
9544031bb98SShilei Tian       CUDA_ERR_STRING(Err);
9553de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
9563de4cd12SGeorge Rokos     }
9573de4cd12SGeorge Rokos 
9584031bb98SShilei Tian     // Once the stream is synchronized, return it to stream pool and reset
9594031bb98SShilei Tian     // async_info. This is to make sure the synchronization only works for its
9604031bb98SShilei Tian     // own tasks.
9614031bb98SShilei Tian     StreamManager->returnStream(
9624031bb98SShilei Tian         DeviceId, reinterpret_cast<CUstream>(AsyncInfoPtr->Queue));
9634031bb98SShilei Tian     AsyncInfoPtr->Queue = nullptr;
9643de4cd12SGeorge Rokos 
9653de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
9663de4cd12SGeorge Rokos   }
9674031bb98SShilei Tian };
9684031bb98SShilei Tian 
9694031bb98SShilei Tian DeviceRTLTy DeviceRTL;
9704031bb98SShilei Tian } // namespace
9714031bb98SShilei Tian 
9724031bb98SShilei Tian // Exposed library API function
9734031bb98SShilei Tian #ifdef __cplusplus
9744031bb98SShilei Tian extern "C" {
9754031bb98SShilei Tian #endif
9764031bb98SShilei Tian 
9774031bb98SShilei Tian int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
9784031bb98SShilei Tian   return elf_check_machine(image, /* EM_CUDA */ 190);
9794031bb98SShilei Tian }
9804031bb98SShilei Tian 
9814031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
9824031bb98SShilei Tian 
9834031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
98440470eb2SGeorge Rokos   DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
9854031bb98SShilei Tian   DeviceRTL.setRequiresFlag(RequiresFlags);
9864031bb98SShilei Tian   return RequiresFlags;
9874031bb98SShilei Tian }
9884031bb98SShilei Tian 
989a014fbbcSShilei Tian int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) {
990a014fbbcSShilei Tian   if (DeviceRTL.isValidDeviceId(src_dev_id) &&
991a014fbbcSShilei Tian       DeviceRTL.isValidDeviceId(dst_dev_id))
992a014fbbcSShilei Tian     return 1;
993a014fbbcSShilei Tian 
994a014fbbcSShilei Tian   return 0;
995a014fbbcSShilei Tian }
996a014fbbcSShilei Tian 
9974031bb98SShilei Tian int32_t __tgt_rtl_init_device(int32_t device_id) {
9984031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
9994031bb98SShilei Tian 
10004031bb98SShilei Tian   return DeviceRTL.initDevice(device_id);
10014031bb98SShilei Tian }
10024031bb98SShilei Tian 
10034031bb98SShilei Tian __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
10044031bb98SShilei Tian                                           __tgt_device_image *image) {
10054031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10064031bb98SShilei Tian 
10074031bb98SShilei Tian   return DeviceRTL.loadBinary(device_id, image);
10084031bb98SShilei Tian }
10094031bb98SShilei Tian 
10104031bb98SShilei Tian void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *) {
10114031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10124031bb98SShilei Tian 
10134031bb98SShilei Tian   return DeviceRTL.dataAlloc(device_id, size);
10144031bb98SShilei Tian }
10154031bb98SShilei Tian 
10164031bb98SShilei Tian int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
10174031bb98SShilei Tian                               int64_t size) {
10184031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10194031bb98SShilei Tian 
10204031bb98SShilei Tian   __tgt_async_info async_info;
10214031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr,
10224031bb98SShilei Tian                                                  size, &async_info);
10234031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
10244031bb98SShilei Tian     return OFFLOAD_FAIL;
10254031bb98SShilei Tian 
10264031bb98SShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
10274031bb98SShilei Tian }
10284031bb98SShilei Tian 
10294031bb98SShilei Tian int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr,
10304031bb98SShilei Tian                                     void *hst_ptr, int64_t size,
10314031bb98SShilei Tian                                     __tgt_async_info *async_info_ptr) {
10324031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10334031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
10344031bb98SShilei Tian 
10354031bb98SShilei Tian   return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size,
10364031bb98SShilei Tian                               async_info_ptr);
10374031bb98SShilei Tian }
10384031bb98SShilei Tian 
10394031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
10404031bb98SShilei Tian                                 int64_t size) {
10414031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10424031bb98SShilei Tian 
10434031bb98SShilei Tian   __tgt_async_info async_info;
10444031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr,
10454031bb98SShilei Tian                                                    size, &async_info);
10464031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
10474031bb98SShilei Tian     return OFFLOAD_FAIL;
10484031bb98SShilei Tian 
10494031bb98SShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
10504031bb98SShilei Tian }
10514031bb98SShilei Tian 
10524031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr,
10534031bb98SShilei Tian                                       void *tgt_ptr, int64_t size,
10544031bb98SShilei Tian                                       __tgt_async_info *async_info_ptr) {
10554031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10564031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
10574031bb98SShilei Tian 
10584031bb98SShilei Tian   return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size,
10594031bb98SShilei Tian                                 async_info_ptr);
10604031bb98SShilei Tian }
10614031bb98SShilei Tian 
1062a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr,
1063a014fbbcSShilei Tian                                       int dst_dev_id, void *dst_ptr,
1064a014fbbcSShilei Tian                                       int64_t size,
1065a014fbbcSShilei Tian                                       __tgt_async_info *async_info_ptr) {
1066a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1067a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1068a014fbbcSShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
1069a014fbbcSShilei Tian 
1070a014fbbcSShilei Tian   return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size,
1071a014fbbcSShilei Tian                                 async_info_ptr);
1072a014fbbcSShilei Tian }
1073a014fbbcSShilei Tian 
1074a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr,
1075a014fbbcSShilei Tian                                 int32_t dst_dev_id, void *dst_ptr,
1076a014fbbcSShilei Tian                                 int64_t size) {
1077a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1078a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1079a014fbbcSShilei Tian 
1080a014fbbcSShilei Tian   __tgt_async_info async_info;
1081a014fbbcSShilei Tian   const int32_t rc = __tgt_rtl_data_exchange_async(
1082a014fbbcSShilei Tian       src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &async_info);
1083a014fbbcSShilei Tian   if (rc != OFFLOAD_SUCCESS)
1084a014fbbcSShilei Tian     return OFFLOAD_FAIL;
1085a014fbbcSShilei Tian 
1086a014fbbcSShilei Tian   return __tgt_rtl_synchronize(src_dev_id, &async_info);
1087a014fbbcSShilei Tian }
1088a014fbbcSShilei Tian 
10894031bb98SShilei Tian int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
10904031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10914031bb98SShilei Tian 
10924031bb98SShilei Tian   return DeviceRTL.dataDelete(device_id, tgt_ptr);
10934031bb98SShilei Tian }
10944031bb98SShilei Tian 
10954031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
10964031bb98SShilei Tian                                          void **tgt_args,
10974031bb98SShilei Tian                                          ptrdiff_t *tgt_offsets,
10984031bb98SShilei Tian                                          int32_t arg_num, int32_t team_num,
10994031bb98SShilei Tian                                          int32_t thread_limit,
11004031bb98SShilei Tian                                          uint64_t loop_tripcount) {
11014031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11024031bb98SShilei Tian 
11034031bb98SShilei Tian   __tgt_async_info async_info;
11044031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_team_region_async(
11054031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
11064031bb98SShilei Tian       thread_limit, loop_tripcount, &async_info);
11074031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
11084031bb98SShilei Tian     return OFFLOAD_FAIL;
11094031bb98SShilei Tian 
11104031bb98SShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
11114031bb98SShilei Tian }
11124031bb98SShilei Tian 
11134031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async(
11144031bb98SShilei Tian     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
11154031bb98SShilei Tian     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
11164031bb98SShilei Tian     int32_t thread_limit, uint64_t loop_tripcount,
11174031bb98SShilei Tian     __tgt_async_info *async_info_ptr) {
11184031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11194031bb98SShilei Tian 
11204031bb98SShilei Tian   return DeviceRTL.runTargetTeamRegion(
11214031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
11224031bb98SShilei Tian       thread_limit, loop_tripcount, async_info_ptr);
11234031bb98SShilei Tian }
11243de4cd12SGeorge Rokos 
11253de4cd12SGeorge Rokos int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
112632ed2927SShilei Tian                                     void **tgt_args, ptrdiff_t *tgt_offsets,
112703ff643dSShilei Tian                                     int32_t arg_num) {
11284031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11294031bb98SShilei Tian 
113003ff643dSShilei Tian   __tgt_async_info async_info;
11314031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_region_async(
113203ff643dSShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &async_info);
113303ff643dSShilei Tian   if (rc != OFFLOAD_SUCCESS)
113403ff643dSShilei Tian     return OFFLOAD_FAIL;
113503ff643dSShilei Tian 
113603ff643dSShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
113703ff643dSShilei Tian }
113803ff643dSShilei Tian 
113903ff643dSShilei Tian int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
114003ff643dSShilei Tian                                           void *tgt_entry_ptr, void **tgt_args,
114103ff643dSShilei Tian                                           ptrdiff_t *tgt_offsets,
114232ed2927SShilei Tian                                           int32_t arg_num,
11434031bb98SShilei Tian                                           __tgt_async_info *async_info_ptr) {
11444031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11454031bb98SShilei Tian 
114603ff643dSShilei Tian   return __tgt_rtl_run_target_team_region_async(
11474031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
11484031bb98SShilei Tian       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
11494031bb98SShilei Tian       async_info_ptr);
115032ed2927SShilei Tian }
115132ed2927SShilei Tian 
11524031bb98SShilei Tian int32_t __tgt_rtl_synchronize(int32_t device_id,
11534031bb98SShilei Tian                               __tgt_async_info *async_info_ptr) {
11544031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11554031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
11564031bb98SShilei Tian   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
115732ed2927SShilei Tian 
11584031bb98SShilei Tian   return DeviceRTL.synchronize(device_id, async_info_ptr);
11593de4cd12SGeorge Rokos }
11603de4cd12SGeorge Rokos 
11613de4cd12SGeorge Rokos #ifdef __cplusplus
11623de4cd12SGeorge Rokos }
11633de4cd12SGeorge Rokos #endif
1164