1 //===--------- device.cpp - Target independent OpenMP target RTL ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Functionality for managing devices that are handled by RTL plugins.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "device.h"
14 #include "private.h"
15 #include "rtl.h"
16 
17 #include <cassert>
18 #include <climits>
19 #include <cstdio>
20 #include <string>
21 
22 DeviceTy::DeviceTy(const DeviceTy &D)
23     : DeviceID(D.DeviceID), RTL(D.RTL), RTLDeviceID(D.RTLDeviceID),
24       IsInit(D.IsInit), InitFlag(), HasPendingGlobals(D.HasPendingGlobals),
25       HostDataToTargetMap(D.HostDataToTargetMap),
26       PendingCtorsDtors(D.PendingCtorsDtors), ShadowPtrMap(D.ShadowPtrMap),
27       DataMapMtx(), PendingGlobalsMtx(), ShadowMtx(),
28       LoopTripCnt(D.LoopTripCnt) {}
29 
30 DeviceTy &DeviceTy::operator=(const DeviceTy &D) {
31   DeviceID = D.DeviceID;
32   RTL = D.RTL;
33   RTLDeviceID = D.RTLDeviceID;
34   IsInit = D.IsInit;
35   HasPendingGlobals = D.HasPendingGlobals;
36   HostDataToTargetMap = D.HostDataToTargetMap;
37   PendingCtorsDtors = D.PendingCtorsDtors;
38   ShadowPtrMap = D.ShadowPtrMap;
39   LoopTripCnt = D.LoopTripCnt;
40 
41   return *this;
42 }
43 
44 DeviceTy::DeviceTy(RTLInfoTy *RTL)
45     : DeviceID(-1), RTL(RTL), RTLDeviceID(-1), IsInit(false), InitFlag(),
46       HasPendingGlobals(false), HostDataToTargetMap(), PendingCtorsDtors(),
47       ShadowPtrMap(), DataMapMtx(), PendingGlobalsMtx(), ShadowMtx() {}
48 
49 DeviceTy::~DeviceTy() {
50   if (DeviceID == -1 || !(getInfoLevel() & OMP_INFOTYPE_DUMP_TABLE))
51     return;
52 
53   ident_t loc = {0, 0, 0, 0, ";libomptarget;libomptarget;0;0;;"};
54   dumpTargetPointerMappings(&loc, *this);
55 }
56 
57 int DeviceTy::associatePtr(void *HstPtrBegin, void *TgtPtrBegin, int64_t Size) {
58   DataMapMtx.lock();
59 
60   // Check if entry exists
61   auto search = HostDataToTargetMap.find(HstPtrBeginTy{(uintptr_t)HstPtrBegin});
62   if (search != HostDataToTargetMap.end()) {
63     // Mapping already exists
64     bool isValid = search->HstPtrEnd == (uintptr_t)HstPtrBegin + Size &&
65                    search->TgtPtrBegin == (uintptr_t)TgtPtrBegin;
66     DataMapMtx.unlock();
67     if (isValid) {
68       DP("Attempt to re-associate the same device ptr+offset with the same "
69          "host ptr, nothing to do\n");
70       return OFFLOAD_SUCCESS;
71     } else {
72       REPORT("Not allowed to re-associate a different device ptr+offset with "
73              "the same host ptr\n");
74       return OFFLOAD_FAIL;
75     }
76   }
77 
78   // Mapping does not exist, allocate it with refCount=INF
79   HostDataToTargetTy newEntry((uintptr_t)HstPtrBegin /*HstPtrBase*/,
80                               (uintptr_t)HstPtrBegin /*HstPtrBegin*/,
81                               (uintptr_t)HstPtrBegin + Size /*HstPtrEnd*/,
82                               (uintptr_t)TgtPtrBegin /*TgtPtrBegin*/, nullptr,
83                               true /*IsRefCountINF*/);
84 
85   DP("Creating new map entry: HstBase=" DPxMOD ", HstBegin=" DPxMOD
86      ", HstEnd=" DPxMOD ", TgtBegin=" DPxMOD "\n",
87      DPxPTR(newEntry.HstPtrBase), DPxPTR(newEntry.HstPtrBegin),
88      DPxPTR(newEntry.HstPtrEnd), DPxPTR(newEntry.TgtPtrBegin));
89   HostDataToTargetMap.insert(newEntry);
90 
91   DataMapMtx.unlock();
92 
93   return OFFLOAD_SUCCESS;
94 }
95 
96 int DeviceTy::disassociatePtr(void *HstPtrBegin) {
97   DataMapMtx.lock();
98 
99   auto search = HostDataToTargetMap.find(HstPtrBeginTy{(uintptr_t)HstPtrBegin});
100   if (search != HostDataToTargetMap.end()) {
101     // Mapping exists
102     if (search->isRefCountInf()) {
103       DP("Association found, removing it\n");
104       HostDataToTargetMap.erase(search);
105       DataMapMtx.unlock();
106       return OFFLOAD_SUCCESS;
107     } else {
108       REPORT("Trying to disassociate a pointer which was not mapped via "
109              "omp_target_associate_ptr\n");
110     }
111   }
112 
113   // Mapping not found
114   DataMapMtx.unlock();
115   REPORT("Association not found\n");
116   return OFFLOAD_FAIL;
117 }
118 
119 // Get ref count of map entry containing HstPtrBegin
120 uint64_t DeviceTy::getMapEntryRefCnt(void *HstPtrBegin) {
121   uintptr_t hp = (uintptr_t)HstPtrBegin;
122   uint64_t RefCnt = 0;
123 
124   DataMapMtx.lock();
125   if (!HostDataToTargetMap.empty()) {
126     auto upper = HostDataToTargetMap.upper_bound(hp);
127     if (upper != HostDataToTargetMap.begin()) {
128       upper--;
129       if (hp >= upper->HstPtrBegin && hp < upper->HstPtrEnd) {
130         DP("DeviceTy::getMapEntry: requested entry found\n");
131         RefCnt = upper->getRefCount();
132       }
133     }
134   }
135   DataMapMtx.unlock();
136 
137   if (RefCnt == 0) {
138     DP("DeviceTy::getMapEntry: requested entry not found\n");
139   }
140 
141   return RefCnt;
142 }
143 
144 LookupResult DeviceTy::lookupMapping(void *HstPtrBegin, int64_t Size) {
145   uintptr_t hp = (uintptr_t)HstPtrBegin;
146   LookupResult lr;
147 
148   DP("Looking up mapping(HstPtrBegin=" DPxMOD ", Size=%" PRId64 ")...\n",
149      DPxPTR(hp), Size);
150 
151   if (HostDataToTargetMap.empty())
152     return lr;
153 
154   auto upper = HostDataToTargetMap.upper_bound(hp);
155   // check the left bin
156   if (upper != HostDataToTargetMap.begin()) {
157     lr.Entry = std::prev(upper);
158     auto &HT = *lr.Entry;
159     // Is it contained?
160     lr.Flags.IsContained = hp >= HT.HstPtrBegin && hp < HT.HstPtrEnd &&
161                            (hp + Size) <= HT.HstPtrEnd;
162     // Does it extend beyond the mapped region?
163     lr.Flags.ExtendsAfter = hp < HT.HstPtrEnd && (hp + Size) > HT.HstPtrEnd;
164   }
165 
166   // check the right bin
167   if (!(lr.Flags.IsContained || lr.Flags.ExtendsAfter) &&
168       upper != HostDataToTargetMap.end()) {
169     lr.Entry = upper;
170     auto &HT = *lr.Entry;
171     // Does it extend into an already mapped region?
172     lr.Flags.ExtendsBefore =
173         hp < HT.HstPtrBegin && (hp + Size) > HT.HstPtrBegin;
174     // Does it extend beyond the mapped region?
175     lr.Flags.ExtendsAfter = hp < HT.HstPtrEnd && (hp + Size) > HT.HstPtrEnd;
176   }
177 
178   if (lr.Flags.ExtendsBefore) {
179     DP("WARNING: Pointer is not mapped but section extends into already "
180        "mapped data\n");
181   }
182   if (lr.Flags.ExtendsAfter) {
183     DP("WARNING: Pointer is already mapped but section extends beyond mapped "
184        "region\n");
185   }
186 
187   return lr;
188 }
189 
190 // Used by targetDataBegin
191 // Return the target pointer begin (where the data will be moved).
192 // Allocate memory if this is the first occurrence of this mapping.
193 // Increment the reference counter.
194 // If NULL is returned, then either data allocation failed or the user tried
195 // to do an illegal mapping.
196 void *DeviceTy::getOrAllocTgtPtr(void *HstPtrBegin, void *HstPtrBase,
197                                  int64_t Size, map_var_info_t HstPtrName,
198                                  bool &IsNew, bool &IsHostPtr, bool IsImplicit,
199                                  bool UpdateRefCount, bool HasCloseModifier,
200                                  bool HasPresentModifier) {
201   void *rc = NULL;
202   IsHostPtr = false;
203   IsNew = false;
204   DataMapMtx.lock();
205   LookupResult lr = lookupMapping(HstPtrBegin, Size);
206 
207   // Check if the pointer is contained.
208   // If a variable is mapped to the device manually by the user - which would
209   // lead to the IsContained flag to be true - then we must ensure that the
210   // device address is returned even under unified memory conditions.
211   if (lr.Flags.IsContained ||
212       ((lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) && IsImplicit)) {
213     auto &HT = *lr.Entry;
214     IsNew = false;
215 
216     if (UpdateRefCount)
217       HT.incRefCount();
218 
219     uintptr_t tp = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
220     INFO(OMP_INFOTYPE_MAPPING_EXISTS, DeviceID,
221          "Mapping exists%s with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD
222          ", "
223          "Size=%" PRId64 ",%s RefCount=%s, Name=%s\n",
224          (IsImplicit ? " (implicit)" : ""), DPxPTR(HstPtrBegin), DPxPTR(tp),
225          Size, (UpdateRefCount ? " updated" : ""),
226          HT.isRefCountInf() ? "INF" : std::to_string(HT.getRefCount()).c_str(),
227          (HstPtrName) ? getNameFromMapping(HstPtrName).c_str() : "unknown");
228     rc = (void *)tp;
229   } else if ((lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) && !IsImplicit) {
230     // Explicit extension of mapped data - not allowed.
231     MESSAGE("explicit extension not allowed: host address specified is " DPxMOD
232             " (%" PRId64
233             " bytes), but device allocation maps to host at " DPxMOD
234             " (%" PRId64 " bytes)",
235             DPxPTR(HstPtrBegin), Size, DPxPTR(lr.Entry->HstPtrBegin),
236             lr.Entry->HstPtrEnd - lr.Entry->HstPtrBegin);
237     if (HasPresentModifier)
238       MESSAGE("device mapping required by 'present' map type modifier does not "
239               "exist for host address " DPxMOD " (%" PRId64 " bytes)",
240               DPxPTR(HstPtrBegin), Size);
241   } else if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
242              !HasCloseModifier) {
243     // If unified shared memory is active, implicitly mapped variables that are
244     // not privatized use host address. Any explicitly mapped variables also use
245     // host address where correctness is not impeded. In all other cases maps
246     // are respected.
247     // In addition to the mapping rules above, the close map modifier forces the
248     // mapping of the variable to the device.
249     if (Size) {
250       DP("Return HstPtrBegin " DPxMOD " Size=%" PRId64 " RefCount=%s\n",
251          DPxPTR((uintptr_t)HstPtrBegin), Size,
252          (UpdateRefCount ? " updated" : ""));
253       IsHostPtr = true;
254       rc = HstPtrBegin;
255     }
256   } else if (HasPresentModifier) {
257     DP("Mapping required by 'present' map type modifier does not exist for "
258        "HstPtrBegin=" DPxMOD ", Size=%" PRId64 "\n",
259        DPxPTR(HstPtrBegin), Size);
260     MESSAGE("device mapping required by 'present' map type modifier does not "
261             "exist for host address " DPxMOD " (%" PRId64 " bytes)",
262             DPxPTR(HstPtrBegin), Size);
263   } else if (Size) {
264     // If it is not contained and Size > 0, we should create a new entry for it.
265     IsNew = true;
266     uintptr_t tp = (uintptr_t)allocData(Size, HstPtrBegin);
267     INFO(OMP_INFOTYPE_MAPPING_CHANGED, DeviceID,
268          "Creating new map entry with "
269          "HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", Size=%ld, Name=%s\n",
270          DPxPTR(HstPtrBegin), DPxPTR(tp), Size,
271          (HstPtrName) ? getNameFromMapping(HstPtrName).c_str() : "unknown");
272     HostDataToTargetMap.emplace(
273         HostDataToTargetTy((uintptr_t)HstPtrBase, (uintptr_t)HstPtrBegin,
274                            (uintptr_t)HstPtrBegin + Size, tp, HstPtrName));
275     rc = (void *)tp;
276   }
277 
278   DataMapMtx.unlock();
279   return rc;
280 }
281 
282 // Used by targetDataBegin, targetDataEnd, targetDataUpdate and target.
283 // Return the target pointer begin (where the data will be moved).
284 // Decrement the reference counter if called from targetDataEnd.
285 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size, bool &IsLast,
286                                bool UpdateRefCount, bool &IsHostPtr,
287                                bool MustContain) {
288   void *rc = NULL;
289   IsHostPtr = false;
290   IsLast = false;
291   DataMapMtx.lock();
292   LookupResult lr = lookupMapping(HstPtrBegin, Size);
293 
294   if (lr.Flags.IsContained ||
295       (!MustContain && (lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter))) {
296     auto &HT = *lr.Entry;
297     IsLast = HT.getRefCount() == 1;
298 
299     if (!IsLast && UpdateRefCount)
300       HT.decRefCount();
301 
302     uintptr_t tp = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
303     DP("Mapping exists with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", "
304        "Size=%" PRId64 ",%s RefCount=%s\n",
305        DPxPTR(HstPtrBegin), DPxPTR(tp), Size,
306        (UpdateRefCount ? " updated" : ""),
307        HT.isRefCountInf() ? "INF" : std::to_string(HT.getRefCount()).c_str());
308     rc = (void *)tp;
309   } else if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
310     // If the value isn't found in the mapping and unified shared memory
311     // is on then it means we have stumbled upon a value which we need to
312     // use directly from the host.
313     DP("Get HstPtrBegin " DPxMOD " Size=%" PRId64 " RefCount=%s\n",
314        DPxPTR((uintptr_t)HstPtrBegin), Size,
315        (UpdateRefCount ? " updated" : ""));
316     IsHostPtr = true;
317     rc = HstPtrBegin;
318   }
319 
320   DataMapMtx.unlock();
321   return rc;
322 }
323 
324 // Return the target pointer begin (where the data will be moved).
325 // Lock-free version called when loading global symbols from the fat binary.
326 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size) {
327   uintptr_t hp = (uintptr_t)HstPtrBegin;
328   LookupResult lr = lookupMapping(HstPtrBegin, Size);
329   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
330     auto &HT = *lr.Entry;
331     uintptr_t tp = HT.TgtPtrBegin + (hp - HT.HstPtrBegin);
332     return (void *)tp;
333   }
334 
335   return NULL;
336 }
337 
338 int DeviceTy::deallocTgtPtr(void *HstPtrBegin, int64_t Size, bool ForceDelete,
339                             bool HasCloseModifier) {
340   if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
341       !HasCloseModifier)
342     return OFFLOAD_SUCCESS;
343   // Check if the pointer is contained in any sub-nodes.
344   int rc;
345   DataMapMtx.lock();
346   LookupResult lr = lookupMapping(HstPtrBegin, Size);
347   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
348     auto &HT = *lr.Entry;
349     if (ForceDelete)
350       HT.resetRefCount();
351     if (HT.decRefCount() == 0) {
352       DP("Deleting tgt data " DPxMOD " of size %" PRId64 "\n",
353          DPxPTR(HT.TgtPtrBegin), Size);
354       deleteData((void *)HT.TgtPtrBegin);
355       INFO(OMP_INFOTYPE_MAPPING_CHANGED, DeviceID,
356            "Removing%s map entry with HstPtrBegin=" DPxMOD
357            ", TgtPtrBegin=" DPxMOD ", Size=%" PRId64 ", Name=%s\n",
358            (ForceDelete ? " (forced)" : ""), DPxPTR(HT.HstPtrBegin),
359            DPxPTR(HT.TgtPtrBegin), Size,
360            (HT.HstPtrName) ? getNameFromMapping(HT.HstPtrName).c_str()
361                            : "unknown");
362       HostDataToTargetMap.erase(lr.Entry);
363     }
364     rc = OFFLOAD_SUCCESS;
365   } else {
366     REPORT("Section to delete (hst addr " DPxMOD ") does not exist in the"
367            " allocated memory\n",
368            DPxPTR(HstPtrBegin));
369     rc = OFFLOAD_FAIL;
370   }
371 
372   DataMapMtx.unlock();
373   return rc;
374 }
375 
376 /// Init device, should not be called directly.
377 void DeviceTy::init() {
378   // Make call to init_requires if it exists for this plugin.
379   if (RTL->init_requires)
380     RTL->init_requires(PM->RTLs.RequiresFlags);
381   int32_t Ret = RTL->init_device(RTLDeviceID);
382   if (Ret != OFFLOAD_SUCCESS)
383     return;
384 
385   IsInit = true;
386 }
387 
388 /// Thread-safe method to initialize the device only once.
389 int32_t DeviceTy::initOnce() {
390   std::call_once(InitFlag, &DeviceTy::init, this);
391 
392   // At this point, if IsInit is true, then either this thread or some other
393   // thread in the past successfully initialized the device, so we can return
394   // OFFLOAD_SUCCESS. If this thread executed init() via call_once() and it
395   // failed, return OFFLOAD_FAIL. If call_once did not invoke init(), it means
396   // that some other thread already attempted to execute init() and if IsInit
397   // is still false, return OFFLOAD_FAIL.
398   if (IsInit)
399     return OFFLOAD_SUCCESS;
400   else
401     return OFFLOAD_FAIL;
402 }
403 
404 // Load binary to device.
405 __tgt_target_table *DeviceTy::load_binary(void *Img) {
406   RTL->Mtx.lock();
407   __tgt_target_table *rc = RTL->load_binary(RTLDeviceID, Img);
408   RTL->Mtx.unlock();
409   return rc;
410 }
411 
412 void *DeviceTy::allocData(int64_t Size, void *HstPtr, int32_t Kind) {
413   return RTL->data_alloc(RTLDeviceID, Size, HstPtr, Kind);
414 }
415 
416 int32_t DeviceTy::deleteData(void *TgtPtrBegin) {
417   return RTL->data_delete(RTLDeviceID, TgtPtrBegin);
418 }
419 
420 // Submit data to device
421 int32_t DeviceTy::submitData(void *TgtPtrBegin, void *HstPtrBegin, int64_t Size,
422                              AsyncInfoTy &AsyncInfo) {
423   if (getInfoLevel() & OMP_INFOTYPE_DATA_TRANSFER) {
424     LookupResult LR = lookupMapping(HstPtrBegin, Size);
425     auto *HT = &*LR.Entry;
426 
427     INFO(OMP_INFOTYPE_DATA_TRANSFER, DeviceID,
428          "Copying data from host to device, HstPtr=" DPxMOD ", TgtPtr=" DPxMOD
429          ", Size=%" PRId64 ", Name=%s\n",
430          DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin), Size,
431          (HT && HT->HstPtrName) ? getNameFromMapping(HT->HstPtrName).c_str()
432                                 : "unknown");
433   }
434 
435   if (!AsyncInfo || !RTL->data_submit_async || !RTL->synchronize)
436     return RTL->data_submit(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size);
437   else
438     return RTL->data_submit_async(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size,
439                                   AsyncInfo);
440 }
441 
442 // Retrieve data from device
443 int32_t DeviceTy::retrieveData(void *HstPtrBegin, void *TgtPtrBegin,
444                                int64_t Size, AsyncInfoTy &AsyncInfo) {
445   if (getInfoLevel() & OMP_INFOTYPE_DATA_TRANSFER) {
446     LookupResult LR = lookupMapping(HstPtrBegin, Size);
447     auto *HT = &*LR.Entry;
448     INFO(OMP_INFOTYPE_DATA_TRANSFER, DeviceID,
449          "Copying data from device to host, TgtPtr=" DPxMOD ", HstPtr=" DPxMOD
450          ", Size=%" PRId64 ", Name=%s\n",
451          DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin), Size,
452          (HT && HT->HstPtrName) ? getNameFromMapping(HT->HstPtrName).c_str()
453                                 : "unknown");
454   }
455 
456   if (!RTL->data_retrieve_async || !RTL->synchronize)
457     return RTL->data_retrieve(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size);
458   else
459     return RTL->data_retrieve_async(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size,
460                                     AsyncInfo);
461 }
462 
463 // Copy data from current device to destination device directly
464 int32_t DeviceTy::dataExchange(void *SrcPtr, DeviceTy &DstDev, void *DstPtr,
465                                int64_t Size, AsyncInfoTy &AsyncInfo) {
466   if (!AsyncInfo || !RTL->data_exchange_async || !RTL->synchronize) {
467     assert(RTL->data_exchange && "RTL->data_exchange is nullptr");
468     return RTL->data_exchange(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID, DstPtr,
469                               Size);
470   } else
471     return RTL->data_exchange_async(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID,
472                                     DstPtr, Size, AsyncInfo);
473 }
474 
475 // Run region on device
476 int32_t DeviceTy::runRegion(void *TgtEntryPtr, void **TgtVarsPtr,
477                             ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
478                             AsyncInfoTy &AsyncInfo) {
479   if (!RTL->run_region || !RTL->synchronize)
480     return RTL->run_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr, TgtOffsets,
481                            TgtVarsSize);
482   else
483     return RTL->run_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
484                                  TgtOffsets, TgtVarsSize, AsyncInfo);
485 }
486 
487 // Run team region on device.
488 int32_t DeviceTy::runTeamRegion(void *TgtEntryPtr, void **TgtVarsPtr,
489                                 ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
490                                 int32_t NumTeams, int32_t ThreadLimit,
491                                 uint64_t LoopTripCount,
492                                 AsyncInfoTy &AsyncInfo) {
493   if (!RTL->run_team_region_async || !RTL->synchronize)
494     return RTL->run_team_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
495                                 TgtOffsets, TgtVarsSize, NumTeams, ThreadLimit,
496                                 LoopTripCount);
497   else
498     return RTL->run_team_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
499                                       TgtOffsets, TgtVarsSize, NumTeams,
500                                       ThreadLimit, LoopTripCount, AsyncInfo);
501 }
502 
503 // Whether data can be copied to DstDevice directly
504 bool DeviceTy::isDataExchangable(const DeviceTy &DstDevice) {
505   if (RTL != DstDevice.RTL || !RTL->is_data_exchangable)
506     return false;
507 
508   if (RTL->is_data_exchangable(RTLDeviceID, DstDevice.RTLDeviceID))
509     return (RTL->data_exchange != nullptr) ||
510            (RTL->data_exchange_async != nullptr);
511 
512   return false;
513 }
514 
515 int32_t DeviceTy::synchronize(AsyncInfoTy &AsyncInfo) {
516   if (RTL->synchronize)
517     return RTL->synchronize(RTLDeviceID, AsyncInfo);
518   return OFFLOAD_SUCCESS;
519 }
520 
521 /// Check whether a device has an associated RTL and initialize it if it's not
522 /// already initialized.
523 bool device_is_ready(int device_num) {
524   DP("Checking whether device %d is ready.\n", device_num);
525   // Devices.size() can only change while registering a new
526   // library, so try to acquire the lock of RTLs' mutex.
527   PM->RTLsMtx.lock();
528   size_t DevicesSize = PM->Devices.size();
529   PM->RTLsMtx.unlock();
530   if (DevicesSize <= (size_t)device_num) {
531     DP("Device ID  %d does not have a matching RTL\n", device_num);
532     return false;
533   }
534 
535   // Get device info
536   DeviceTy &Device = PM->Devices[device_num];
537 
538   DP("Is the device %d (local ID %d) initialized? %d\n", device_num,
539      Device.RTLDeviceID, Device.IsInit);
540 
541   // Init the device if not done before
542   if (!Device.IsInit && Device.initOnce() != OFFLOAD_SUCCESS) {
543     DP("Failed to init device %d\n", device_num);
544     return false;
545   }
546 
547   DP("Device %d is ready to use.\n", device_num);
548 
549   return true;
550 }
551