1 //===------ omptarget.cpp - Target independent OpenMP target RTL -- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.txt for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implementation of the interface to be used by Clang during the codegen of a
11 // target region.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include <algorithm>
16 #include <cassert>
17 #include <climits>
18 #include <cstdlib>
19 #include <cstring>
20 #include <dlfcn.h>
21 #include <list>
22 #include <map>
23 #include <mutex>
24 #include <string>
25 #include <vector>
26 
27 // Header file global to this project
28 #include "omptarget.h"
29 
30 #define DP(...) DEBUGP("Libomptarget", __VA_ARGS__)
31 #define INF_REF_CNT (LONG_MAX>>1) // leave room for additions/subtractions
32 #define CONSIDERED_INF(x) (x > (INF_REF_CNT>>1))
33 
34 // List of all plugins that can support offloading.
35 static const char *RTLNames[] = {
36     /* PowerPC target */ "libomptarget.rtl.ppc64.so",
37     /* x86_64 target  */ "libomptarget.rtl.x86_64.so",
38     /* CUDA target    */ "libomptarget.rtl.cuda.so",
39     /* AArch64 target */ "libomptarget.rtl.aarch64.so"};
40 
41 // forward declarations
42 struct RTLInfoTy;
43 static int target(int32_t device_id, void *host_ptr, int32_t arg_num,
44     void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types,
45     int32_t team_num, int32_t thread_limit, int IsTeamConstruct);
46 
47 /// Map between host data and target data.
48 struct HostDataToTargetTy {
49   uintptr_t HstPtrBase; // host info.
50   uintptr_t HstPtrBegin;
51   uintptr_t HstPtrEnd; // non-inclusive.
52 
53   uintptr_t TgtPtrBegin; // target info.
54 
55   long RefCount;
56 
57   HostDataToTargetTy()
58       : HstPtrBase(0), HstPtrBegin(0), HstPtrEnd(0),
59         TgtPtrBegin(0), RefCount(0) {}
60   HostDataToTargetTy(uintptr_t BP, uintptr_t B, uintptr_t E, uintptr_t TB)
61       : HstPtrBase(BP), HstPtrBegin(B), HstPtrEnd(E),
62         TgtPtrBegin(TB), RefCount(1) {}
63   HostDataToTargetTy(uintptr_t BP, uintptr_t B, uintptr_t E, uintptr_t TB,
64       long RF)
65       : HstPtrBase(BP), HstPtrBegin(B), HstPtrEnd(E),
66         TgtPtrBegin(TB), RefCount(RF) {}
67 };
68 
69 typedef std::list<HostDataToTargetTy> HostDataToTargetListTy;
70 
71 struct LookupResult {
72   struct {
73     unsigned IsContained   : 1;
74     unsigned ExtendsBefore : 1;
75     unsigned ExtendsAfter  : 1;
76   } Flags;
77 
78   HostDataToTargetListTy::iterator Entry;
79 
80   LookupResult() : Flags({0,0,0}), Entry() {}
81 };
82 
83 /// Map for shadow pointers
84 struct ShadowPtrValTy {
85   void *HstPtrVal;
86   void *TgtPtrAddr;
87   void *TgtPtrVal;
88 };
89 typedef std::map<void *, ShadowPtrValTy> ShadowPtrListTy;
90 
91 ///
92 struct PendingCtorDtorListsTy {
93   std::list<void *> PendingCtors;
94   std::list<void *> PendingDtors;
95 };
96 typedef std::map<__tgt_bin_desc *, PendingCtorDtorListsTy>
97     PendingCtorsDtorsPerLibrary;
98 
99 struct DeviceTy {
100   int32_t DeviceID;
101   RTLInfoTy *RTL;
102   int32_t RTLDeviceID;
103 
104   bool IsInit;
105   std::once_flag InitFlag;
106   bool HasPendingGlobals;
107 
108   HostDataToTargetListTy HostDataToTargetMap;
109   PendingCtorsDtorsPerLibrary PendingCtorsDtors;
110 
111   ShadowPtrListTy ShadowPtrMap;
112 
113   std::mutex DataMapMtx, PendingGlobalsMtx, ShadowMtx;
114 
115   uint64_t loopTripCnt;
116 
117   DeviceTy(RTLInfoTy *RTL)
118       : DeviceID(-1), RTL(RTL), RTLDeviceID(-1), IsInit(false), InitFlag(),
119         HasPendingGlobals(false), HostDataToTargetMap(),
120         PendingCtorsDtors(), ShadowPtrMap(), DataMapMtx(), PendingGlobalsMtx(),
121         ShadowMtx(), loopTripCnt(0) {}
122 
123   // The existence of mutexes makes DeviceTy non-copyable. We need to
124   // provide a copy constructor and an assignment operator explicitly.
125   DeviceTy(const DeviceTy &d)
126       : DeviceID(d.DeviceID), RTL(d.RTL), RTLDeviceID(d.RTLDeviceID),
127         IsInit(d.IsInit), InitFlag(), HasPendingGlobals(d.HasPendingGlobals),
128         HostDataToTargetMap(d.HostDataToTargetMap),
129         PendingCtorsDtors(d.PendingCtorsDtors), ShadowPtrMap(d.ShadowPtrMap),
130         DataMapMtx(), PendingGlobalsMtx(),
131         ShadowMtx(), loopTripCnt(d.loopTripCnt) {}
132 
133   DeviceTy& operator=(const DeviceTy &d) {
134     DeviceID = d.DeviceID;
135     RTL = d.RTL;
136     RTLDeviceID = d.RTLDeviceID;
137     IsInit = d.IsInit;
138     HasPendingGlobals = d.HasPendingGlobals;
139     HostDataToTargetMap = d.HostDataToTargetMap;
140     PendingCtorsDtors = d.PendingCtorsDtors;
141     ShadowPtrMap = d.ShadowPtrMap;
142     loopTripCnt = d.loopTripCnt;
143 
144     return *this;
145   }
146 
147   long getMapEntryRefCnt(void *HstPtrBegin);
148   LookupResult lookupMapping(void *HstPtrBegin, int64_t Size);
149   void *getOrAllocTgtPtr(void *HstPtrBegin, void *HstPtrBase, int64_t Size,
150       bool &IsNew, bool IsImplicit, bool UpdateRefCount = true);
151   void *getTgtPtrBegin(void *HstPtrBegin, int64_t Size);
152   void *getTgtPtrBegin(void *HstPtrBegin, int64_t Size, bool &IsLast,
153       bool UpdateRefCount);
154   int deallocTgtPtr(void *TgtPtrBegin, int64_t Size, bool ForceDelete);
155   int associatePtr(void *HstPtrBegin, void *TgtPtrBegin, int64_t Size);
156   int disassociatePtr(void *HstPtrBegin);
157 
158   // calls to RTL
159   int32_t initOnce();
160   __tgt_target_table *load_binary(void *Img);
161 
162   int32_t data_submit(void *TgtPtrBegin, void *HstPtrBegin, int64_t Size);
163   int32_t data_retrieve(void *HstPtrBegin, void *TgtPtrBegin, int64_t Size);
164 
165   int32_t run_region(void *TgtEntryPtr, void **TgtVarsPtr,
166       ptrdiff_t *TgtOffsets, int32_t TgtVarsSize);
167   int32_t run_team_region(void *TgtEntryPtr, void **TgtVarsPtr,
168       ptrdiff_t *TgtOffsets, int32_t TgtVarsSize, int32_t NumTeams,
169       int32_t ThreadLimit, uint64_t LoopTripCount);
170 
171 private:
172   // Call to RTL
173   void init(); // To be called only via DeviceTy::initOnce()
174 };
175 
176 /// Map between Device ID (i.e. openmp device id) and its DeviceTy.
177 typedef std::vector<DeviceTy> DevicesTy;
178 static DevicesTy Devices;
179 
180 struct RTLInfoTy {
181   typedef int32_t(is_valid_binary_ty)(void *);
182   typedef int32_t(number_of_devices_ty)();
183   typedef int32_t(init_device_ty)(int32_t);
184   typedef __tgt_target_table *(load_binary_ty)(int32_t, void *);
185   typedef void *(data_alloc_ty)(int32_t, int64_t, void *);
186   typedef int32_t(data_submit_ty)(int32_t, void *, void *, int64_t);
187   typedef int32_t(data_retrieve_ty)(int32_t, void *, void *, int64_t);
188   typedef int32_t(data_delete_ty)(int32_t, void *);
189   typedef int32_t(run_region_ty)(int32_t, void *, void **, ptrdiff_t *,
190                                  int32_t);
191   typedef int32_t(run_team_region_ty)(int32_t, void *, void **, ptrdiff_t *,
192                                       int32_t, int32_t, int32_t, uint64_t);
193 
194   int32_t Idx;                     // RTL index, index is the number of devices
195                                    // of other RTLs that were registered before,
196                                    // i.e. the OpenMP index of the first device
197                                    // to be registered with this RTL.
198   int32_t NumberOfDevices;         // Number of devices this RTL deals with.
199   std::vector<DeviceTy *> Devices; // one per device (NumberOfDevices in total).
200 
201   void *LibraryHandler;
202 
203 #ifdef OMPTARGET_DEBUG
204   std::string RTLName;
205 #endif
206 
207   // Functions implemented in the RTL.
208   is_valid_binary_ty *is_valid_binary;
209   number_of_devices_ty *number_of_devices;
210   init_device_ty *init_device;
211   load_binary_ty *load_binary;
212   data_alloc_ty *data_alloc;
213   data_submit_ty *data_submit;
214   data_retrieve_ty *data_retrieve;
215   data_delete_ty *data_delete;
216   run_region_ty *run_region;
217   run_team_region_ty *run_team_region;
218 
219   // Are there images associated with this RTL.
220   bool isUsed;
221 
222   // Mutex for thread-safety when calling RTL interface functions.
223   // It is easier to enforce thread-safety at the libomptarget level,
224   // so that developers of new RTLs do not have to worry about it.
225   std::mutex Mtx;
226 
227   // The existence of the mutex above makes RTLInfoTy non-copyable.
228   // We need to provide a copy constructor explicitly.
229   RTLInfoTy()
230       : Idx(-1), NumberOfDevices(-1), Devices(), LibraryHandler(0),
231 #ifdef OMPTARGET_DEBUG
232         RTLName(),
233 #endif
234         is_valid_binary(0), number_of_devices(0), init_device(0),
235         load_binary(0), data_alloc(0), data_submit(0), data_retrieve(0),
236         data_delete(0), run_region(0), run_team_region(0), isUsed(false),
237         Mtx() {}
238 
239   RTLInfoTy(const RTLInfoTy &r) : Mtx() {
240     Idx = r.Idx;
241     NumberOfDevices = r.NumberOfDevices;
242     Devices = r.Devices;
243     LibraryHandler = r.LibraryHandler;
244 #ifdef OMPTARGET_DEBUG
245     RTLName = r.RTLName;
246 #endif
247     is_valid_binary = r.is_valid_binary;
248     number_of_devices = r.number_of_devices;
249     init_device = r.init_device;
250     load_binary = r.load_binary;
251     data_alloc = r.data_alloc;
252     data_submit = r.data_submit;
253     data_retrieve = r.data_retrieve;
254     data_delete = r.data_delete;
255     run_region = r.run_region;
256     run_team_region = r.run_team_region;
257     isUsed = r.isUsed;
258   }
259 };
260 
261 /// RTLs identified in the system.
262 class RTLsTy {
263 private:
264   // Mutex-like object to guarantee thread-safety and unique initialization
265   // (i.e. the library attempts to load the RTLs (plugins) only once).
266   std::once_flag initFlag;
267   void LoadRTLs(); // not thread-safe
268 
269 public:
270   // List of the detected runtime libraries.
271   std::list<RTLInfoTy> AllRTLs;
272 
273   // Array of pointers to the detected runtime libraries that have compatible
274   // binaries.
275   std::vector<RTLInfoTy *> UsedRTLs;
276 
277   explicit RTLsTy() {}
278 
279   // Load all the runtime libraries (plugins) if not done before.
280   void LoadRTLsOnce();
281 };
282 
283 void RTLsTy::LoadRTLs() {
284   // Parse environment variable OMP_TARGET_OFFLOAD (if set)
285   char *envStr = getenv("OMP_TARGET_OFFLOAD");
286   if (envStr && !strcmp(envStr, "DISABLED")) {
287     DP("Target offloading disabled by environment\n");
288     return;
289   }
290 
291   DP("Loading RTLs...\n");
292 
293   // Attempt to open all the plugins and, if they exist, check if the interface
294   // is correct and if they are supporting any devices.
295   for (auto *Name : RTLNames) {
296     DP("Loading library '%s'...\n", Name);
297     void *dynlib_handle = dlopen(Name, RTLD_NOW);
298 
299     if (!dynlib_handle) {
300       // Library does not exist or cannot be found.
301       DP("Unable to load library '%s': %s!\n", Name, dlerror());
302       continue;
303     }
304 
305     DP("Successfully loaded library '%s'!\n", Name);
306 
307     // Retrieve the RTL information from the runtime library.
308     RTLInfoTy R;
309 
310     R.LibraryHandler = dynlib_handle;
311     R.isUsed = false;
312 
313 #ifdef OMPTARGET_DEBUG
314     R.RTLName = Name;
315 #endif
316 
317     if (!(*((void**) &R.is_valid_binary) = dlsym(
318               dynlib_handle, "__tgt_rtl_is_valid_binary")))
319       continue;
320     if (!(*((void**) &R.number_of_devices) = dlsym(
321               dynlib_handle, "__tgt_rtl_number_of_devices")))
322       continue;
323     if (!(*((void**) &R.init_device) = dlsym(
324               dynlib_handle, "__tgt_rtl_init_device")))
325       continue;
326     if (!(*((void**) &R.load_binary) = dlsym(
327               dynlib_handle, "__tgt_rtl_load_binary")))
328       continue;
329     if (!(*((void**) &R.data_alloc) = dlsym(
330               dynlib_handle, "__tgt_rtl_data_alloc")))
331       continue;
332     if (!(*((void**) &R.data_submit) = dlsym(
333               dynlib_handle, "__tgt_rtl_data_submit")))
334       continue;
335     if (!(*((void**) &R.data_retrieve) = dlsym(
336               dynlib_handle, "__tgt_rtl_data_retrieve")))
337       continue;
338     if (!(*((void**) &R.data_delete) = dlsym(
339               dynlib_handle, "__tgt_rtl_data_delete")))
340       continue;
341     if (!(*((void**) &R.run_region) = dlsym(
342               dynlib_handle, "__tgt_rtl_run_target_region")))
343       continue;
344     if (!(*((void**) &R.run_team_region) = dlsym(
345               dynlib_handle, "__tgt_rtl_run_target_team_region")))
346       continue;
347 
348     // No devices are supported by this RTL?
349     if (!(R.NumberOfDevices = R.number_of_devices())) {
350       DP("No devices supported in this RTL\n");
351       continue;
352     }
353 
354     DP("Registering RTL %s supporting %d devices!\n",
355         R.RTLName.c_str(), R.NumberOfDevices);
356 
357     // The RTL is valid! Will save the information in the RTLs list.
358     AllRTLs.push_back(R);
359   }
360 
361   DP("RTLs loaded!\n");
362 
363   return;
364 }
365 
366 void RTLsTy::LoadRTLsOnce() {
367   // RTL.LoadRTLs() is called only once in a thread-safe fashion.
368   std::call_once(initFlag, &RTLsTy::LoadRTLs, this);
369 }
370 
371 static RTLsTy RTLs;
372 static std::mutex RTLsMtx;
373 
374 /// Map between the host entry begin and the translation table. Each
375 /// registered library gets one TranslationTable. Use the map from
376 /// __tgt_offload_entry so that we may quickly determine whether we
377 /// are trying to (re)register an existing lib or really have a new one.
378 struct TranslationTable {
379   __tgt_target_table HostTable;
380 
381   // Image assigned to a given device.
382   std::vector<__tgt_device_image *> TargetsImages; // One image per device ID.
383 
384   // Table of entry points or NULL if it was not already computed.
385   std::vector<__tgt_target_table *> TargetsTable; // One table per device ID.
386 };
387 typedef std::map<__tgt_offload_entry *, TranslationTable>
388     HostEntriesBeginToTransTableTy;
389 static HostEntriesBeginToTransTableTy HostEntriesBeginToTransTable;
390 static std::mutex TrlTblMtx;
391 
392 /// Map between the host ptr and a table index
393 struct TableMap {
394   TranslationTable *Table; // table associated with the host ptr.
395   uint32_t Index; // index in which the host ptr translated entry is found.
396   TableMap() : Table(0), Index(0) {}
397   TableMap(TranslationTable *table, uint32_t index)
398       : Table(table), Index(index) {}
399 };
400 typedef std::map<void *, TableMap> HostPtrToTableMapTy;
401 static HostPtrToTableMapTy HostPtrToTableMap;
402 static std::mutex TblMapMtx;
403 
404 /// Check whether a device has an associated RTL and initialize it if it's not
405 /// already initialized.
406 static bool device_is_ready(int device_num) {
407   DP("Checking whether device %d is ready.\n", device_num);
408   // Devices.size() can only change while registering a new
409   // library, so try to acquire the lock of RTLs' mutex.
410   RTLsMtx.lock();
411   size_t Devices_size = Devices.size();
412   RTLsMtx.unlock();
413   if (Devices_size <= (size_t)device_num) {
414     DP("Device ID  %d does not have a matching RTL\n", device_num);
415     return false;
416   }
417 
418   // Get device info
419   DeviceTy &Device = Devices[device_num];
420 
421   DP("Is the device %d (local ID %d) initialized? %d\n", device_num,
422        Device.RTLDeviceID, Device.IsInit);
423 
424   // Init the device if not done before
425   if (!Device.IsInit && Device.initOnce() != OFFLOAD_SUCCESS) {
426     DP("Failed to init device %d\n", device_num);
427     return false;
428   }
429 
430   DP("Device %d is ready to use.\n", device_num);
431 
432   return true;
433 }
434 
435 ////////////////////////////////////////////////////////////////////////////////
436 // Target API functions
437 //
438 EXTERN int omp_get_num_devices(void) {
439   RTLsMtx.lock();
440   size_t Devices_size = Devices.size();
441   RTLsMtx.unlock();
442 
443   DP("Call to omp_get_num_devices returning %zd\n", Devices_size);
444 
445   return Devices_size;
446 }
447 
448 EXTERN int omp_get_initial_device(void) {
449   DP("Call to omp_get_initial_device returning %d\n", HOST_DEVICE);
450   return HOST_DEVICE;
451 }
452 
453 EXTERN void *omp_target_alloc(size_t size, int device_num) {
454   DP("Call to omp_target_alloc for device %d requesting %zu bytes\n",
455       device_num, size);
456 
457   if (size <= 0) {
458     DP("Call to omp_target_alloc with non-positive length\n");
459     return NULL;
460   }
461 
462   void *rc = NULL;
463 
464   if (device_num == omp_get_initial_device()) {
465     rc = malloc(size);
466     DP("omp_target_alloc returns host ptr " DPxMOD "\n", DPxPTR(rc));
467     return rc;
468   }
469 
470   if (!device_is_ready(device_num)) {
471     DP("omp_target_alloc returns NULL ptr\n");
472     return NULL;
473   }
474 
475   DeviceTy &Device = Devices[device_num];
476   rc = Device.RTL->data_alloc(Device.RTLDeviceID, size, NULL);
477   DP("omp_target_alloc returns device ptr " DPxMOD "\n", DPxPTR(rc));
478   return rc;
479 }
480 
481 EXTERN void omp_target_free(void *device_ptr, int device_num) {
482   DP("Call to omp_target_free for device %d and address " DPxMOD "\n",
483       device_num, DPxPTR(device_ptr));
484 
485   if (!device_ptr) {
486     DP("Call to omp_target_free with NULL ptr\n");
487     return;
488   }
489 
490   if (device_num == omp_get_initial_device()) {
491     free(device_ptr);
492     DP("omp_target_free deallocated host ptr\n");
493     return;
494   }
495 
496   if (!device_is_ready(device_num)) {
497     DP("omp_target_free returns, nothing to do\n");
498     return;
499   }
500 
501   DeviceTy &Device = Devices[device_num];
502   Device.RTL->data_delete(Device.RTLDeviceID, (void *)device_ptr);
503   DP("omp_target_free deallocated device ptr\n");
504 }
505 
506 EXTERN int omp_target_is_present(void *ptr, int device_num) {
507   DP("Call to omp_target_is_present for device %d and address " DPxMOD "\n",
508       device_num, DPxPTR(ptr));
509 
510   if (!ptr) {
511     DP("Call to omp_target_is_present with NULL ptr, returning false\n");
512     return false;
513   }
514 
515   if (device_num == omp_get_initial_device()) {
516     DP("Call to omp_target_is_present on host, returning true\n");
517     return true;
518   }
519 
520   RTLsMtx.lock();
521   size_t Devices_size = Devices.size();
522   RTLsMtx.unlock();
523   if (Devices_size <= (size_t)device_num) {
524     DP("Call to omp_target_is_present with invalid device ID, returning "
525         "false\n");
526     return false;
527   }
528 
529   DeviceTy& Device = Devices[device_num];
530   bool IsLast; // not used
531   int rc = (Device.getTgtPtrBegin(ptr, 0, IsLast, false) != NULL);
532   DP("Call to omp_target_is_present returns %d\n", rc);
533   return rc;
534 }
535 
536 EXTERN int omp_target_memcpy(void *dst, void *src, size_t length,
537     size_t dst_offset, size_t src_offset, int dst_device, int src_device) {
538   DP("Call to omp_target_memcpy, dst device %d, src device %d, "
539       "dst addr " DPxMOD ", src addr " DPxMOD ", dst offset %zu, "
540       "src offset %zu, length %zu\n", dst_device, src_device, DPxPTR(dst),
541       DPxPTR(src), dst_offset, src_offset, length);
542 
543   if (!dst || !src || length <= 0) {
544     DP("Call to omp_target_memcpy with invalid arguments\n");
545     return OFFLOAD_FAIL;
546   }
547 
548   if (src_device != omp_get_initial_device() && !device_is_ready(src_device)) {
549       DP("omp_target_memcpy returns OFFLOAD_FAIL\n");
550       return OFFLOAD_FAIL;
551   }
552 
553   if (dst_device != omp_get_initial_device() && !device_is_ready(dst_device)) {
554       DP("omp_target_memcpy returns OFFLOAD_FAIL\n");
555       return OFFLOAD_FAIL;
556   }
557 
558   int rc = OFFLOAD_SUCCESS;
559   void *srcAddr = (char *)src + src_offset;
560   void *dstAddr = (char *)dst + dst_offset;
561 
562   if (src_device == omp_get_initial_device() &&
563       dst_device == omp_get_initial_device()) {
564     DP("copy from host to host\n");
565     const void *p = memcpy(dstAddr, srcAddr, length);
566     if (p == NULL)
567       rc = OFFLOAD_FAIL;
568   } else if (src_device == omp_get_initial_device()) {
569     DP("copy from host to device\n");
570     DeviceTy& DstDev = Devices[dst_device];
571     rc = DstDev.data_submit(dstAddr, srcAddr, length);
572   } else if (dst_device == omp_get_initial_device()) {
573     DP("copy from device to host\n");
574     DeviceTy& SrcDev = Devices[src_device];
575     rc = SrcDev.data_retrieve(dstAddr, srcAddr, length);
576   } else {
577     DP("copy from device to device\n");
578     void *buffer = malloc(length);
579     DeviceTy& SrcDev = Devices[src_device];
580     DeviceTy& DstDev = Devices[dst_device];
581     rc = SrcDev.data_retrieve(buffer, srcAddr, length);
582     if (rc == OFFLOAD_SUCCESS)
583       rc = DstDev.data_submit(dstAddr, buffer, length);
584   }
585 
586   DP("omp_target_memcpy returns %d\n", rc);
587   return rc;
588 }
589 
590 EXTERN int omp_target_memcpy_rect(void *dst, void *src, size_t element_size,
591     int num_dims, const size_t *volume, const size_t *dst_offsets,
592     const size_t *src_offsets, const size_t *dst_dimensions,
593     const size_t *src_dimensions, int dst_device, int src_device) {
594   DP("Call to omp_target_memcpy_rect, dst device %d, src device %d, "
595       "dst addr " DPxMOD ", src addr " DPxMOD ", dst offsets " DPxMOD ", "
596       "src offsets " DPxMOD ", dst dims " DPxMOD ", src dims " DPxMOD ", "
597       "volume " DPxMOD ", element size %zu, num_dims %d\n", dst_device,
598       src_device, DPxPTR(dst), DPxPTR(src), DPxPTR(dst_offsets),
599       DPxPTR(src_offsets), DPxPTR(dst_dimensions), DPxPTR(src_dimensions),
600       DPxPTR(volume), element_size, num_dims);
601 
602   if (!(dst || src)) {
603     DP("Call to omp_target_memcpy_rect returns max supported dimensions %d\n",
604         INT_MAX);
605     return INT_MAX;
606   }
607 
608   if (!dst || !src || element_size < 1 || num_dims < 1 || !volume ||
609       !dst_offsets || !src_offsets || !dst_dimensions || !src_dimensions) {
610     DP("Call to omp_target_memcpy_rect with invalid arguments\n");
611     return OFFLOAD_FAIL;
612   }
613 
614   int rc;
615   if (num_dims == 1) {
616     rc = omp_target_memcpy(dst, src, element_size * volume[0],
617         element_size * dst_offsets[0], element_size * src_offsets[0],
618         dst_device, src_device);
619   } else {
620     size_t dst_slice_size = element_size;
621     size_t src_slice_size = element_size;
622     for (int i=1; i<num_dims; ++i) {
623       dst_slice_size *= dst_dimensions[i];
624       src_slice_size *= src_dimensions[i];
625     }
626 
627     size_t dst_off = dst_offsets[0] * dst_slice_size;
628     size_t src_off = src_offsets[0] * src_slice_size;
629     for (size_t i=0; i<volume[0]; ++i) {
630       rc = omp_target_memcpy_rect((char *) dst + dst_off + dst_slice_size * i,
631           (char *) src + src_off + src_slice_size * i, element_size,
632           num_dims - 1, volume + 1, dst_offsets + 1, src_offsets + 1,
633           dst_dimensions + 1, src_dimensions + 1, dst_device, src_device);
634 
635       if (rc) {
636         DP("Recursive call to omp_target_memcpy_rect returns unsuccessfully\n");
637         return rc;
638       }
639     }
640   }
641 
642   DP("omp_target_memcpy_rect returns %d\n", rc);
643   return rc;
644 }
645 
646 EXTERN int omp_target_associate_ptr(void *host_ptr, void *device_ptr,
647     size_t size, size_t device_offset, int device_num) {
648   DP("Call to omp_target_associate_ptr with host_ptr " DPxMOD ", "
649       "device_ptr " DPxMOD ", size %zu, device_offset %zu, device_num %d\n",
650       DPxPTR(host_ptr), DPxPTR(device_ptr), size, device_offset, device_num);
651 
652   if (!host_ptr || !device_ptr || size <= 0) {
653     DP("Call to omp_target_associate_ptr with invalid arguments\n");
654     return OFFLOAD_FAIL;
655   }
656 
657   if (device_num == omp_get_initial_device()) {
658     DP("omp_target_associate_ptr: no association possible on the host\n");
659     return OFFLOAD_FAIL;
660   }
661 
662   if (!device_is_ready(device_num)) {
663     DP("omp_target_associate_ptr returns OFFLOAD_FAIL\n");
664     return OFFLOAD_FAIL;
665   }
666 
667   DeviceTy& Device = Devices[device_num];
668   void *device_addr = (void *)((uint64_t)device_ptr + (uint64_t)device_offset);
669   int rc = Device.associatePtr(host_ptr, device_addr, size);
670   DP("omp_target_associate_ptr returns %d\n", rc);
671   return rc;
672 }
673 
674 EXTERN int omp_target_disassociate_ptr(void *host_ptr, int device_num) {
675   DP("Call to omp_target_disassociate_ptr with host_ptr " DPxMOD ", "
676       "device_num %d\n", DPxPTR(host_ptr), device_num);
677 
678   if (!host_ptr) {
679     DP("Call to omp_target_associate_ptr with invalid host_ptr\n");
680     return OFFLOAD_FAIL;
681   }
682 
683   if (device_num == omp_get_initial_device()) {
684     DP("omp_target_disassociate_ptr: no association possible on the host\n");
685     return OFFLOAD_FAIL;
686   }
687 
688   if (!device_is_ready(device_num)) {
689     DP("omp_target_disassociate_ptr returns OFFLOAD_FAIL\n");
690     return OFFLOAD_FAIL;
691   }
692 
693   DeviceTy& Device = Devices[device_num];
694   int rc = Device.disassociatePtr(host_ptr);
695   DP("omp_target_disassociate_ptr returns %d\n", rc);
696   return rc;
697 }
698 
699 ////////////////////////////////////////////////////////////////////////////////
700 // functionality for device
701 
702 int DeviceTy::associatePtr(void *HstPtrBegin, void *TgtPtrBegin, int64_t Size) {
703   DataMapMtx.lock();
704 
705   // Check if entry exists
706   for (auto &HT : HostDataToTargetMap) {
707     if ((uintptr_t)HstPtrBegin == HT.HstPtrBegin) {
708       // Mapping already exists
709       bool isValid = HT.HstPtrBegin == (uintptr_t) HstPtrBegin &&
710                      HT.HstPtrEnd == (uintptr_t) HstPtrBegin + Size &&
711                      HT.TgtPtrBegin == (uintptr_t) TgtPtrBegin;
712       DataMapMtx.unlock();
713       if (isValid) {
714         DP("Attempt to re-associate the same device ptr+offset with the same "
715             "host ptr, nothing to do\n");
716         return OFFLOAD_SUCCESS;
717       } else {
718         DP("Not allowed to re-associate a different device ptr+offset with the "
719             "same host ptr\n");
720         return OFFLOAD_FAIL;
721       }
722     }
723   }
724 
725   // Mapping does not exist, allocate it
726   HostDataToTargetTy newEntry;
727 
728   // Set up missing fields
729   newEntry.HstPtrBase = (uintptr_t) HstPtrBegin;
730   newEntry.HstPtrBegin = (uintptr_t) HstPtrBegin;
731   newEntry.HstPtrEnd = (uintptr_t) HstPtrBegin + Size;
732   newEntry.TgtPtrBegin = (uintptr_t) TgtPtrBegin;
733   // refCount must be infinite
734   newEntry.RefCount = INF_REF_CNT;
735 
736   DP("Creating new map entry: HstBase=" DPxMOD ", HstBegin=" DPxMOD ", HstEnd="
737       DPxMOD ", TgtBegin=" DPxMOD "\n", DPxPTR(newEntry.HstPtrBase),
738       DPxPTR(newEntry.HstPtrBegin), DPxPTR(newEntry.HstPtrEnd),
739       DPxPTR(newEntry.TgtPtrBegin));
740   HostDataToTargetMap.push_front(newEntry);
741 
742   DataMapMtx.unlock();
743 
744   return OFFLOAD_SUCCESS;
745 }
746 
747 int DeviceTy::disassociatePtr(void *HstPtrBegin) {
748   DataMapMtx.lock();
749 
750   // Check if entry exists
751   for (HostDataToTargetListTy::iterator ii = HostDataToTargetMap.begin();
752       ii != HostDataToTargetMap.end(); ++ii) {
753     if ((uintptr_t)HstPtrBegin == ii->HstPtrBegin) {
754       // Mapping exists
755       if (CONSIDERED_INF(ii->RefCount)) {
756         DP("Association found, removing it\n");
757         HostDataToTargetMap.erase(ii);
758         DataMapMtx.unlock();
759         return OFFLOAD_SUCCESS;
760       } else {
761         DP("Trying to disassociate a pointer which was not mapped via "
762             "omp_target_associate_ptr\n");
763         break;
764       }
765     }
766   }
767 
768   // Mapping not found
769   DataMapMtx.unlock();
770   DP("Association not found\n");
771   return OFFLOAD_FAIL;
772 }
773 
774 // Get ref count of map entry containing HstPtrBegin
775 long DeviceTy::getMapEntryRefCnt(void *HstPtrBegin) {
776   uintptr_t hp = (uintptr_t)HstPtrBegin;
777   long RefCnt = -1;
778 
779   DataMapMtx.lock();
780   for (auto &HT : HostDataToTargetMap) {
781     if (hp >= HT.HstPtrBegin && hp < HT.HstPtrEnd) {
782       DP("DeviceTy::getMapEntry: requested entry found\n");
783       RefCnt = HT.RefCount;
784       break;
785     }
786   }
787   DataMapMtx.unlock();
788 
789   if (RefCnt < 0) {
790     DP("DeviceTy::getMapEntry: requested entry not found\n");
791   }
792 
793   return RefCnt;
794 }
795 
796 LookupResult DeviceTy::lookupMapping(void *HstPtrBegin, int64_t Size) {
797   uintptr_t hp = (uintptr_t)HstPtrBegin;
798   LookupResult lr;
799 
800   DP("Looking up mapping(HstPtrBegin=" DPxMOD ", Size=%ld)...\n", DPxPTR(hp),
801       Size);
802   for (lr.Entry = HostDataToTargetMap.begin();
803       lr.Entry != HostDataToTargetMap.end(); ++lr.Entry) {
804     auto &HT = *lr.Entry;
805     // Is it contained?
806     lr.Flags.IsContained = hp >= HT.HstPtrBegin && hp < HT.HstPtrEnd &&
807         (hp+Size) <= HT.HstPtrEnd;
808     // Does it extend into an already mapped region?
809     lr.Flags.ExtendsBefore = hp < HT.HstPtrBegin && (hp+Size) > HT.HstPtrBegin;
810     // Does it extend beyond the mapped region?
811     lr.Flags.ExtendsAfter = hp < HT.HstPtrEnd && (hp+Size) > HT.HstPtrEnd;
812 
813     if (lr.Flags.IsContained || lr.Flags.ExtendsBefore ||
814         lr.Flags.ExtendsAfter) {
815       break;
816     }
817   }
818 
819   if (lr.Flags.ExtendsBefore) {
820     DP("WARNING: Pointer is not mapped but section extends into already "
821         "mapped data\n");
822   }
823   if (lr.Flags.ExtendsAfter) {
824     DP("WARNING: Pointer is already mapped but section extends beyond mapped "
825         "region\n");
826   }
827 
828   return lr;
829 }
830 
831 // Used by target_data_begin
832 // Return the target pointer begin (where the data will be moved).
833 // Allocate memory if this is the first occurrence if this mapping.
834 // Increment the reference counter.
835 // If NULL is returned, then either data allocation failed or the user tried
836 // to do an illegal mapping.
837 void *DeviceTy::getOrAllocTgtPtr(void *HstPtrBegin, void *HstPtrBase,
838     int64_t Size, bool &IsNew, bool IsImplicit, bool UpdateRefCount) {
839   void *rc = NULL;
840   DataMapMtx.lock();
841   LookupResult lr = lookupMapping(HstPtrBegin, Size);
842 
843   // Check if the pointer is contained.
844   if (lr.Flags.IsContained ||
845       ((lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) && IsImplicit)) {
846     auto &HT = *lr.Entry;
847     IsNew = false;
848 
849     if (UpdateRefCount)
850       ++HT.RefCount;
851 
852     uintptr_t tp = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
853     DP("Mapping exists%s with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", "
854         "Size=%ld,%s RefCount=%s\n", (IsImplicit ? " (implicit)" : ""),
855         DPxPTR(HstPtrBegin), DPxPTR(tp), Size,
856         (UpdateRefCount ? " updated" : ""),
857         (CONSIDERED_INF(HT.RefCount)) ? "INF" :
858             std::to_string(HT.RefCount).c_str());
859     rc = (void *)tp;
860   } else if ((lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) && !IsImplicit) {
861     // Explicit extension of mapped data - not allowed.
862     DP("Explicit extension of mapping is not allowed.\n");
863   } else if (Size) {
864     // If it is not contained and Size > 0 we should create a new entry for it.
865     IsNew = true;
866     uintptr_t tp = (uintptr_t)RTL->data_alloc(RTLDeviceID, Size, HstPtrBegin);
867     DP("Creating new map entry: HstBase=" DPxMOD ", HstBegin=" DPxMOD ", "
868         "HstEnd=" DPxMOD ", TgtBegin=" DPxMOD "\n", DPxPTR(HstPtrBase),
869         DPxPTR(HstPtrBegin), DPxPTR((uintptr_t)HstPtrBegin + Size), DPxPTR(tp));
870     HostDataToTargetMap.push_front(HostDataToTargetTy((uintptr_t)HstPtrBase,
871         (uintptr_t)HstPtrBegin, (uintptr_t)HstPtrBegin + Size, tp));
872     rc = (void *)tp;
873   }
874 
875   DataMapMtx.unlock();
876   return rc;
877 }
878 
879 // Used by target_data_begin, target_data_end, target_data_update and target.
880 // Return the target pointer begin (where the data will be moved).
881 // Decrement the reference counter if called from target_data_end.
882 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size, bool &IsLast,
883     bool UpdateRefCount) {
884   void *rc = NULL;
885   DataMapMtx.lock();
886   LookupResult lr = lookupMapping(HstPtrBegin, Size);
887 
888   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
889     auto &HT = *lr.Entry;
890     IsLast = !(HT.RefCount > 1);
891 
892     if (HT.RefCount > 1 && UpdateRefCount)
893       --HT.RefCount;
894 
895     uintptr_t tp = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
896     DP("Mapping exists with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", "
897         "Size=%ld,%s RefCount=%s\n", DPxPTR(HstPtrBegin), DPxPTR(tp), Size,
898         (UpdateRefCount ? " updated" : ""),
899         (CONSIDERED_INF(HT.RefCount)) ? "INF" :
900             std::to_string(HT.RefCount).c_str());
901     rc = (void *)tp;
902   } else {
903     IsLast = false;
904   }
905 
906   DataMapMtx.unlock();
907   return rc;
908 }
909 
910 // Return the target pointer begin (where the data will be moved).
911 // Lock-free version called when loading global symbols from the fat binary.
912 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size) {
913   uintptr_t hp = (uintptr_t)HstPtrBegin;
914   LookupResult lr = lookupMapping(HstPtrBegin, Size);
915   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
916     auto &HT = *lr.Entry;
917     uintptr_t tp = HT.TgtPtrBegin + (hp - HT.HstPtrBegin);
918     return (void *)tp;
919   }
920 
921   return NULL;
922 }
923 
924 int DeviceTy::deallocTgtPtr(void *HstPtrBegin, int64_t Size, bool ForceDelete) {
925   // Check if the pointer is contained in any sub-nodes.
926   int rc;
927   DataMapMtx.lock();
928   LookupResult lr = lookupMapping(HstPtrBegin, Size);
929   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
930     auto &HT = *lr.Entry;
931     if (ForceDelete)
932       HT.RefCount = 1;
933     if (--HT.RefCount <= 0) {
934       assert(HT.RefCount == 0 && "did not expect a negative ref count");
935       DP("Deleting tgt data " DPxMOD " of size %ld\n",
936           DPxPTR(HT.TgtPtrBegin), Size);
937       RTL->data_delete(RTLDeviceID, (void *)HT.TgtPtrBegin);
938       DP("Removing%s mapping with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD
939           ", Size=%ld\n", (ForceDelete ? " (forced)" : ""),
940           DPxPTR(HT.HstPtrBegin), DPxPTR(HT.TgtPtrBegin), Size);
941       HostDataToTargetMap.erase(lr.Entry);
942     }
943     rc = OFFLOAD_SUCCESS;
944   } else {
945     DP("Section to delete (hst addr " DPxMOD ") does not exist in the allocated"
946        " memory\n", DPxPTR(HstPtrBegin));
947     rc = OFFLOAD_FAIL;
948   }
949 
950   DataMapMtx.unlock();
951   return rc;
952 }
953 
954 /// Init device, should not be called directly.
955 void DeviceTy::init() {
956   int32_t rc = RTL->init_device(RTLDeviceID);
957   if (rc == OFFLOAD_SUCCESS) {
958     IsInit = true;
959   }
960 }
961 
962 /// Thread-safe method to initialize the device only once.
963 int32_t DeviceTy::initOnce() {
964   std::call_once(InitFlag, &DeviceTy::init, this);
965 
966   // At this point, if IsInit is true, then either this thread or some other
967   // thread in the past successfully initialized the device, so we can return
968   // OFFLOAD_SUCCESS. If this thread executed init() via call_once() and it
969   // failed, return OFFLOAD_FAIL. If call_once did not invoke init(), it means
970   // that some other thread already attempted to execute init() and if IsInit
971   // is still false, return OFFLOAD_FAIL.
972   if (IsInit)
973     return OFFLOAD_SUCCESS;
974   else
975     return OFFLOAD_FAIL;
976 }
977 
978 // Load binary to device.
979 __tgt_target_table *DeviceTy::load_binary(void *Img) {
980   RTL->Mtx.lock();
981   __tgt_target_table *rc = RTL->load_binary(RTLDeviceID, Img);
982   RTL->Mtx.unlock();
983   return rc;
984 }
985 
986 // Submit data to device.
987 int32_t DeviceTy::data_submit(void *TgtPtrBegin, void *HstPtrBegin,
988     int64_t Size) {
989   return RTL->data_submit(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size);
990 }
991 
992 // Retrieve data from device.
993 int32_t DeviceTy::data_retrieve(void *HstPtrBegin, void *TgtPtrBegin,
994     int64_t Size) {
995   return RTL->data_retrieve(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size);
996 }
997 
998 // Run region on device
999 int32_t DeviceTy::run_region(void *TgtEntryPtr, void **TgtVarsPtr,
1000     ptrdiff_t *TgtOffsets, int32_t TgtVarsSize) {
1001   return RTL->run_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr, TgtOffsets,
1002       TgtVarsSize);
1003 }
1004 
1005 // Run team region on device.
1006 int32_t DeviceTy::run_team_region(void *TgtEntryPtr, void **TgtVarsPtr,
1007     ptrdiff_t *TgtOffsets, int32_t TgtVarsSize, int32_t NumTeams,
1008     int32_t ThreadLimit, uint64_t LoopTripCount) {
1009   return RTL->run_team_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr, TgtOffsets,
1010       TgtVarsSize, NumTeams, ThreadLimit, LoopTripCount);
1011 }
1012 
1013 ////////////////////////////////////////////////////////////////////////////////
1014 // Functionality for registering libs
1015 
1016 static void RegisterImageIntoTranslationTable(TranslationTable &TT,
1017     RTLInfoTy &RTL, __tgt_device_image *image) {
1018 
1019   // same size, as when we increase one, we also increase the other.
1020   assert(TT.TargetsTable.size() == TT.TargetsImages.size() &&
1021          "We should have as many images as we have tables!");
1022 
1023   // Resize the Targets Table and Images to accommodate the new targets if
1024   // required
1025   unsigned TargetsTableMinimumSize = RTL.Idx + RTL.NumberOfDevices;
1026 
1027   if (TT.TargetsTable.size() < TargetsTableMinimumSize) {
1028     TT.TargetsImages.resize(TargetsTableMinimumSize, 0);
1029     TT.TargetsTable.resize(TargetsTableMinimumSize, 0);
1030   }
1031 
1032   // Register the image in all devices for this target type.
1033   for (int32_t i = 0; i < RTL.NumberOfDevices; ++i) {
1034     // If we are changing the image we are also invalidating the target table.
1035     if (TT.TargetsImages[RTL.Idx + i] != image) {
1036       TT.TargetsImages[RTL.Idx + i] = image;
1037       TT.TargetsTable[RTL.Idx + i] = 0; // lazy initialization of target table.
1038     }
1039   }
1040 }
1041 
1042 ////////////////////////////////////////////////////////////////////////////////
1043 // Functionality for registering Ctors/Dtors
1044 
1045 static void RegisterGlobalCtorsDtorsForImage(__tgt_bin_desc *desc,
1046     __tgt_device_image *img, RTLInfoTy *RTL) {
1047 
1048   for (int32_t i = 0; i < RTL->NumberOfDevices; ++i) {
1049     DeviceTy &Device = Devices[RTL->Idx + i];
1050     Device.PendingGlobalsMtx.lock();
1051     Device.HasPendingGlobals = true;
1052     for (__tgt_offload_entry *entry = img->EntriesBegin;
1053         entry != img->EntriesEnd; ++entry) {
1054       if (entry->flags & OMP_DECLARE_TARGET_CTOR) {
1055         DP("Adding ctor " DPxMOD " to the pending list.\n",
1056             DPxPTR(entry->addr));
1057         Device.PendingCtorsDtors[desc].PendingCtors.push_back(entry->addr);
1058       } else if (entry->flags & OMP_DECLARE_TARGET_DTOR) {
1059         // Dtors are pushed in reverse order so they are executed from end
1060         // to beginning when unregistering the library!
1061         DP("Adding dtor " DPxMOD " to the pending list.\n",
1062             DPxPTR(entry->addr));
1063         Device.PendingCtorsDtors[desc].PendingDtors.push_front(entry->addr);
1064       }
1065 
1066       if (entry->flags & OMP_DECLARE_TARGET_LINK) {
1067         DP("The \"link\" attribute is not yet supported!\n");
1068       }
1069     }
1070     Device.PendingGlobalsMtx.unlock();
1071   }
1072 }
1073 
1074 ////////////////////////////////////////////////////////////////////////////////
1075 /// adds a target shared library to the target execution image
1076 EXTERN void __tgt_register_lib(__tgt_bin_desc *desc) {
1077 
1078   // Attempt to load all plugins available in the system.
1079   RTLs.LoadRTLsOnce();
1080 
1081   RTLsMtx.lock();
1082   // Register the images with the RTLs that understand them, if any.
1083   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
1084     // Obtain the image.
1085     __tgt_device_image *img = &desc->DeviceImages[i];
1086 
1087     RTLInfoTy *FoundRTL = NULL;
1088 
1089     // Scan the RTLs that have associated images until we find one that supports
1090     // the current image.
1091     for (auto &R : RTLs.AllRTLs) {
1092       if (!R.is_valid_binary(img)) {
1093         DP("Image " DPxMOD " is NOT compatible with RTL %s!\n",
1094             DPxPTR(img->ImageStart), R.RTLName.c_str());
1095         continue;
1096       }
1097 
1098       DP("Image " DPxMOD " is compatible with RTL %s!\n",
1099           DPxPTR(img->ImageStart), R.RTLName.c_str());
1100 
1101       // If this RTL is not already in use, initialize it.
1102       if (!R.isUsed) {
1103         // Initialize the device information for the RTL we are about to use.
1104         DeviceTy device(&R);
1105 
1106         size_t start = Devices.size();
1107         Devices.resize(start + R.NumberOfDevices, device);
1108         for (int32_t device_id = 0; device_id < R.NumberOfDevices;
1109             device_id++) {
1110           // global device ID
1111           Devices[start + device_id].DeviceID = start + device_id;
1112           // RTL local device ID
1113           Devices[start + device_id].RTLDeviceID = device_id;
1114 
1115           // Save pointer to device in RTL in case we want to unregister the RTL
1116           R.Devices.push_back(&Devices[start + device_id]);
1117         }
1118 
1119         // Initialize the index of this RTL and save it in the used RTLs.
1120         R.Idx = (RTLs.UsedRTLs.empty())
1121                     ? 0
1122                     : RTLs.UsedRTLs.back()->Idx +
1123                           RTLs.UsedRTLs.back()->NumberOfDevices;
1124         assert((size_t) R.Idx == start &&
1125             "RTL index should equal the number of devices used so far.");
1126         R.isUsed = true;
1127         RTLs.UsedRTLs.push_back(&R);
1128 
1129         DP("RTL " DPxMOD " has index %d!\n", DPxPTR(R.LibraryHandler), R.Idx);
1130       }
1131 
1132       // Initialize (if necessary) translation table for this library.
1133       TrlTblMtx.lock();
1134       if(!HostEntriesBeginToTransTable.count(desc->HostEntriesBegin)){
1135         TranslationTable &tt =
1136             HostEntriesBeginToTransTable[desc->HostEntriesBegin];
1137         tt.HostTable.EntriesBegin = desc->HostEntriesBegin;
1138         tt.HostTable.EntriesEnd = desc->HostEntriesEnd;
1139       }
1140 
1141       // Retrieve translation table for this library.
1142       TranslationTable &TransTable =
1143           HostEntriesBeginToTransTable[desc->HostEntriesBegin];
1144 
1145       DP("Registering image " DPxMOD " with RTL %s!\n",
1146           DPxPTR(img->ImageStart), R.RTLName.c_str());
1147       RegisterImageIntoTranslationTable(TransTable, R, img);
1148       TrlTblMtx.unlock();
1149       FoundRTL = &R;
1150 
1151       // Load ctors/dtors for static objects
1152       RegisterGlobalCtorsDtorsForImage(desc, img, FoundRTL);
1153 
1154       // if an RTL was found we are done - proceed to register the next image
1155       break;
1156     }
1157 
1158     if (!FoundRTL) {
1159       DP("No RTL found for image " DPxMOD "!\n", DPxPTR(img->ImageStart));
1160     }
1161   }
1162   RTLsMtx.unlock();
1163 
1164 
1165   DP("Done registering entries!\n");
1166 }
1167 
1168 ////////////////////////////////////////////////////////////////////////////////
1169 /// unloads a target shared library
1170 EXTERN void __tgt_unregister_lib(__tgt_bin_desc *desc) {
1171   DP("Unloading target library!\n");
1172 
1173   RTLsMtx.lock();
1174   // Find which RTL understands each image, if any.
1175   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
1176     // Obtain the image.
1177     __tgt_device_image *img = &desc->DeviceImages[i];
1178 
1179     RTLInfoTy *FoundRTL = NULL;
1180 
1181     // Scan the RTLs that have associated images until we find one that supports
1182     // the current image. We only need to scan RTLs that are already being used.
1183     for (auto *R : RTLs.UsedRTLs) {
1184 
1185       assert(R->isUsed && "Expecting used RTLs.");
1186 
1187       if (!R->is_valid_binary(img)) {
1188         DP("Image " DPxMOD " is NOT compatible with RTL " DPxMOD "!\n",
1189             DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
1190         continue;
1191       }
1192 
1193       DP("Image " DPxMOD " is compatible with RTL " DPxMOD "!\n",
1194           DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
1195 
1196       FoundRTL = R;
1197 
1198       // Execute dtors for static objects if the device has been used, i.e.
1199       // if its PendingCtors list has been emptied.
1200       for (int32_t i = 0; i < FoundRTL->NumberOfDevices; ++i) {
1201         DeviceTy &Device = Devices[FoundRTL->Idx + i];
1202         Device.PendingGlobalsMtx.lock();
1203         if (Device.PendingCtorsDtors[desc].PendingCtors.empty()) {
1204           for (auto &dtor : Device.PendingCtorsDtors[desc].PendingDtors) {
1205             int rc = target(Device.DeviceID, dtor, 0, NULL, NULL, NULL, NULL, 1,
1206                 1, true /*team*/);
1207             if (rc != OFFLOAD_SUCCESS) {
1208               DP("Running destructor " DPxMOD " failed.\n", DPxPTR(dtor));
1209             }
1210           }
1211           // Remove this library's entry from PendingCtorsDtors
1212           Device.PendingCtorsDtors.erase(desc);
1213         }
1214         Device.PendingGlobalsMtx.unlock();
1215       }
1216 
1217       DP("Unregistered image " DPxMOD " from RTL " DPxMOD "!\n",
1218           DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
1219 
1220       break;
1221     }
1222 
1223     // if no RTL was found proceed to unregister the next image
1224     if (!FoundRTL){
1225       DP("No RTLs in use support the image " DPxMOD "!\n",
1226           DPxPTR(img->ImageStart));
1227     }
1228   }
1229   RTLsMtx.unlock();
1230   DP("Done unregistering images!\n");
1231 
1232   // Remove entries from HostPtrToTableMap
1233   TblMapMtx.lock();
1234   for (__tgt_offload_entry *cur = desc->HostEntriesBegin;
1235       cur < desc->HostEntriesEnd; ++cur) {
1236     HostPtrToTableMap.erase(cur->addr);
1237   }
1238 
1239   // Remove translation table for this descriptor.
1240   auto tt = HostEntriesBeginToTransTable.find(desc->HostEntriesBegin);
1241   if (tt != HostEntriesBeginToTransTable.end()) {
1242     DP("Removing translation table for descriptor " DPxMOD "\n",
1243         DPxPTR(desc->HostEntriesBegin));
1244     HostEntriesBeginToTransTable.erase(tt);
1245   } else {
1246     DP("Translation table for descriptor " DPxMOD " cannot be found, probably "
1247         "it has been already removed.\n", DPxPTR(desc->HostEntriesBegin));
1248   }
1249 
1250   TblMapMtx.unlock();
1251 
1252   // TODO: Remove RTL and the devices it manages if it's not used anymore?
1253   // TODO: Write some RTL->unload_image(...) function?
1254 
1255   DP("Done unregistering library!\n");
1256 }
1257 
1258 /// Map global data and execute pending ctors
1259 static int InitLibrary(DeviceTy& Device) {
1260   /*
1261    * Map global data
1262    */
1263   int32_t device_id = Device.DeviceID;
1264   int rc = OFFLOAD_SUCCESS;
1265 
1266   Device.PendingGlobalsMtx.lock();
1267   TrlTblMtx.lock();
1268   for (HostEntriesBeginToTransTableTy::iterator
1269       ii = HostEntriesBeginToTransTable.begin();
1270       ii != HostEntriesBeginToTransTable.end(); ++ii) {
1271     TranslationTable *TransTable = &ii->second;
1272     if (TransTable->TargetsTable[device_id] != 0) {
1273       // Library entries have already been processed
1274       continue;
1275     }
1276 
1277     // 1) get image.
1278     assert(TransTable->TargetsImages.size() > (size_t)device_id &&
1279            "Not expecting a device ID outside the table's bounds!");
1280     __tgt_device_image *img = TransTable->TargetsImages[device_id];
1281     if (!img) {
1282       DP("No image loaded for device id %d.\n", device_id);
1283       rc = OFFLOAD_FAIL;
1284       break;
1285     }
1286     // 2) load image into the target table.
1287     __tgt_target_table *TargetTable =
1288         TransTable->TargetsTable[device_id] = Device.load_binary(img);
1289     // Unable to get table for this image: invalidate image and fail.
1290     if (!TargetTable) {
1291       DP("Unable to generate entries table for device id %d.\n", device_id);
1292       TransTable->TargetsImages[device_id] = 0;
1293       rc = OFFLOAD_FAIL;
1294       break;
1295     }
1296 
1297     // Verify whether the two table sizes match.
1298     size_t hsize =
1299         TransTable->HostTable.EntriesEnd - TransTable->HostTable.EntriesBegin;
1300     size_t tsize = TargetTable->EntriesEnd - TargetTable->EntriesBegin;
1301 
1302     // Invalid image for these host entries!
1303     if (hsize != tsize) {
1304       DP("Host and Target tables mismatch for device id %d [%zx != %zx].\n",
1305          device_id, hsize, tsize);
1306       TransTable->TargetsImages[device_id] = 0;
1307       TransTable->TargetsTable[device_id] = 0;
1308       rc = OFFLOAD_FAIL;
1309       break;
1310     }
1311 
1312     // process global data that needs to be mapped.
1313     Device.DataMapMtx.lock();
1314     __tgt_target_table *HostTable = &TransTable->HostTable;
1315     for (__tgt_offload_entry *CurrDeviceEntry = TargetTable->EntriesBegin,
1316                              *CurrHostEntry = HostTable->EntriesBegin,
1317                              *EntryDeviceEnd = TargetTable->EntriesEnd;
1318          CurrDeviceEntry != EntryDeviceEnd;
1319          CurrDeviceEntry++, CurrHostEntry++) {
1320       if (CurrDeviceEntry->size != 0) {
1321         // has data.
1322         assert(CurrDeviceEntry->size == CurrHostEntry->size &&
1323                "data size mismatch");
1324 
1325         // Fortran may use multiple weak declarations for the same symbol,
1326         // therefore we must allow for multiple weak symbols to be loaded from
1327         // the fat binary. Treat these mappings as any other "regular" mapping.
1328         // Add entry to map.
1329         if (Device.getTgtPtrBegin(CurrHostEntry->addr, CurrHostEntry->size))
1330           continue;
1331         DP("Add mapping from host " DPxMOD " to device " DPxMOD " with size %zu"
1332             "\n", DPxPTR(CurrHostEntry->addr), DPxPTR(CurrDeviceEntry->addr),
1333             CurrDeviceEntry->size);
1334         Device.HostDataToTargetMap.push_front(HostDataToTargetTy(
1335             (uintptr_t)CurrHostEntry->addr /*HstPtrBase*/,
1336             (uintptr_t)CurrHostEntry->addr /*HstPtrBegin*/,
1337             (uintptr_t)CurrHostEntry->addr + CurrHostEntry->size /*HstPtrEnd*/,
1338             (uintptr_t)CurrDeviceEntry->addr /*TgtPtrBegin*/,
1339             INF_REF_CNT /*RefCount*/));
1340       }
1341     }
1342     Device.DataMapMtx.unlock();
1343   }
1344   TrlTblMtx.unlock();
1345 
1346   if (rc != OFFLOAD_SUCCESS) {
1347     Device.PendingGlobalsMtx.unlock();
1348     return rc;
1349   }
1350 
1351   /*
1352    * Run ctors for static objects
1353    */
1354   if (!Device.PendingCtorsDtors.empty()) {
1355     // Call all ctors for all libraries registered so far
1356     for (auto &lib : Device.PendingCtorsDtors) {
1357       if (!lib.second.PendingCtors.empty()) {
1358         DP("Has pending ctors... call now\n");
1359         for (auto &entry : lib.second.PendingCtors) {
1360           void *ctor = entry;
1361           int rc = target(device_id, ctor, 0, NULL, NULL, NULL,
1362                           NULL, 1, 1, true /*team*/);
1363           if (rc != OFFLOAD_SUCCESS) {
1364             DP("Running ctor " DPxMOD " failed.\n", DPxPTR(ctor));
1365             Device.PendingGlobalsMtx.unlock();
1366             return OFFLOAD_FAIL;
1367           }
1368         }
1369         // Clear the list to indicate that this device has been used
1370         lib.second.PendingCtors.clear();
1371         DP("Done with pending ctors for lib " DPxMOD "\n", DPxPTR(lib.first));
1372       }
1373     }
1374   }
1375   Device.HasPendingGlobals = false;
1376   Device.PendingGlobalsMtx.unlock();
1377 
1378   return OFFLOAD_SUCCESS;
1379 }
1380 
1381 // Check whether a device has been initialized, global ctors have been
1382 // executed and global data has been mapped; do so if not already done.
1383 static int CheckDevice(int32_t device_id) {
1384   // Is device ready?
1385   if (!device_is_ready(device_id)) {
1386     DP("Device %d is not ready.\n", device_id);
1387     return OFFLOAD_FAIL;
1388   }
1389 
1390   // Get device info.
1391   DeviceTy &Device = Devices[device_id];
1392 
1393   // Check whether global data has been mapped for this device
1394   Device.PendingGlobalsMtx.lock();
1395   bool hasPendingGlobals = Device.HasPendingGlobals;
1396   Device.PendingGlobalsMtx.unlock();
1397   if (hasPendingGlobals && InitLibrary(Device) != OFFLOAD_SUCCESS) {
1398     DP("Failed to init globals on device %d\n", device_id);
1399     return OFFLOAD_FAIL;
1400   }
1401 
1402   return OFFLOAD_SUCCESS;
1403 }
1404 
1405 // Following datatypes and functions (tgt_oldmap_type, combined_entry_t,
1406 // translate_map, cleanup_map) will be removed once the compiler starts using
1407 // the new map types.
1408 
1409 // Old map types
1410 enum tgt_oldmap_type {
1411   OMP_TGT_OLDMAPTYPE_TO          = 0x001, // copy data from host to device
1412   OMP_TGT_OLDMAPTYPE_FROM        = 0x002, // copy data from device to host
1413   OMP_TGT_OLDMAPTYPE_ALWAYS      = 0x004, // copy regardless of the ref. count
1414   OMP_TGT_OLDMAPTYPE_DELETE      = 0x008, // force unmapping of data
1415   OMP_TGT_OLDMAPTYPE_MAP_PTR     = 0x010, // map pointer as well as pointee
1416   OMP_TGT_OLDMAPTYPE_FIRST_MAP   = 0x020, // first occurrence of mapped variable
1417   OMP_TGT_OLDMAPTYPE_RETURN_PTR  = 0x040, // return TgtBase addr of mapped data
1418   OMP_TGT_OLDMAPTYPE_PRIVATE_PTR = 0x080, // private variable - not mapped
1419   OMP_TGT_OLDMAPTYPE_PRIVATE_VAL = 0x100  // copy by value - not mapped
1420 };
1421 
1422 // Temporary functions for map translation and cleanup
1423 struct combined_entry_t {
1424   int num_members; // number of members in combined entry
1425   void *base_addr; // base address of combined entry
1426   void *begin_addr; // begin address of combined entry
1427   void *end_addr; // size of combined entry
1428 };
1429 
1430 static void translate_map(int32_t arg_num, void **args_base, void **args,
1431     int64_t *arg_sizes, int32_t *arg_types, int32_t &new_arg_num,
1432     void **&new_args_base, void **&new_args, int64_t *&new_arg_sizes,
1433     int64_t *&new_arg_types, bool is_target_construct) {
1434   if (arg_num <= 0) {
1435     DP("Nothing to translate\n");
1436     new_arg_num = 0;
1437     return;
1438   }
1439 
1440   // array of combined entries
1441   combined_entry_t *cmb_entries =
1442       (combined_entry_t *) alloca(arg_num * sizeof(combined_entry_t));
1443   // number of combined entries
1444   long num_combined = 0;
1445   // old entry is MAP_PTR?
1446   bool *is_ptr_old = (bool *) alloca(arg_num * sizeof(bool));
1447   // old entry is member of member_of[old] cmb_entry
1448   int *member_of = (int *) alloca(arg_num * sizeof(int));
1449   // temporary storage for modifications of the original arg_types
1450   int32_t *mod_arg_types = (int32_t *) alloca(arg_num  *sizeof(int32_t));
1451 
1452   DP("Translating %d map entries\n", arg_num);
1453   for (int i = 0; i < arg_num; ++i) {
1454     member_of[i] = -1;
1455     is_ptr_old[i] = false;
1456     mod_arg_types[i] = arg_types[i];
1457     // Scan previous entries to see whether this entry shares the same base
1458     for (int j = 0; j < i; ++j) {
1459       void *new_begin_addr = NULL;
1460       void *new_end_addr = NULL;
1461 
1462       if (mod_arg_types[i] & OMP_TGT_OLDMAPTYPE_MAP_PTR) {
1463         if (args_base[i] == args[j]) {
1464           if (!(mod_arg_types[j] & OMP_TGT_OLDMAPTYPE_MAP_PTR)) {
1465             DP("Entry %d has the same base as entry %d's begin address\n", i,
1466                 j);
1467             new_begin_addr = args_base[i];
1468             new_end_addr = (char *)args_base[i] + sizeof(void *);
1469             assert(arg_sizes[j] == sizeof(void *));
1470             is_ptr_old[j] = true;
1471           } else {
1472             DP("Entry %d has the same base as entry %d's begin address, but "
1473                 "%d's base was a MAP_PTR too\n", i, j, j);
1474             int32_t to_from_always_delete =
1475                 OMP_TGT_OLDMAPTYPE_TO | OMP_TGT_OLDMAPTYPE_FROM |
1476                 OMP_TGT_OLDMAPTYPE_ALWAYS | OMP_TGT_OLDMAPTYPE_DELETE;
1477             if (mod_arg_types[j] & to_from_always_delete) {
1478               DP("Resetting to/from/always/delete flags for entry %d because "
1479                   "it is only a pointer to pointer\n", j);
1480               mod_arg_types[j] &= ~to_from_always_delete;
1481             }
1482           }
1483         }
1484       } else {
1485         if (!(mod_arg_types[i] & OMP_TGT_OLDMAPTYPE_FIRST_MAP) &&
1486             args_base[i] == args_base[j]) {
1487           DP("Entry %d has the same base address as entry %d\n", i, j);
1488           new_begin_addr = args[i];
1489           new_end_addr = (char *)args[i] + arg_sizes[i];
1490         }
1491       }
1492 
1493       // If we have combined the entry with a previous one
1494       if (new_begin_addr) {
1495         int id;
1496         if(member_of[j] == -1) {
1497           // We have a new entry
1498           id = num_combined++;
1499           DP("Creating new combined entry %d for old entry %d\n", id, j);
1500           // Initialize new entry
1501           cmb_entries[id].num_members = 1;
1502           cmb_entries[id].base_addr = args_base[j];
1503           if (mod_arg_types[j] & OMP_TGT_OLDMAPTYPE_MAP_PTR) {
1504             cmb_entries[id].begin_addr = args_base[j];
1505             cmb_entries[id].end_addr = (char *)args_base[j] + arg_sizes[j];
1506           } else {
1507             cmb_entries[id].begin_addr = args[j];
1508             cmb_entries[id].end_addr = (char *)args[j] + arg_sizes[j];
1509           }
1510           member_of[j] = id;
1511         } else {
1512           // Reuse existing combined entry
1513           DP("Reusing existing combined entry %d\n", member_of[j]);
1514           id = member_of[j];
1515         }
1516 
1517         // Update combined entry
1518         DP("Adding entry %d to combined entry %d\n", i, id);
1519         cmb_entries[id].num_members++;
1520         // base_addr stays the same
1521         cmb_entries[id].begin_addr =
1522             std::min(cmb_entries[id].begin_addr, new_begin_addr);
1523         cmb_entries[id].end_addr =
1524             std::max(cmb_entries[id].end_addr, new_end_addr);
1525         member_of[i] = id;
1526         break;
1527       }
1528     }
1529   }
1530 
1531   DP("New entries: %ld combined + %d original\n", num_combined, arg_num);
1532   new_arg_num = arg_num + num_combined;
1533   new_args_base = (void **) malloc(new_arg_num * sizeof(void *));
1534   new_args = (void **) malloc(new_arg_num * sizeof(void *));
1535   new_arg_sizes = (int64_t *) malloc(new_arg_num * sizeof(int64_t));
1536   new_arg_types = (int64_t *) malloc(new_arg_num * sizeof(int64_t));
1537 
1538   const int64_t alignment = 8;
1539 
1540   int next_id = 0; // next ID
1541   int next_cid = 0; // next combined ID
1542   int *combined_to_new_id = (int *) alloca(num_combined * sizeof(int));
1543   for (int i = 0; i < arg_num; ++i) {
1544     // It is member_of
1545     if (member_of[i] == next_cid) {
1546       int cid = next_cid++; // ID of this combined entry
1547       int nid = next_id++; // ID of the new (global) entry
1548       combined_to_new_id[cid] = nid;
1549       DP("Combined entry %3d will become new entry %3d\n", cid, nid);
1550 
1551       int64_t padding = (int64_t)cmb_entries[cid].begin_addr % alignment;
1552       if (padding) {
1553         DP("Using a padding of %" PRId64 " for begin address " DPxMOD "\n",
1554             padding, DPxPTR(cmb_entries[cid].begin_addr));
1555         cmb_entries[cid].begin_addr =
1556             (char *)cmb_entries[cid].begin_addr - padding;
1557       }
1558 
1559       new_args_base[nid] = cmb_entries[cid].base_addr;
1560       new_args[nid] = cmb_entries[cid].begin_addr;
1561       new_arg_sizes[nid] = (int64_t) ((char *)cmb_entries[cid].end_addr -
1562           (char *)cmb_entries[cid].begin_addr);
1563       new_arg_types[nid] = OMP_TGT_MAPTYPE_TARGET_PARAM;
1564       DP("Entry %3d: base_addr " DPxMOD ", begin_addr " DPxMOD ", "
1565           "size %" PRId64 ", type 0x%" PRIx64 "\n", nid,
1566           DPxPTR(new_args_base[nid]), DPxPTR(new_args[nid]), new_arg_sizes[nid],
1567           new_arg_types[nid]);
1568     } else if (member_of[i] != -1) {
1569       DP("Combined entry %3d has been encountered before, do nothing\n",
1570           member_of[i]);
1571     }
1572 
1573     // Now that the combined entry (the one the old entry was a member of) has
1574     // been inserted into the new arguments list, proceed with the old entry.
1575     int nid = next_id++;
1576     DP("Old entry %3d will become new entry %3d\n", i, nid);
1577 
1578     new_args_base[nid] = args_base[i];
1579     new_args[nid] = args[i];
1580     new_arg_sizes[nid] = arg_sizes[i];
1581     int64_t old_type = mod_arg_types[i];
1582 
1583     if (is_ptr_old[i]) {
1584       // Reset TO and FROM flags
1585       old_type &= ~(OMP_TGT_OLDMAPTYPE_TO | OMP_TGT_OLDMAPTYPE_FROM);
1586     }
1587 
1588     if (member_of[i] == -1) {
1589       if (!is_target_construct)
1590         old_type &= ~OMP_TGT_MAPTYPE_TARGET_PARAM;
1591       new_arg_types[nid] = old_type;
1592       DP("Entry %3d: base_addr " DPxMOD ", begin_addr " DPxMOD ", size %" PRId64
1593           ", type 0x%" PRIx64 " (old entry %d not MEMBER_OF)\n", nid,
1594           DPxPTR(new_args_base[nid]), DPxPTR(new_args[nid]), new_arg_sizes[nid],
1595           new_arg_types[nid], i);
1596     } else {
1597       // Old entry is not FIRST_MAP
1598       old_type &= ~OMP_TGT_OLDMAPTYPE_FIRST_MAP;
1599       // Add MEMBER_OF
1600       int new_member_of = combined_to_new_id[member_of[i]];
1601       old_type |= ((int64_t)new_member_of + 1) << 48;
1602       new_arg_types[nid] = old_type;
1603       DP("Entry %3d: base_addr " DPxMOD ", begin_addr " DPxMOD ", size %" PRId64
1604         ", type 0x%" PRIx64 " (old entry %d MEMBER_OF %d)\n", nid,
1605         DPxPTR(new_args_base[nid]), DPxPTR(new_args[nid]), new_arg_sizes[nid],
1606         new_arg_types[nid], i, new_member_of);
1607     }
1608   }
1609 }
1610 
1611 static void cleanup_map(int32_t new_arg_num, void **new_args_base,
1612     void **new_args, int64_t *new_arg_sizes, int64_t *new_arg_types,
1613     int32_t arg_num, void **args_base) {
1614   if (new_arg_num > 0) {
1615     int offset = new_arg_num - arg_num;
1616     for (int32_t i = 0; i < arg_num; ++i) {
1617       // Restore old base address
1618       args_base[i] = new_args_base[i+offset];
1619     }
1620     free(new_args_base);
1621     free(new_args);
1622     free(new_arg_sizes);
1623     free(new_arg_types);
1624   }
1625 }
1626 
1627 static short member_of(int64_t type) {
1628   return ((type & OMP_TGT_MAPTYPE_MEMBER_OF) >> 48) - 1;
1629 }
1630 
1631 /// Internal function to do the mapping and transfer the data to the device
1632 static int target_data_begin(DeviceTy &Device, int32_t arg_num,
1633     void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types) {
1634   // process each input.
1635   int rc = OFFLOAD_SUCCESS;
1636   for (int32_t i = 0; i < arg_num; ++i) {
1637     // Ignore private variables and arrays - there is no mapping for them.
1638     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
1639         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
1640       continue;
1641 
1642     void *HstPtrBegin = args[i];
1643     void *HstPtrBase = args_base[i];
1644     // Address of pointer on the host and device, respectively.
1645     void *Pointer_HstPtrBegin, *Pointer_TgtPtrBegin;
1646     bool IsNew, Pointer_IsNew;
1647     bool IsImplicit = arg_types[i] & OMP_TGT_MAPTYPE_IMPLICIT;
1648     bool UpdateRef = !(arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF);
1649     if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ) {
1650       DP("Has a pointer entry: \n");
1651       // base is address of pointer.
1652       Pointer_TgtPtrBegin = Device.getOrAllocTgtPtr(HstPtrBase, HstPtrBase,
1653           sizeof(void *), Pointer_IsNew, IsImplicit, UpdateRef);
1654       if (!Pointer_TgtPtrBegin) {
1655         DP("Call to getOrAllocTgtPtr returned null pointer (device failure or "
1656             "illegal mapping).\n");
1657       }
1658       DP("There are %zu bytes allocated at target address " DPxMOD " - is%s new"
1659           "\n", sizeof(void *), DPxPTR(Pointer_TgtPtrBegin),
1660           (Pointer_IsNew ? "" : " not"));
1661       Pointer_HstPtrBegin = HstPtrBase;
1662       // modify current entry.
1663       HstPtrBase = *(void **)HstPtrBase;
1664       UpdateRef = true; // subsequently update ref count of pointee
1665     }
1666 
1667     void *TgtPtrBegin = Device.getOrAllocTgtPtr(HstPtrBegin, HstPtrBase,
1668         arg_sizes[i], IsNew, IsImplicit, UpdateRef);
1669     if (!TgtPtrBegin && arg_sizes[i]) {
1670       // If arg_sizes[i]==0, then the argument is a pointer to NULL, so
1671       // getOrAlloc() returning NULL is not an error.
1672       DP("Call to getOrAllocTgtPtr returned null pointer (device failure or "
1673           "illegal mapping).\n");
1674     }
1675     DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
1676         " - is%s new\n", arg_sizes[i], DPxPTR(TgtPtrBegin),
1677         (IsNew ? "" : " not"));
1678 
1679     if (arg_types[i] & OMP_TGT_MAPTYPE_RETURN_PARAM) {
1680       void *ret_ptr;
1681       if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)
1682         ret_ptr = Pointer_TgtPtrBegin;
1683       else {
1684         bool IsLast; // not used
1685         ret_ptr = Device.getTgtPtrBegin(HstPtrBegin, 0, IsLast, false);
1686       }
1687 
1688       DP("Returning device pointer " DPxMOD "\n", DPxPTR(ret_ptr));
1689       args_base[i] = ret_ptr;
1690     }
1691 
1692     if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
1693       bool copy = false;
1694       if (IsNew || (arg_types[i] & OMP_TGT_MAPTYPE_ALWAYS)) {
1695         copy = true;
1696       } else if (arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) {
1697         // Copy data only if the "parent" struct has RefCount==1.
1698         short parent_idx = member_of(arg_types[i]);
1699         long parent_rc = Device.getMapEntryRefCnt(args[parent_idx]);
1700         assert(parent_rc > 0 && "parent struct not found");
1701         if (parent_rc == 1) {
1702           copy = true;
1703         }
1704       }
1705 
1706       if (copy) {
1707         DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
1708             arg_sizes[i], DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
1709         int rt = Device.data_submit(TgtPtrBegin, HstPtrBegin, arg_sizes[i]);
1710         if (rt != OFFLOAD_SUCCESS) {
1711           DP("Copying data to device failed.\n");
1712           rc = OFFLOAD_FAIL;
1713         }
1714       }
1715     }
1716 
1717     if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ) {
1718       DP("Update pointer (" DPxMOD ") -> [" DPxMOD "]\n",
1719           DPxPTR(Pointer_TgtPtrBegin), DPxPTR(TgtPtrBegin));
1720       uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
1721       void *TgtPtrBase = (void *)((uint64_t)TgtPtrBegin - Delta);
1722       int rt = Device.data_submit(Pointer_TgtPtrBegin, &TgtPtrBase,
1723           sizeof(void *));
1724       if (rt != OFFLOAD_SUCCESS) {
1725         DP("Copying data to device failed.\n");
1726         rc = OFFLOAD_FAIL;
1727       }
1728       // create shadow pointers for this entry
1729       Device.ShadowMtx.lock();
1730       Device.ShadowPtrMap[Pointer_HstPtrBegin] = {HstPtrBase,
1731           Pointer_TgtPtrBegin, TgtPtrBase};
1732       Device.ShadowMtx.unlock();
1733     }
1734   }
1735 
1736   return rc;
1737 }
1738 
1739 EXTERN void __tgt_target_data_begin_nowait(int32_t device_id, int32_t arg_num,
1740     void **args_base, void **args, int64_t *arg_sizes, int32_t *arg_types,
1741     int32_t depNum, void *depList, int32_t noAliasDepNum,
1742     void *noAliasDepList) {
1743   if (depNum + noAliasDepNum > 0)
1744     __kmpc_omp_taskwait(NULL, 0);
1745 
1746   __tgt_target_data_begin(device_id, arg_num, args_base, args, arg_sizes,
1747                           arg_types);
1748 }
1749 
1750 /// creates host-to-target data mapping, stores it in the
1751 /// libomptarget.so internal structure (an entry in a stack of data maps)
1752 /// and passes the data to the device.
1753 EXTERN void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1754     void **args_base, void **args, int64_t *arg_sizes, int32_t *arg_types) {
1755   DP("Entering data begin region for device %d with %d mappings\n", device_id,
1756      arg_num);
1757 
1758   // No devices available?
1759   if (device_id == OFFLOAD_DEVICE_DEFAULT) {
1760     device_id = omp_get_default_device();
1761     DP("Use default device id %d\n", device_id);
1762   }
1763 
1764   if (CheckDevice(device_id) != OFFLOAD_SUCCESS) {
1765     DP("Failed to get device %d ready\n", device_id);
1766     return;
1767   }
1768 
1769   DeviceTy& Device = Devices[device_id];
1770 
1771   // Translate maps
1772   int32_t new_arg_num;
1773   void **new_args_base;
1774   void **new_args;
1775   int64_t *new_arg_sizes;
1776   int64_t *new_arg_types;
1777   translate_map(arg_num, args_base, args, arg_sizes, arg_types, new_arg_num,
1778       new_args_base, new_args, new_arg_sizes, new_arg_types, false);
1779 
1780   //target_data_begin(Device, arg_num, args_base, args, arg_sizes, arg_types);
1781   target_data_begin(Device, new_arg_num, new_args_base, new_args, new_arg_sizes,
1782       new_arg_types);
1783 
1784   // Cleanup translation memory
1785   cleanup_map(new_arg_num, new_args_base, new_args, new_arg_sizes,
1786       new_arg_types, arg_num, args_base);
1787 }
1788 
1789 /// Internal function to undo the mapping and retrieve the data from the device.
1790 static int target_data_end(DeviceTy &Device, int32_t arg_num, void **args_base,
1791     void **args, int64_t *arg_sizes, int64_t *arg_types) {
1792   int rc = OFFLOAD_SUCCESS;
1793   // process each input.
1794   for (int32_t i = arg_num - 1; i >= 0; --i) {
1795     // Ignore private variables and arrays - there is no mapping for them.
1796     // Also, ignore the use_device_ptr directive, it has no effect here.
1797     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
1798         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
1799       continue;
1800 
1801     void *HstPtrBegin = args[i];
1802     bool IsLast;
1803     bool UpdateRef = !(arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) ||
1804         (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ);
1805     bool ForceDelete = arg_types[i] & OMP_TGT_MAPTYPE_DELETE;
1806 
1807     // If PTR_AND_OBJ, HstPtrBegin is address of pointee
1808     void *TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, arg_sizes[i], IsLast,
1809         UpdateRef);
1810     DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
1811         " - is%s last\n", arg_sizes[i], DPxPTR(TgtPtrBegin),
1812         (IsLast ? "" : " not"));
1813 
1814     bool DelEntry = IsLast || ForceDelete;
1815 
1816     if ((arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
1817         !(arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
1818       DelEntry = false; // protect parent struct from being deallocated
1819     }
1820 
1821     if ((arg_types[i] & OMP_TGT_MAPTYPE_FROM) || DelEntry) {
1822       // Move data back to the host
1823       if (arg_types[i] & OMP_TGT_MAPTYPE_FROM) {
1824         bool Always = arg_types[i] & OMP_TGT_MAPTYPE_ALWAYS;
1825         bool CopyMember = false;
1826         if ((arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
1827             !(arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
1828           // Copy data only if the "parent" struct has RefCount==1.
1829           short parent_idx = member_of(arg_types[i]);
1830           long parent_rc = Device.getMapEntryRefCnt(args[parent_idx]);
1831           assert(parent_rc > 0 && "parent struct not found");
1832           if (parent_rc == 1) {
1833             CopyMember = true;
1834           }
1835         }
1836 
1837         if (DelEntry || Always || CopyMember) {
1838           DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
1839               arg_sizes[i], DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
1840           int rt = Device.data_retrieve(HstPtrBegin, TgtPtrBegin, arg_sizes[i]);
1841           if (rt != OFFLOAD_SUCCESS) {
1842             DP("Copying data from device failed.\n");
1843             rc = OFFLOAD_FAIL;
1844           }
1845         }
1846       }
1847 
1848       // If we copied back to the host a struct/array containing pointers, we
1849       // need to restore the original host pointer values from their shadow
1850       // copies. If the struct is going to be deallocated, remove any remaining
1851       // shadow pointer entries for this struct.
1852       uintptr_t lb = (uintptr_t) HstPtrBegin;
1853       uintptr_t ub = (uintptr_t) HstPtrBegin + arg_sizes[i];
1854       Device.ShadowMtx.lock();
1855       for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
1856           it != Device.ShadowPtrMap.end(); ++it) {
1857         void **ShadowHstPtrAddr = (void**) it->first;
1858 
1859         // An STL map is sorted on its keys; use this property
1860         // to quickly determine when to break out of the loop.
1861         if ((uintptr_t) ShadowHstPtrAddr < lb)
1862           continue;
1863         if ((uintptr_t) ShadowHstPtrAddr >= ub)
1864           break;
1865 
1866         // If we copied the struct to the host, we need to restore the pointer.
1867         if (arg_types[i] & OMP_TGT_MAPTYPE_FROM) {
1868           DP("Restoring original host pointer value " DPxMOD " for host "
1869               "pointer " DPxMOD "\n", DPxPTR(it->second.HstPtrVal),
1870               DPxPTR(ShadowHstPtrAddr));
1871           *ShadowHstPtrAddr = it->second.HstPtrVal;
1872         }
1873         // If the struct is to be deallocated, remove the shadow entry.
1874         if (DelEntry) {
1875           DP("Removing shadow pointer " DPxMOD "\n", DPxPTR(ShadowHstPtrAddr));
1876           Device.ShadowPtrMap.erase(it);
1877         }
1878       }
1879       Device.ShadowMtx.unlock();
1880 
1881       // Deallocate map
1882       if (DelEntry) {
1883         int rt = Device.deallocTgtPtr(HstPtrBegin, arg_sizes[i], ForceDelete);
1884         if (rt != OFFLOAD_SUCCESS) {
1885           DP("Deallocating data from device failed.\n");
1886           rc = OFFLOAD_FAIL;
1887         }
1888       }
1889     }
1890   }
1891 
1892   return rc;
1893 }
1894 
1895 /// passes data from the target, releases target memory and destroys
1896 /// the host-target mapping (top entry from the stack of data maps)
1897 /// created by the last __tgt_target_data_begin.
1898 EXTERN void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1899     void **args_base, void **args, int64_t *arg_sizes, int32_t *arg_types) {
1900   DP("Entering data end region with %d mappings\n", arg_num);
1901 
1902   // No devices available?
1903   if (device_id == OFFLOAD_DEVICE_DEFAULT) {
1904     device_id = omp_get_default_device();
1905   }
1906 
1907   RTLsMtx.lock();
1908   size_t Devices_size = Devices.size();
1909   RTLsMtx.unlock();
1910   if (Devices_size <= (size_t)device_id) {
1911     DP("Device ID  %d does not have a matching RTL.\n", device_id);
1912     return;
1913   }
1914 
1915   DeviceTy &Device = Devices[device_id];
1916   if (!Device.IsInit) {
1917     DP("uninit device: ignore");
1918     return;
1919   }
1920 
1921   // Translate maps
1922   int32_t new_arg_num;
1923   void **new_args_base;
1924   void **new_args;
1925   int64_t *new_arg_sizes;
1926   int64_t *new_arg_types;
1927   translate_map(arg_num, args_base, args, arg_sizes, arg_types, new_arg_num,
1928       new_args_base, new_args, new_arg_sizes, new_arg_types, false);
1929 
1930   //target_data_end(Device, arg_num, args_base, args, arg_sizes, arg_types);
1931   target_data_end(Device, new_arg_num, new_args_base, new_args, new_arg_sizes,
1932       new_arg_types);
1933 
1934   // Cleanup translation memory
1935   cleanup_map(new_arg_num, new_args_base, new_args, new_arg_sizes,
1936       new_arg_types, arg_num, args_base);
1937 }
1938 
1939 EXTERN void __tgt_target_data_end_nowait(int32_t device_id, int32_t arg_num,
1940     void **args_base, void **args, int64_t *arg_sizes, int32_t *arg_types,
1941     int32_t depNum, void *depList, int32_t noAliasDepNum,
1942     void *noAliasDepList) {
1943   if (depNum + noAliasDepNum > 0)
1944     __kmpc_omp_taskwait(NULL, 0);
1945 
1946   __tgt_target_data_end(device_id, arg_num, args_base, args, arg_sizes,
1947                         arg_types);
1948 }
1949 
1950 /// passes data to/from the target.
1951 EXTERN void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
1952     void **args_base, void **args, int64_t *arg_sizes, int32_t *arg_types) {
1953   DP("Entering data update with %d mappings\n", arg_num);
1954 
1955   // No devices available?
1956   if (device_id == OFFLOAD_DEVICE_DEFAULT) {
1957     device_id = omp_get_default_device();
1958   }
1959 
1960   if (CheckDevice(device_id) != OFFLOAD_SUCCESS) {
1961     DP("Failed to get device %d ready\n", device_id);
1962     return;
1963   }
1964 
1965   DeviceTy& Device = Devices[device_id];
1966 
1967   // process each input.
1968   for (int32_t i = 0; i < arg_num; ++i) {
1969     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
1970         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
1971       continue;
1972 
1973     void *HstPtrBegin = args[i];
1974     int64_t MapSize = arg_sizes[i];
1975     bool IsLast;
1976     void *TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, MapSize, IsLast,
1977         false);
1978 
1979     if (arg_types[i] & OMP_TGT_MAPTYPE_FROM) {
1980       DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
1981           arg_sizes[i], DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
1982       Device.data_retrieve(HstPtrBegin, TgtPtrBegin, MapSize);
1983 
1984       uintptr_t lb = (uintptr_t) HstPtrBegin;
1985       uintptr_t ub = (uintptr_t) HstPtrBegin + MapSize;
1986       Device.ShadowMtx.lock();
1987       for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
1988           it != Device.ShadowPtrMap.end(); ++it) {
1989         void **ShadowHstPtrAddr = (void**) it->first;
1990         if ((uintptr_t) ShadowHstPtrAddr < lb)
1991           continue;
1992         if ((uintptr_t) ShadowHstPtrAddr >= ub)
1993           break;
1994         DP("Restoring original host pointer value " DPxMOD " for host pointer "
1995             DPxMOD "\n", DPxPTR(it->second.HstPtrVal),
1996             DPxPTR(ShadowHstPtrAddr));
1997         *ShadowHstPtrAddr = it->second.HstPtrVal;
1998       }
1999       Device.ShadowMtx.unlock();
2000     }
2001 
2002     if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
2003       DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
2004           arg_sizes[i], DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
2005       Device.data_submit(TgtPtrBegin, HstPtrBegin, MapSize);
2006 
2007       uintptr_t lb = (uintptr_t) HstPtrBegin;
2008       uintptr_t ub = (uintptr_t) HstPtrBegin + MapSize;
2009       Device.ShadowMtx.lock();
2010       for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
2011           it != Device.ShadowPtrMap.end(); ++it) {
2012         void **ShadowHstPtrAddr = (void**) it->first;
2013         if ((uintptr_t) ShadowHstPtrAddr < lb)
2014           continue;
2015         if ((uintptr_t) ShadowHstPtrAddr >= ub)
2016           break;
2017         DP("Restoring original target pointer value " DPxMOD " for target "
2018             "pointer " DPxMOD "\n", DPxPTR(it->second.TgtPtrVal),
2019             DPxPTR(it->second.TgtPtrAddr));
2020         Device.data_submit(it->second.TgtPtrAddr,
2021             &it->second.TgtPtrVal, sizeof(void *));
2022       }
2023       Device.ShadowMtx.unlock();
2024     }
2025   }
2026 }
2027 
2028 EXTERN void __tgt_target_data_update_nowait(
2029     int32_t device_id, int32_t arg_num, void **args_base, void **args,
2030     int64_t *arg_sizes, int32_t *arg_types, int32_t depNum, void *depList,
2031     int32_t noAliasDepNum, void *noAliasDepList) {
2032   if (depNum + noAliasDepNum > 0)
2033     __kmpc_omp_taskwait(NULL, 0);
2034 
2035   __tgt_target_data_update(device_id, arg_num, args_base, args, arg_sizes,
2036                            arg_types);
2037 }
2038 
2039 /// performs the same actions as data_begin in case arg_num is
2040 /// non-zero and initiates run of the offloaded region on the target platform;
2041 /// if arg_num is non-zero after the region execution is done it also
2042 /// performs the same action as data_update and data_end above. This function
2043 /// returns 0 if it was able to transfer the execution to a target and an
2044 /// integer different from zero otherwise.
2045 static int target(int32_t device_id, void *host_ptr, int32_t arg_num,
2046     void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types,
2047     int32_t team_num, int32_t thread_limit, int IsTeamConstruct) {
2048   DeviceTy &Device = Devices[device_id];
2049 
2050   // Find the table information in the map or look it up in the translation
2051   // tables.
2052   TableMap *TM = 0;
2053   TblMapMtx.lock();
2054   HostPtrToTableMapTy::iterator TableMapIt = HostPtrToTableMap.find(host_ptr);
2055   if (TableMapIt == HostPtrToTableMap.end()) {
2056     // We don't have a map. So search all the registered libraries.
2057     TrlTblMtx.lock();
2058     for (HostEntriesBeginToTransTableTy::iterator
2059              ii = HostEntriesBeginToTransTable.begin(),
2060              ie = HostEntriesBeginToTransTable.end();
2061          !TM && ii != ie; ++ii) {
2062       // get the translation table (which contains all the good info).
2063       TranslationTable *TransTable = &ii->second;
2064       // iterate over all the host table entries to see if we can locate the
2065       // host_ptr.
2066       __tgt_offload_entry *begin = TransTable->HostTable.EntriesBegin;
2067       __tgt_offload_entry *end = TransTable->HostTable.EntriesEnd;
2068       __tgt_offload_entry *cur = begin;
2069       for (uint32_t i = 0; cur < end; ++cur, ++i) {
2070         if (cur->addr != host_ptr)
2071           continue;
2072         // we got a match, now fill the HostPtrToTableMap so that we
2073         // may avoid this search next time.
2074         TM = &HostPtrToTableMap[host_ptr];
2075         TM->Table = TransTable;
2076         TM->Index = i;
2077         break;
2078       }
2079     }
2080     TrlTblMtx.unlock();
2081   } else {
2082     TM = &TableMapIt->second;
2083   }
2084   TblMapMtx.unlock();
2085 
2086   // No map for this host pointer found!
2087   if (!TM) {
2088     DP("Host ptr " DPxMOD " does not have a matching target pointer.\n",
2089        DPxPTR(host_ptr));
2090     return OFFLOAD_FAIL;
2091   }
2092 
2093   // get target table.
2094   TrlTblMtx.lock();
2095   assert(TM->Table->TargetsTable.size() > (size_t)device_id &&
2096          "Not expecting a device ID outside the table's bounds!");
2097   __tgt_target_table *TargetTable = TM->Table->TargetsTable[device_id];
2098   TrlTblMtx.unlock();
2099   assert(TargetTable && "Global data has not been mapped\n");
2100 
2101   // Move data to device.
2102   int rc = target_data_begin(Device, arg_num, args_base, args, arg_sizes,
2103       arg_types);
2104 
2105   if (rc != OFFLOAD_SUCCESS) {
2106     DP("Call to target_data_begin failed, skipping target execution.\n");
2107     // Call target_data_end to dealloc whatever target_data_begin allocated
2108     // and return OFFLOAD_FAIL.
2109     target_data_end(Device, arg_num, args_base, args, arg_sizes, arg_types);
2110     return OFFLOAD_FAIL;
2111   }
2112 
2113   std::vector<void *> tgt_args;
2114   std::vector<ptrdiff_t> tgt_offsets;
2115 
2116   // List of (first-)private arrays allocated for this target region
2117   std::vector<void *> fpArrays;
2118 
2119   for (int32_t i = 0; i < arg_num; ++i) {
2120     if (!(arg_types[i] & OMP_TGT_MAPTYPE_TARGET_PARAM)) {
2121       // This is not a target parameter, do not push it into tgt_args.
2122       continue;
2123     }
2124     void *HstPtrBegin = args[i];
2125     void *HstPtrBase = args_base[i];
2126     void *TgtPtrBegin;
2127     ptrdiff_t TgtBaseOffset;
2128     bool IsLast; // unused.
2129     if (arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) {
2130       DP("Forwarding first-private value " DPxMOD " to the target construct\n",
2131           DPxPTR(HstPtrBase));
2132       TgtPtrBegin = HstPtrBase;
2133       TgtBaseOffset = 0;
2134     } else if (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE) {
2135       // Allocate memory for (first-)private array
2136       TgtPtrBegin = Device.RTL->data_alloc(Device.RTLDeviceID,
2137           arg_sizes[i], HstPtrBegin);
2138       if (!TgtPtrBegin) {
2139         DP ("Data allocation for %sprivate array " DPxMOD " failed\n",
2140             (arg_types[i] & OMP_TGT_MAPTYPE_TO ? "first-" : ""),
2141             DPxPTR(HstPtrBegin));
2142         rc = OFFLOAD_FAIL;
2143         break;
2144       } else {
2145         fpArrays.push_back(TgtPtrBegin);
2146         TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
2147 #ifdef OMPTARGET_DEBUG
2148         void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
2149         DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD " for "
2150             "%sprivate array " DPxMOD " - pushing target argument " DPxMOD "\n",
2151             arg_sizes[i], DPxPTR(TgtPtrBegin),
2152             (arg_types[i] & OMP_TGT_MAPTYPE_TO ? "first-" : ""),
2153             DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBase));
2154 #endif
2155         // If first-private, copy data from host
2156         if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
2157           int rt = Device.data_submit(TgtPtrBegin, HstPtrBegin, arg_sizes[i]);
2158           if (rt != OFFLOAD_SUCCESS) {
2159             DP ("Copying data to device failed.\n");
2160             rc = OFFLOAD_FAIL;
2161             break;
2162           }
2163         }
2164       }
2165     } else if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ) {
2166       TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBase, sizeof(void *), IsLast,
2167           false);
2168       TgtBaseOffset = 0; // no offset for ptrs.
2169       DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD " to "
2170          "object " DPxMOD "\n", DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBase),
2171          DPxPTR(HstPtrBase));
2172     } else {
2173       TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, arg_sizes[i], IsLast,
2174           false);
2175       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
2176 #ifdef OMPTARGET_DEBUG
2177       void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
2178       DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD "\n",
2179           DPxPTR(TgtPtrBase), DPxPTR(HstPtrBegin));
2180 #endif
2181     }
2182     tgt_args.push_back(TgtPtrBegin);
2183     tgt_offsets.push_back(TgtBaseOffset);
2184   }
2185   // Push omp handle.
2186   tgt_args.push_back((void *)0);
2187   tgt_offsets.push_back(0);
2188 
2189   assert(tgt_args.size() == tgt_offsets.size() &&
2190       "Size mismatch in arguments and offsets");
2191 
2192   // Pop loop trip count
2193   uint64_t ltc = Device.loopTripCnt;
2194   Device.loopTripCnt = 0;
2195 
2196   // Launch device execution.
2197   if (rc == OFFLOAD_SUCCESS) {
2198     DP("Launching target execution %s with pointer " DPxMOD " (index=%d).\n",
2199         TargetTable->EntriesBegin[TM->Index].name,
2200         DPxPTR(TargetTable->EntriesBegin[TM->Index].addr), TM->Index);
2201     if (IsTeamConstruct) {
2202       rc = Device.run_team_region(TargetTable->EntriesBegin[TM->Index].addr,
2203           &tgt_args[0], &tgt_offsets[0], tgt_args.size(), team_num,
2204           thread_limit, ltc);
2205     } else {
2206       rc = Device.run_region(TargetTable->EntriesBegin[TM->Index].addr,
2207           &tgt_args[0], &tgt_offsets[0], tgt_args.size());
2208     }
2209   } else {
2210     DP("Errors occurred while obtaining target arguments, skipping kernel "
2211         "execution\n");
2212   }
2213 
2214   // Deallocate (first-)private arrays
2215   for (auto it : fpArrays) {
2216     int rt = Device.RTL->data_delete(Device.RTLDeviceID, it);
2217     if (rt != OFFLOAD_SUCCESS) {
2218       DP("Deallocation of (first-)private arrays failed.\n");
2219       rc = OFFLOAD_FAIL;
2220     }
2221   }
2222 
2223   // Move data from device.
2224   int rt = target_data_end(Device, arg_num, args_base, args, arg_sizes,
2225       arg_types);
2226 
2227   if (rt != OFFLOAD_SUCCESS) {
2228     DP("Call to target_data_end failed.\n");
2229     rc = OFFLOAD_FAIL;
2230   }
2231 
2232   return rc;
2233 }
2234 
2235 EXTERN int __tgt_target(int32_t device_id, void *host_ptr, int32_t arg_num,
2236     void **args_base, void **args, int64_t *arg_sizes, int32_t *arg_types) {
2237   DP("Entering target region with entry point " DPxMOD " and device Id %d\n",
2238      DPxPTR(host_ptr), device_id);
2239 
2240   if (device_id == OFFLOAD_DEVICE_DEFAULT) {
2241     device_id = omp_get_default_device();
2242   }
2243 
2244   if (CheckDevice(device_id) != OFFLOAD_SUCCESS) {
2245     DP("Failed to get device %d ready\n", device_id);
2246     return OFFLOAD_FAIL;
2247   }
2248 
2249   // Translate maps
2250   int32_t new_arg_num;
2251   void **new_args_base;
2252   void **new_args;
2253   int64_t *new_arg_sizes;
2254   int64_t *new_arg_types;
2255   translate_map(arg_num, args_base, args, arg_sizes, arg_types, new_arg_num,
2256       new_args_base, new_args, new_arg_sizes, new_arg_types, true);
2257 
2258   //return target(device_id, host_ptr, arg_num, args_base, args, arg_sizes,
2259   //    arg_types, 0, 0, false /*team*/, false /*recursive*/);
2260   int rc = target(device_id, host_ptr, new_arg_num, new_args_base, new_args,
2261       new_arg_sizes, new_arg_types, 0, 0, false /*team*/);
2262 
2263   // Cleanup translation memory
2264   cleanup_map(new_arg_num, new_args_base, new_args, new_arg_sizes,
2265       new_arg_types, arg_num, args_base);
2266 
2267   return rc;
2268 }
2269 
2270 EXTERN int __tgt_target_nowait(int32_t device_id, void *host_ptr,
2271     int32_t arg_num, void **args_base, void **args, int64_t *arg_sizes,
2272     int32_t *arg_types, int32_t depNum, void *depList, int32_t noAliasDepNum,
2273     void *noAliasDepList) {
2274   if (depNum + noAliasDepNum > 0)
2275     __kmpc_omp_taskwait(NULL, 0);
2276 
2277   return __tgt_target(device_id, host_ptr, arg_num, args_base, args, arg_sizes,
2278                       arg_types);
2279 }
2280 
2281 EXTERN int __tgt_target_teams(int32_t device_id, void *host_ptr,
2282     int32_t arg_num, void **args_base, void **args, int64_t *arg_sizes,
2283     int32_t *arg_types, int32_t team_num, int32_t thread_limit) {
2284   DP("Entering target region with entry point " DPxMOD " and device Id %d\n",
2285      DPxPTR(host_ptr), device_id);
2286 
2287   if (device_id == OFFLOAD_DEVICE_DEFAULT) {
2288     device_id = omp_get_default_device();
2289   }
2290 
2291   if (CheckDevice(device_id) != OFFLOAD_SUCCESS) {
2292     DP("Failed to get device %d ready\n", device_id);
2293     return OFFLOAD_FAIL;
2294   }
2295 
2296   // Translate maps
2297   int32_t new_arg_num;
2298   void **new_args_base;
2299   void **new_args;
2300   int64_t *new_arg_sizes;
2301   int64_t *new_arg_types;
2302   translate_map(arg_num, args_base, args, arg_sizes, arg_types, new_arg_num,
2303       new_args_base, new_args, new_arg_sizes, new_arg_types, true);
2304 
2305   //return target(device_id, host_ptr, arg_num, args_base, args, arg_sizes,
2306   //              arg_types, team_num, thread_limit, true /*team*/,
2307   //              false /*recursive*/);
2308   int rc = target(device_id, host_ptr, new_arg_num, new_args_base, new_args,
2309       new_arg_sizes, new_arg_types, team_num, thread_limit, true /*team*/);
2310 
2311   // Cleanup translation memory
2312   cleanup_map(new_arg_num, new_args_base, new_args, new_arg_sizes,
2313       new_arg_types, arg_num, args_base);
2314 
2315   return rc;
2316 }
2317 
2318 EXTERN int __tgt_target_teams_nowait(int32_t device_id, void *host_ptr,
2319     int32_t arg_num, void **args_base, void **args, int64_t *arg_sizes,
2320     int32_t *arg_types, int32_t team_num, int32_t thread_limit, int32_t depNum,
2321     void *depList, int32_t noAliasDepNum, void *noAliasDepList) {
2322   if (depNum + noAliasDepNum > 0)
2323     __kmpc_omp_taskwait(NULL, 0);
2324 
2325   return __tgt_target_teams(device_id, host_ptr, arg_num, args_base, args,
2326                             arg_sizes, arg_types, team_num, thread_limit);
2327 }
2328 
2329 
2330 // The trip count mechanism will be revised - this scheme is not thread-safe.
2331 EXTERN void __kmpc_push_target_tripcount(int32_t device_id,
2332     uint64_t loop_tripcount) {
2333   if (device_id == OFFLOAD_DEVICE_DEFAULT) {
2334     device_id = omp_get_default_device();
2335   }
2336 
2337   if (CheckDevice(device_id) != OFFLOAD_SUCCESS) {
2338     DP("Failed to get device %d ready\n", device_id);
2339     return;
2340   }
2341 
2342   DP("__kmpc_push_target_tripcount(%d, %" PRIu64 ")\n", device_id,
2343       loop_tripcount);
2344   Devices[device_id].loopTripCnt = loop_tripcount;
2345 }
2346 
2347