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   const HostDataToTargetTy &newEntry =
80       *HostDataToTargetMap
81            .emplace(
82                /*HstPtrBase=*/(uintptr_t)HstPtrBegin,
83                /*HstPtrBegin=*/(uintptr_t)HstPtrBegin,
84                /*HstPtrEnd=*/(uintptr_t)HstPtrBegin + Size,
85                /*TgtPtrBegin=*/(uintptr_t)TgtPtrBegin,
86                /*UseHoldRefCount=*/false, /*Name=*/nullptr,
87                /*IsRefCountINF=*/true)
88            .first;
89   DP("Creating new map entry: HstBase=" DPxMOD ", HstBegin=" DPxMOD
90      ", HstEnd=" DPxMOD ", TgtBegin=" DPxMOD ", DynRefCount=%s, "
91      "HoldRefCount=%s\n",
92      DPxPTR(newEntry.HstPtrBase), DPxPTR(newEntry.HstPtrBegin),
93      DPxPTR(newEntry.HstPtrEnd), DPxPTR(newEntry.TgtPtrBegin),
94      newEntry.dynRefCountToStr().c_str(), newEntry.holdRefCountToStr().c_str());
95   (void)newEntry;
96 
97   DataMapMtx.unlock();
98 
99   return OFFLOAD_SUCCESS;
100 }
101 
102 int DeviceTy::disassociatePtr(void *HstPtrBegin) {
103   DataMapMtx.lock();
104 
105   auto search = HostDataToTargetMap.find(HstPtrBeginTy{(uintptr_t)HstPtrBegin});
106   if (search != HostDataToTargetMap.end()) {
107     // Mapping exists
108     if (search->getHoldRefCount()) {
109       // This is based on OpenACC 3.1, sec 3.2.33 "acc_unmap_data", L3656-3657:
110       // "It is an error to call acc_unmap_data if the structured reference
111       // count for the pointer is not zero."
112       REPORT("Trying to disassociate a pointer with a non-zero hold reference "
113              "count\n");
114     } else if (search->isDynRefCountInf()) {
115       DP("Association found, removing it\n");
116       HostDataToTargetMap.erase(search);
117       DataMapMtx.unlock();
118       return OFFLOAD_SUCCESS;
119     } else {
120       REPORT("Trying to disassociate a pointer which was not mapped via "
121              "omp_target_associate_ptr\n");
122     }
123   } else {
124     REPORT("Association not found\n");
125   }
126 
127   // Mapping not found
128   DataMapMtx.unlock();
129   return OFFLOAD_FAIL;
130 }
131 
132 LookupResult DeviceTy::lookupMapping(void *HstPtrBegin, int64_t Size) {
133   uintptr_t hp = (uintptr_t)HstPtrBegin;
134   LookupResult lr;
135 
136   DP("Looking up mapping(HstPtrBegin=" DPxMOD ", Size=%" PRId64 ")...\n",
137      DPxPTR(hp), Size);
138 
139   if (HostDataToTargetMap.empty())
140     return lr;
141 
142   auto upper = HostDataToTargetMap.upper_bound(hp);
143   // check the left bin
144   if (upper != HostDataToTargetMap.begin()) {
145     lr.Entry = std::prev(upper);
146     auto &HT = *lr.Entry;
147     // Is it contained?
148     lr.Flags.IsContained = hp >= HT.HstPtrBegin && hp < HT.HstPtrEnd &&
149                            (hp + Size) <= HT.HstPtrEnd;
150     // Does it extend beyond the mapped region?
151     lr.Flags.ExtendsAfter = hp < HT.HstPtrEnd && (hp + Size) > HT.HstPtrEnd;
152   }
153 
154   // check the right bin
155   if (!(lr.Flags.IsContained || lr.Flags.ExtendsAfter) &&
156       upper != HostDataToTargetMap.end()) {
157     lr.Entry = upper;
158     auto &HT = *lr.Entry;
159     // Does it extend into an already mapped region?
160     lr.Flags.ExtendsBefore =
161         hp < HT.HstPtrBegin && (hp + Size) > HT.HstPtrBegin;
162     // Does it extend beyond the mapped region?
163     lr.Flags.ExtendsAfter = hp < HT.HstPtrEnd && (hp + Size) > HT.HstPtrEnd;
164   }
165 
166   if (lr.Flags.ExtendsBefore) {
167     DP("WARNING: Pointer is not mapped but section extends into already "
168        "mapped data\n");
169   }
170   if (lr.Flags.ExtendsAfter) {
171     DP("WARNING: Pointer is already mapped but section extends beyond mapped "
172        "region\n");
173   }
174 
175   return lr;
176 }
177 
178 TargetPointerResultTy
179 DeviceTy::getTargetPointer(void *HstPtrBegin, void *HstPtrBase, int64_t Size,
180                            map_var_info_t HstPtrName, bool HasFlagTo,
181                            bool HasFlagAlways, bool IsImplicit,
182                            bool UpdateRefCount, bool HasCloseModifier,
183                            bool HasPresentModifier, bool HasHoldModifier,
184                            AsyncInfoTy &AsyncInfo) {
185   void *TargetPointer = nullptr;
186   bool IsHostPtr = false;
187   bool IsNew = false;
188 
189   DataMapMtx.lock();
190 
191   LookupResult LR = lookupMapping(HstPtrBegin, Size);
192   auto Entry = LR.Entry;
193 
194   // Check if the pointer is contained.
195   // If a variable is mapped to the device manually by the user - which would
196   // lead to the IsContained flag to be true - then we must ensure that the
197   // device address is returned even under unified memory conditions.
198   if (LR.Flags.IsContained ||
199       ((LR.Flags.ExtendsBefore || LR.Flags.ExtendsAfter) && IsImplicit)) {
200     auto &HT = *LR.Entry;
201     const char *RefCountAction;
202     assert(HT.getTotalRefCount() > 0 && "expected existing RefCount > 0");
203     if (UpdateRefCount) {
204       // After this, RefCount > 1.
205       HT.incRefCount(HasHoldModifier);
206       RefCountAction = " (incremented)";
207     } else {
208       // It might have been allocated with the parent, but it's still new.
209       IsNew = HT.getTotalRefCount() == 1;
210       RefCountAction = " (update suppressed)";
211     }
212     const char *DynRefCountAction = HasHoldModifier ? "" : RefCountAction;
213     const char *HoldRefCountAction = HasHoldModifier ? RefCountAction : "";
214     uintptr_t Ptr = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
215     INFO(OMP_INFOTYPE_MAPPING_EXISTS, DeviceID,
216          "Mapping exists%s with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD
217          ", Size=%" PRId64 ", DynRefCount=%s%s, HoldRefCount=%s%s, Name=%s\n",
218          (IsImplicit ? " (implicit)" : ""), DPxPTR(HstPtrBegin), DPxPTR(Ptr),
219          Size, HT.dynRefCountToStr().c_str(), DynRefCountAction,
220          HT.holdRefCountToStr().c_str(), HoldRefCountAction,
221          (HstPtrName) ? getNameFromMapping(HstPtrName).c_str() : "unknown");
222     TargetPointer = (void *)Ptr;
223   } else if ((LR.Flags.ExtendsBefore || LR.Flags.ExtendsAfter) && !IsImplicit) {
224     // Explicit extension of mapped data - not allowed.
225     MESSAGE("explicit extension not allowed: host address specified is " DPxMOD
226             " (%" PRId64
227             " bytes), but device allocation maps to host at " DPxMOD
228             " (%" PRId64 " bytes)",
229             DPxPTR(HstPtrBegin), Size, DPxPTR(Entry->HstPtrBegin),
230             Entry->HstPtrEnd - Entry->HstPtrBegin);
231     if (HasPresentModifier)
232       MESSAGE("device mapping required by 'present' map type modifier does not "
233               "exist for host address " DPxMOD " (%" PRId64 " bytes)",
234               DPxPTR(HstPtrBegin), Size);
235   } else if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
236              !HasCloseModifier) {
237     // If unified shared memory is active, implicitly mapped variables that are
238     // not privatized use host address. Any explicitly mapped variables also use
239     // host address where correctness is not impeded. In all other cases maps
240     // are respected.
241     // In addition to the mapping rules above, the close map modifier forces the
242     // mapping of the variable to the device.
243     if (Size) {
244       DP("Return HstPtrBegin " DPxMOD " Size=%" PRId64 " for unified shared "
245          "memory\n",
246          DPxPTR((uintptr_t)HstPtrBegin), Size);
247       IsHostPtr = true;
248       TargetPointer = HstPtrBegin;
249     }
250   } else if (HasPresentModifier) {
251     DP("Mapping required by 'present' map type modifier does not exist for "
252        "HstPtrBegin=" DPxMOD ", Size=%" PRId64 "\n",
253        DPxPTR(HstPtrBegin), Size);
254     MESSAGE("device mapping required by 'present' map type modifier does not "
255             "exist for host address " DPxMOD " (%" PRId64 " bytes)",
256             DPxPTR(HstPtrBegin), Size);
257   } else if (Size) {
258     // If it is not contained and Size > 0, we should create a new entry for it.
259     IsNew = true;
260     uintptr_t Ptr = (uintptr_t)allocData(Size, HstPtrBegin);
261     Entry = HostDataToTargetMap
262                 .emplace((uintptr_t)HstPtrBase, (uintptr_t)HstPtrBegin,
263                          (uintptr_t)HstPtrBegin + Size, Ptr, HasHoldModifier,
264                          HstPtrName)
265                 .first;
266     INFO(OMP_INFOTYPE_MAPPING_CHANGED, DeviceID,
267          "Creating new map entry with "
268          "HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", Size=%ld, "
269          "DynRefCount=%s, HoldRefCount=%s, Name=%s\n",
270          DPxPTR(HstPtrBegin), DPxPTR(Ptr), Size,
271          Entry->dynRefCountToStr().c_str(), Entry->holdRefCountToStr().c_str(),
272          (HstPtrName) ? getNameFromMapping(HstPtrName).c_str() : "unknown");
273     TargetPointer = (void *)Ptr;
274   }
275 
276   // If the target pointer is valid, and we need to transfer data, issue the
277   // data transfer.
278   if (TargetPointer && !IsHostPtr && HasFlagTo && (IsNew || HasFlagAlways)) {
279     // Lock the entry before releasing the mapping table lock such that another
280     // thread that could issue data movement will get the right result.
281     Entry->lock();
282     // Release the mapping table lock right after the entry is locked.
283     DataMapMtx.unlock();
284 
285     DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n", Size,
286        DPxPTR(HstPtrBegin), DPxPTR(TargetPointer));
287 
288     int Ret = submitData(TargetPointer, HstPtrBegin, Size, AsyncInfo);
289 
290     // Unlock the entry immediately after the data movement is issued.
291     Entry->unlock();
292 
293     if (Ret != OFFLOAD_SUCCESS) {
294       REPORT("Copying data to device failed.\n");
295       // We will also return nullptr if the data movement fails because that
296       // pointer points to a corrupted memory region so it doesn't make any
297       // sense to continue to use it.
298       TargetPointer = nullptr;
299     }
300   } else {
301     // Release the mapping table lock directly.
302     DataMapMtx.unlock();
303   }
304 
305   return {{IsNew, IsHostPtr}, Entry, TargetPointer};
306 }
307 
308 // Used by targetDataBegin, targetDataEnd, targetDataUpdate and target.
309 // Return the target pointer begin (where the data will be moved).
310 // Decrement the reference counter if called from targetDataEnd.
311 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size, bool &IsLast,
312                                bool UpdateRefCount, bool UseHoldRefCount,
313                                bool &IsHostPtr, bool MustContain,
314                                bool ForceDelete) {
315   void *rc = NULL;
316   IsHostPtr = false;
317   IsLast = false;
318   DataMapMtx.lock();
319   LookupResult lr = lookupMapping(HstPtrBegin, Size);
320 
321   if (lr.Flags.IsContained ||
322       (!MustContain && (lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter))) {
323     auto &HT = *lr.Entry;
324     // We do not zero the total reference count here.  deallocTgtPtr does that
325     // atomically with removing the mapping.  Otherwise, before this thread
326     // removed the mapping in deallocTgtPtr, another thread could retrieve the
327     // mapping, increment and decrement back to zero, and then both threads
328     // would try to remove the mapping, resulting in a double free.
329     IsLast = HT.decShouldRemove(UseHoldRefCount, ForceDelete);
330     const char *RefCountAction;
331     if (!UpdateRefCount) {
332       RefCountAction = " (update suppressed)";
333     } else if (ForceDelete) {
334       HT.resetRefCount(UseHoldRefCount);
335       assert(IsLast == HT.decShouldRemove(UseHoldRefCount) &&
336              "expected correct IsLast prediction for reset");
337       if (IsLast)
338         RefCountAction = " (reset, deferred final decrement)";
339       else {
340         HT.decRefCount(UseHoldRefCount);
341         RefCountAction = " (reset)";
342       }
343     } else if (IsLast) {
344       RefCountAction = " (deferred final decrement)";
345     } else {
346       HT.decRefCount(UseHoldRefCount);
347       RefCountAction = " (decremented)";
348     }
349     const char *DynRefCountAction = UseHoldRefCount ? "" : RefCountAction;
350     const char *HoldRefCountAction = UseHoldRefCount ? RefCountAction : "";
351     uintptr_t tp = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
352     INFO(OMP_INFOTYPE_MAPPING_EXISTS, DeviceID,
353          "Mapping exists with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", "
354          "Size=%" PRId64 ", DynRefCount=%s%s, HoldRefCount=%s%s\n",
355          DPxPTR(HstPtrBegin), DPxPTR(tp), Size, HT.dynRefCountToStr().c_str(),
356          DynRefCountAction, HT.holdRefCountToStr().c_str(), HoldRefCountAction);
357     rc = (void *)tp;
358   } else if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
359     // If the value isn't found in the mapping and unified shared memory
360     // is on then it means we have stumbled upon a value which we need to
361     // use directly from the host.
362     DP("Get HstPtrBegin " DPxMOD " Size=%" PRId64 " for unified shared "
363        "memory\n",
364        DPxPTR((uintptr_t)HstPtrBegin), Size);
365     IsHostPtr = true;
366     rc = HstPtrBegin;
367   }
368 
369   DataMapMtx.unlock();
370   return rc;
371 }
372 
373 // Return the target pointer begin (where the data will be moved).
374 // Lock-free version called when loading global symbols from the fat binary.
375 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size) {
376   uintptr_t hp = (uintptr_t)HstPtrBegin;
377   LookupResult lr = lookupMapping(HstPtrBegin, Size);
378   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
379     auto &HT = *lr.Entry;
380     uintptr_t tp = HT.TgtPtrBegin + (hp - HT.HstPtrBegin);
381     return (void *)tp;
382   }
383 
384   return NULL;
385 }
386 
387 int DeviceTy::deallocTgtPtr(void *HstPtrBegin, int64_t Size,
388                             bool HasHoldModifier) {
389   // Check if the pointer is contained in any sub-nodes.
390   int rc;
391   DataMapMtx.lock();
392   LookupResult lr = lookupMapping(HstPtrBegin, Size);
393   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
394     auto &HT = *lr.Entry;
395     if (HT.decRefCount(HasHoldModifier) == 0) {
396       DP("Deleting tgt data " DPxMOD " of size %" PRId64 "\n",
397          DPxPTR(HT.TgtPtrBegin), Size);
398       deleteData((void *)HT.TgtPtrBegin);
399       INFO(OMP_INFOTYPE_MAPPING_CHANGED, DeviceID,
400            "Removing map entry with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD
401            ", Size=%" PRId64 ", Name=%s\n",
402            DPxPTR(HT.HstPtrBegin), DPxPTR(HT.TgtPtrBegin), Size,
403            (HT.HstPtrName) ? getNameFromMapping(HT.HstPtrName).c_str()
404                            : "unknown");
405       HostDataToTargetMap.erase(lr.Entry);
406     }
407     rc = OFFLOAD_SUCCESS;
408   } else {
409     REPORT("Section to delete (hst addr " DPxMOD ") does not exist in the"
410            " allocated memory\n",
411            DPxPTR(HstPtrBegin));
412     rc = OFFLOAD_FAIL;
413   }
414 
415   DataMapMtx.unlock();
416   return rc;
417 }
418 
419 /// Init device, should not be called directly.
420 void DeviceTy::init() {
421   // Make call to init_requires if it exists for this plugin.
422   if (RTL->init_requires)
423     RTL->init_requires(PM->RTLs.RequiresFlags);
424   int32_t Ret = RTL->init_device(RTLDeviceID);
425   if (Ret != OFFLOAD_SUCCESS)
426     return;
427 
428   IsInit = true;
429 }
430 
431 /// Thread-safe method to initialize the device only once.
432 int32_t DeviceTy::initOnce() {
433   std::call_once(InitFlag, &DeviceTy::init, this);
434 
435   // At this point, if IsInit is true, then either this thread or some other
436   // thread in the past successfully initialized the device, so we can return
437   // OFFLOAD_SUCCESS. If this thread executed init() via call_once() and it
438   // failed, return OFFLOAD_FAIL. If call_once did not invoke init(), it means
439   // that some other thread already attempted to execute init() and if IsInit
440   // is still false, return OFFLOAD_FAIL.
441   if (IsInit)
442     return OFFLOAD_SUCCESS;
443   else
444     return OFFLOAD_FAIL;
445 }
446 
447 // Load binary to device.
448 __tgt_target_table *DeviceTy::load_binary(void *Img) {
449   RTL->Mtx.lock();
450   __tgt_target_table *rc = RTL->load_binary(RTLDeviceID, Img);
451   RTL->Mtx.unlock();
452   return rc;
453 }
454 
455 void *DeviceTy::allocData(int64_t Size, void *HstPtr, int32_t Kind) {
456   return RTL->data_alloc(RTLDeviceID, Size, HstPtr, Kind);
457 }
458 
459 int32_t DeviceTy::deleteData(void *TgtPtrBegin) {
460   return RTL->data_delete(RTLDeviceID, TgtPtrBegin);
461 }
462 
463 // Submit data to device
464 int32_t DeviceTy::submitData(void *TgtPtrBegin, void *HstPtrBegin, int64_t Size,
465                              AsyncInfoTy &AsyncInfo) {
466   if (getInfoLevel() & OMP_INFOTYPE_DATA_TRANSFER) {
467     LookupResult LR = lookupMapping(HstPtrBegin, Size);
468     auto *HT = &*LR.Entry;
469 
470     INFO(OMP_INFOTYPE_DATA_TRANSFER, DeviceID,
471          "Copying data from host to device, HstPtr=" DPxMOD ", TgtPtr=" DPxMOD
472          ", Size=%" PRId64 ", Name=%s\n",
473          DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin), Size,
474          (HT && HT->HstPtrName) ? getNameFromMapping(HT->HstPtrName).c_str()
475                                 : "unknown");
476   }
477 
478   if (!AsyncInfo || !RTL->data_submit_async || !RTL->synchronize)
479     return RTL->data_submit(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size);
480   else
481     return RTL->data_submit_async(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size,
482                                   AsyncInfo);
483 }
484 
485 // Retrieve data from device
486 int32_t DeviceTy::retrieveData(void *HstPtrBegin, void *TgtPtrBegin,
487                                int64_t Size, AsyncInfoTy &AsyncInfo) {
488   if (getInfoLevel() & OMP_INFOTYPE_DATA_TRANSFER) {
489     LookupResult LR = lookupMapping(HstPtrBegin, Size);
490     auto *HT = &*LR.Entry;
491     INFO(OMP_INFOTYPE_DATA_TRANSFER, DeviceID,
492          "Copying data from device to host, TgtPtr=" DPxMOD ", HstPtr=" DPxMOD
493          ", Size=%" PRId64 ", Name=%s\n",
494          DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin), Size,
495          (HT && HT->HstPtrName) ? getNameFromMapping(HT->HstPtrName).c_str()
496                                 : "unknown");
497   }
498 
499   if (!RTL->data_retrieve_async || !RTL->synchronize)
500     return RTL->data_retrieve(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size);
501   else
502     return RTL->data_retrieve_async(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size,
503                                     AsyncInfo);
504 }
505 
506 // Copy data from current device to destination device directly
507 int32_t DeviceTy::dataExchange(void *SrcPtr, DeviceTy &DstDev, void *DstPtr,
508                                int64_t Size, AsyncInfoTy &AsyncInfo) {
509   if (!AsyncInfo || !RTL->data_exchange_async || !RTL->synchronize) {
510     assert(RTL->data_exchange && "RTL->data_exchange is nullptr");
511     return RTL->data_exchange(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID, DstPtr,
512                               Size);
513   } else
514     return RTL->data_exchange_async(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID,
515                                     DstPtr, Size, AsyncInfo);
516 }
517 
518 // Run region on device
519 int32_t DeviceTy::runRegion(void *TgtEntryPtr, void **TgtVarsPtr,
520                             ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
521                             AsyncInfoTy &AsyncInfo) {
522   if (!RTL->run_region || !RTL->synchronize)
523     return RTL->run_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr, TgtOffsets,
524                            TgtVarsSize);
525   else
526     return RTL->run_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
527                                  TgtOffsets, TgtVarsSize, AsyncInfo);
528 }
529 
530 // Run region on device
531 bool DeviceTy::printDeviceInfo(int32_t RTLDevId) {
532   if (!RTL->print_device_info)
533     return false;
534   RTL->print_device_info(RTLDevId);
535   return true;
536 }
537 
538 // Run team region on device.
539 int32_t DeviceTy::runTeamRegion(void *TgtEntryPtr, void **TgtVarsPtr,
540                                 ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
541                                 int32_t NumTeams, int32_t ThreadLimit,
542                                 uint64_t LoopTripCount,
543                                 AsyncInfoTy &AsyncInfo) {
544   if (!RTL->run_team_region_async || !RTL->synchronize)
545     return RTL->run_team_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
546                                 TgtOffsets, TgtVarsSize, NumTeams, ThreadLimit,
547                                 LoopTripCount);
548   else
549     return RTL->run_team_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
550                                       TgtOffsets, TgtVarsSize, NumTeams,
551                                       ThreadLimit, LoopTripCount, AsyncInfo);
552 }
553 
554 // Whether data can be copied to DstDevice directly
555 bool DeviceTy::isDataExchangable(const DeviceTy &DstDevice) {
556   if (RTL != DstDevice.RTL || !RTL->is_data_exchangable)
557     return false;
558 
559   if (RTL->is_data_exchangable(RTLDeviceID, DstDevice.RTLDeviceID))
560     return (RTL->data_exchange != nullptr) ||
561            (RTL->data_exchange_async != nullptr);
562 
563   return false;
564 }
565 
566 int32_t DeviceTy::synchronize(AsyncInfoTy &AsyncInfo) {
567   if (RTL->synchronize)
568     return RTL->synchronize(RTLDeviceID, AsyncInfo);
569   return OFFLOAD_SUCCESS;
570 }
571 
572 int32_t DeviceTy::createEvent(void **Event) {
573   if (RTL->create_event)
574     return RTL->create_event(RTLDeviceID, Event);
575 
576   return OFFLOAD_SUCCESS;
577 }
578 
579 int32_t DeviceTy::recordEvent(void *Event, AsyncInfoTy &AsyncInfo) {
580   if (RTL->record_event)
581     return RTL->record_event(RTLDeviceID, Event, AsyncInfo);
582 
583   return OFFLOAD_SUCCESS;
584 }
585 
586 int32_t DeviceTy::waitEvent(void *Event, AsyncInfoTy &AsyncInfo) {
587   if (RTL->wait_event)
588     return RTL->wait_event(RTLDeviceID, Event, AsyncInfo);
589 
590   return OFFLOAD_SUCCESS;
591 }
592 
593 int32_t DeviceTy::syncEvent(void *Event) {
594   if (RTL->sync_event)
595     return RTL->sync_event(RTLDeviceID, Event);
596 
597   return OFFLOAD_SUCCESS;
598 }
599 
600 int32_t DeviceTy::destroyEvent(void *Event) {
601   if (RTL->create_event)
602     return RTL->destroy_event(RTLDeviceID, Event);
603 
604   return OFFLOAD_SUCCESS;
605 }
606 
607 /// Check whether a device has an associated RTL and initialize it if it's not
608 /// already initialized.
609 bool device_is_ready(int device_num) {
610   DP("Checking whether device %d is ready.\n", device_num);
611   // Devices.size() can only change while registering a new
612   // library, so try to acquire the lock of RTLs' mutex.
613   PM->RTLsMtx.lock();
614   size_t DevicesSize = PM->Devices.size();
615   PM->RTLsMtx.unlock();
616   if (DevicesSize <= (size_t)device_num) {
617     DP("Device ID  %d does not have a matching RTL\n", device_num);
618     return false;
619   }
620 
621   // Get device info
622   DeviceTy &Device = PM->Devices[device_num];
623 
624   DP("Is the device %d (local ID %d) initialized? %d\n", device_num,
625      Device.RTLDeviceID, Device.IsInit);
626 
627   // Init the device if not done before
628   if (!Device.IsInit && Device.initOnce() != OFFLOAD_SUCCESS) {
629     DP("Failed to init device %d\n", device_num);
630     return false;
631   }
632 
633   DP("Device %d is ready to use.\n", device_num);
634 
635   return true;
636 }
637