1 //===------ omptarget.cpp - Target independent OpenMP target RTL -- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implementation of the interface to be used by Clang during the codegen of a
10 // target region.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include <omptarget.h>
15 
16 #include "device.h"
17 #include "private.h"
18 #include "rtl.h"
19 
20 #include <cassert>
21 #include <vector>
22 
23 #ifdef OMPTARGET_DEBUG
24 int DebugLevel = 0;
25 #endif // OMPTARGET_DEBUG
26 
27 
28 
29 /* All begin addresses for partially mapped structs must be 8-aligned in order
30  * to ensure proper alignment of members. E.g.
31  *
32  * struct S {
33  *   int a;   // 4-aligned
34  *   int b;   // 4-aligned
35  *   int *p;  // 8-aligned
36  * } s1;
37  * ...
38  * #pragma omp target map(tofrom: s1.b, s1.p[0:N])
39  * {
40  *   s1.b = 5;
41  *   for (int i...) s1.p[i] = ...;
42  * }
43  *
44  * Here we are mapping s1 starting from member b, so BaseAddress=&s1=&s1.a and
45  * BeginAddress=&s1.b. Let's assume that the struct begins at address 0x100,
46  * then &s1.a=0x100, &s1.b=0x104, &s1.p=0x108. Each member obeys the alignment
47  * requirements for its type. Now, when we allocate memory on the device, in
48  * CUDA's case cuMemAlloc() returns an address which is at least 256-aligned.
49  * This means that the chunk of the struct on the device will start at a
50  * 256-aligned address, let's say 0x200. Then the address of b will be 0x200 and
51  * address of p will be a misaligned 0x204 (on the host there was no need to add
52  * padding between b and p, so p comes exactly 4 bytes after b). If the device
53  * kernel tries to access s1.p, a misaligned address error occurs (as reported
54  * by the CUDA plugin). By padding the begin address down to a multiple of 8 and
55  * extending the size of the allocated chuck accordingly, the chuck on the
56  * device will start at 0x200 with the padding (4 bytes), then &s1.b=0x204 and
57  * &s1.p=0x208, as they should be to satisfy the alignment requirements.
58  */
59 static const int64_t Alignment = 8;
60 
61 /// Map global data and execute pending ctors
62 static int InitLibrary(DeviceTy& Device) {
63   /*
64    * Map global data
65    */
66   int32_t device_id = Device.DeviceID;
67   int rc = OFFLOAD_SUCCESS;
68 
69   Device.PendingGlobalsMtx.lock();
70   TrlTblMtx->lock();
71   for (HostEntriesBeginToTransTableTy::iterator
72       ii = HostEntriesBeginToTransTable->begin();
73       ii != HostEntriesBeginToTransTable->end(); ++ii) {
74     TranslationTable *TransTable = &ii->second;
75     if (TransTable->HostTable.EntriesBegin ==
76         TransTable->HostTable.EntriesEnd) {
77       // No host entry so no need to proceed
78       continue;
79     }
80     if (TransTable->TargetsTable[device_id] != 0) {
81       // Library entries have already been processed
82       continue;
83     }
84 
85     // 1) get image.
86     assert(TransTable->TargetsImages.size() > (size_t)device_id &&
87            "Not expecting a device ID outside the table's bounds!");
88     __tgt_device_image *img = TransTable->TargetsImages[device_id];
89     if (!img) {
90       DP("No image loaded for device id %d.\n", device_id);
91       rc = OFFLOAD_FAIL;
92       break;
93     }
94     // 2) load image into the target table.
95     __tgt_target_table *TargetTable =
96         TransTable->TargetsTable[device_id] = Device.load_binary(img);
97     // Unable to get table for this image: invalidate image and fail.
98     if (!TargetTable) {
99       DP("Unable to generate entries table for device id %d.\n", device_id);
100       TransTable->TargetsImages[device_id] = 0;
101       rc = OFFLOAD_FAIL;
102       break;
103     }
104 
105     // Verify whether the two table sizes match.
106     size_t hsize =
107         TransTable->HostTable.EntriesEnd - TransTable->HostTable.EntriesBegin;
108     size_t tsize = TargetTable->EntriesEnd - TargetTable->EntriesBegin;
109 
110     // Invalid image for these host entries!
111     if (hsize != tsize) {
112       DP("Host and Target tables mismatch for device id %d [%zx != %zx].\n",
113          device_id, hsize, tsize);
114       TransTable->TargetsImages[device_id] = 0;
115       TransTable->TargetsTable[device_id] = 0;
116       rc = OFFLOAD_FAIL;
117       break;
118     }
119 
120     // process global data that needs to be mapped.
121     Device.DataMapMtx.lock();
122     __tgt_target_table *HostTable = &TransTable->HostTable;
123     for (__tgt_offload_entry *CurrDeviceEntry = TargetTable->EntriesBegin,
124                              *CurrHostEntry = HostTable->EntriesBegin,
125                              *EntryDeviceEnd = TargetTable->EntriesEnd;
126          CurrDeviceEntry != EntryDeviceEnd;
127          CurrDeviceEntry++, CurrHostEntry++) {
128       if (CurrDeviceEntry->size != 0) {
129         // has data.
130         assert(CurrDeviceEntry->size == CurrHostEntry->size &&
131                "data size mismatch");
132 
133         // Fortran may use multiple weak declarations for the same symbol,
134         // therefore we must allow for multiple weak symbols to be loaded from
135         // the fat binary. Treat these mappings as any other "regular" mapping.
136         // Add entry to map.
137         if (Device.getTgtPtrBegin(CurrHostEntry->addr, CurrHostEntry->size))
138           continue;
139         DP("Add mapping from host " DPxMOD " to device " DPxMOD " with size %zu"
140             "\n", DPxPTR(CurrHostEntry->addr), DPxPTR(CurrDeviceEntry->addr),
141             CurrDeviceEntry->size);
142         Device.HostDataToTargetMap.emplace(
143             (uintptr_t)CurrHostEntry->addr /*HstPtrBase*/,
144             (uintptr_t)CurrHostEntry->addr /*HstPtrBegin*/,
145             (uintptr_t)CurrHostEntry->addr + CurrHostEntry->size /*HstPtrEnd*/,
146             (uintptr_t)CurrDeviceEntry->addr /*TgtPtrBegin*/,
147             true /*IsRefCountINF*/);
148       }
149     }
150     Device.DataMapMtx.unlock();
151   }
152   TrlTblMtx->unlock();
153 
154   if (rc != OFFLOAD_SUCCESS) {
155     Device.PendingGlobalsMtx.unlock();
156     return rc;
157   }
158 
159   /*
160    * Run ctors for static objects
161    */
162   if (!Device.PendingCtorsDtors.empty()) {
163     // Call all ctors for all libraries registered so far
164     for (auto &lib : Device.PendingCtorsDtors) {
165       if (!lib.second.PendingCtors.empty()) {
166         DP("Has pending ctors... call now\n");
167         for (auto &entry : lib.second.PendingCtors) {
168           void *ctor = entry;
169           int rc = target(device_id, ctor, 0, NULL, NULL, NULL, NULL, NULL, 1,
170               1, true /*team*/);
171           if (rc != OFFLOAD_SUCCESS) {
172             DP("Running ctor " DPxMOD " failed.\n", DPxPTR(ctor));
173             Device.PendingGlobalsMtx.unlock();
174             return OFFLOAD_FAIL;
175           }
176         }
177         // Clear the list to indicate that this device has been used
178         lib.second.PendingCtors.clear();
179         DP("Done with pending ctors for lib " DPxMOD "\n", DPxPTR(lib.first));
180       }
181     }
182   }
183   Device.HasPendingGlobals = false;
184   Device.PendingGlobalsMtx.unlock();
185 
186   return OFFLOAD_SUCCESS;
187 }
188 
189 // Check whether a device has been initialized, global ctors have been
190 // executed and global data has been mapped; do so if not already done.
191 int CheckDeviceAndCtors(int64_t device_id) {
192   // Is device ready?
193   if (!device_is_ready(device_id)) {
194     DP("Device %" PRId64 " is not ready.\n", device_id);
195     return OFFLOAD_FAIL;
196   }
197 
198   // Get device info.
199   DeviceTy &Device = Devices[device_id];
200 
201   // Check whether global data has been mapped for this device
202   Device.PendingGlobalsMtx.lock();
203   bool hasPendingGlobals = Device.HasPendingGlobals;
204   Device.PendingGlobalsMtx.unlock();
205   if (hasPendingGlobals && InitLibrary(Device) != OFFLOAD_SUCCESS) {
206     DP("Failed to init globals on device %" PRId64 "\n", device_id);
207     return OFFLOAD_FAIL;
208   }
209 
210   return OFFLOAD_SUCCESS;
211 }
212 
213 static int32_t getParentIndex(int64_t type) {
214   return ((type & OMP_TGT_MAPTYPE_MEMBER_OF) >> 48) - 1;
215 }
216 
217 /// Call the user-defined mapper function followed by the appropriate
218 // target_data_* function (target_data_{begin,end,update}).
219 int targetDataMapper(DeviceTy &Device, void *arg_base, void *arg,
220                      int64_t arg_size, int64_t arg_type, void *arg_mapper,
221                      TargetDataFuncPtrTy target_data_function) {
222   DP("Calling the mapper function " DPxMOD "\n", DPxPTR(arg_mapper));
223 
224   // The mapper function fills up Components.
225   MapperComponentsTy MapperComponents;
226   MapperFuncPtrTy MapperFuncPtr = (MapperFuncPtrTy)(arg_mapper);
227   (*MapperFuncPtr)((void *)&MapperComponents, arg_base, arg, arg_size,
228       arg_type);
229 
230   // Construct new arrays for args_base, args, arg_sizes and arg_types
231   // using the information in MapperComponents and call the corresponding
232   // target_data_* function using these new arrays.
233   std::vector<void *> mapper_args_base;
234   std::vector<void *> mapper_args;
235   std::vector<int64_t> mapper_arg_sizes;
236   std::vector<int64_t> mapper_arg_types;
237 
238   for (auto& C : MapperComponents.Components) {
239     mapper_args_base.push_back(C.Base);
240     mapper_args.push_back(C.Begin);
241     mapper_arg_sizes.push_back(C.Size);
242     mapper_arg_types.push_back(C.Type);
243   }
244 
245   int rc = target_data_function(Device, MapperComponents.Components.size(),
246       mapper_args_base.data(), mapper_args.data(), mapper_arg_sizes.data(),
247       mapper_arg_types.data(), /*arg_mappers*/ nullptr,
248       /*__tgt_async_info*/ nullptr);
249 
250   return rc;
251 }
252 
253 /// Internal function to do the mapping and transfer the data to the device
254 int targetDataBegin(DeviceTy &Device, int32_t arg_num, void **args_base,
255                     void **args, int64_t *arg_sizes, int64_t *arg_types,
256                     void **arg_mappers, __tgt_async_info *async_info_ptr) {
257   // process each input.
258   for (int32_t i = 0; i < arg_num; ++i) {
259     // Ignore private variables and arrays - there is no mapping for them.
260     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
261         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
262       continue;
263 
264     if (arg_mappers && arg_mappers[i]) {
265       // Instead of executing the regular path of targetDataBegin, call the
266       // targetDataMapper variant which will call targetDataBegin again
267       // with new arguments.
268       DP("Calling targetDataMapper for the %dth argument\n", i);
269 
270       int rc = targetDataMapper(Device, args_base[i], args[i], arg_sizes[i],
271                                 arg_types[i], arg_mappers[i], targetDataBegin);
272 
273       if (rc != OFFLOAD_SUCCESS) {
274         DP("Call to targetDataBegin via targetDataMapper for custom mapper"
275            " failed.\n");
276         return OFFLOAD_FAIL;
277       }
278 
279       // Skip the rest of this function, continue to the next argument.
280       continue;
281     }
282 
283     void *HstPtrBegin = args[i];
284     void *HstPtrBase = args_base[i];
285     int64_t data_size = arg_sizes[i];
286 
287     // Adjust for proper alignment if this is a combined entry (for structs).
288     // Look at the next argument - if that is MEMBER_OF this one, then this one
289     // is a combined entry.
290     int64_t padding = 0;
291     const int next_i = i+1;
292     if (getParentIndex(arg_types[i]) < 0 && next_i < arg_num &&
293         getParentIndex(arg_types[next_i]) == i) {
294       padding = (int64_t)HstPtrBegin % Alignment;
295       if (padding) {
296         DP("Using a padding of %" PRId64 " bytes for begin address " DPxMOD
297             "\n", padding, DPxPTR(HstPtrBegin));
298         HstPtrBegin = (char *) HstPtrBegin - padding;
299         data_size += padding;
300       }
301     }
302 
303     // Address of pointer on the host and device, respectively.
304     void *Pointer_HstPtrBegin, *PointerTgtPtrBegin;
305     bool IsNew, Pointer_IsNew;
306     bool IsHostPtr = false;
307     bool IsImplicit = arg_types[i] & OMP_TGT_MAPTYPE_IMPLICIT;
308     // Force the creation of a device side copy of the data when:
309     // a close map modifier was associated with a map that contained a to.
310     bool HasCloseModifier = arg_types[i] & OMP_TGT_MAPTYPE_CLOSE;
311     bool HasPresentModifier = arg_types[i] & OMP_TGT_MAPTYPE_PRESENT;
312     // UpdateRef is based on MEMBER_OF instead of TARGET_PARAM because if we
313     // have reached this point via __tgt_target_data_begin and not __tgt_target
314     // then no argument is marked as TARGET_PARAM ("omp target data map" is not
315     // associated with a target region, so there are no target parameters). This
316     // may be considered a hack, we could revise the scheme in the future.
317     bool UpdateRef = !(arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF);
318     if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ) {
319       DP("Has a pointer entry: \n");
320       // Base is address of pointer.
321       //
322       // Usually, the pointer is already allocated by this time.  For example:
323       //
324       //   #pragma omp target map(s.p[0:N])
325       //
326       // The map entry for s comes first, and the PTR_AND_OBJ entry comes
327       // afterward, so the pointer is already allocated by the time the
328       // PTR_AND_OBJ entry is handled below, and PointerTgtPtrBegin is thus
329       // non-null.  However, "declare target link" can produce a PTR_AND_OBJ
330       // entry for a global that might not already be allocated by the time the
331       // PTR_AND_OBJ entry is handled below, and so the allocation might fail
332       // when HasPresentModifier.
333       PointerTgtPtrBegin = Device.getOrAllocTgtPtr(
334           HstPtrBase, HstPtrBase, sizeof(void *), Pointer_IsNew, IsHostPtr,
335           IsImplicit, UpdateRef, HasCloseModifier, HasPresentModifier);
336       if (!PointerTgtPtrBegin) {
337         DP("Call to getOrAllocTgtPtr returned null pointer (%s).\n",
338            HasPresentModifier ? "'present' map type modifier"
339                               : "device failure or illegal mapping");
340         return OFFLOAD_FAIL;
341       }
342       DP("There are %zu bytes allocated at target address " DPxMOD " - is%s new"
343           "\n", sizeof(void *), DPxPTR(PointerTgtPtrBegin),
344           (Pointer_IsNew ? "" : " not"));
345       Pointer_HstPtrBegin = HstPtrBase;
346       // modify current entry.
347       HstPtrBase = *(void **)HstPtrBase;
348       UpdateRef = true; // subsequently update ref count of pointee
349     }
350 
351     void *TgtPtrBegin = Device.getOrAllocTgtPtr(
352         HstPtrBegin, HstPtrBase, data_size, IsNew, IsHostPtr, IsImplicit,
353         UpdateRef, HasCloseModifier, HasPresentModifier);
354     // If data_size==0, then the argument could be a zero-length pointer to
355     // NULL, so getOrAlloc() returning NULL is not an error.
356     if (!TgtPtrBegin && (data_size || HasPresentModifier)) {
357       DP("Call to getOrAllocTgtPtr returned null pointer (%s).\n",
358          HasPresentModifier ? "'present' map type modifier"
359                             : "device failure or illegal mapping");
360       return OFFLOAD_FAIL;
361     }
362     DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
363         " - is%s new\n", data_size, DPxPTR(TgtPtrBegin),
364         (IsNew ? "" : " not"));
365 
366     if (arg_types[i] & OMP_TGT_MAPTYPE_RETURN_PARAM) {
367       uintptr_t Delta = (uintptr_t)HstPtrBegin - (uintptr_t)HstPtrBase;
368       void *TgtPtrBase = (void *)((uintptr_t)TgtPtrBegin - Delta);
369       DP("Returning device pointer " DPxMOD "\n", DPxPTR(TgtPtrBase));
370       args_base[i] = TgtPtrBase;
371     }
372 
373     if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
374       bool copy = false;
375       if (!(RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) ||
376           HasCloseModifier) {
377         if (IsNew || (arg_types[i] & OMP_TGT_MAPTYPE_ALWAYS)) {
378           copy = true;
379         } else if (arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) {
380           // Copy data only if the "parent" struct has RefCount==1.
381           int32_t parent_idx = getParentIndex(arg_types[i]);
382           uint64_t parent_rc = Device.getMapEntryRefCnt(args[parent_idx]);
383           assert(parent_rc > 0 && "parent struct not found");
384           if (parent_rc == 1) {
385             copy = true;
386           }
387         }
388       }
389 
390       if (copy && !IsHostPtr) {
391         DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
392            data_size, DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
393         int rt = Device.submitData(TgtPtrBegin, HstPtrBegin, data_size,
394                                    async_info_ptr);
395         if (rt != OFFLOAD_SUCCESS) {
396           DP("Copying data to device failed.\n");
397           return OFFLOAD_FAIL;
398         }
399       }
400     }
401 
402     if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ && !IsHostPtr) {
403       DP("Update pointer (" DPxMOD ") -> [" DPxMOD "]\n",
404          DPxPTR(PointerTgtPtrBegin), DPxPTR(TgtPtrBegin));
405       uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
406       void *TgtPtrBase = (void *)((uint64_t)TgtPtrBegin - Delta);
407       int rt = Device.submitData(PointerTgtPtrBegin, &TgtPtrBase,
408                                  sizeof(void *), async_info_ptr);
409       if (rt != OFFLOAD_SUCCESS) {
410         DP("Copying data to device failed.\n");
411         return OFFLOAD_FAIL;
412       }
413       // create shadow pointers for this entry
414       Device.ShadowMtx.lock();
415       Device.ShadowPtrMap[Pointer_HstPtrBegin] = {
416           HstPtrBase, PointerTgtPtrBegin, TgtPtrBase};
417       Device.ShadowMtx.unlock();
418     }
419   }
420 
421   return OFFLOAD_SUCCESS;
422 }
423 
424 /// Internal function to undo the mapping and retrieve the data from the device.
425 int targetDataEnd(DeviceTy &Device, int32_t ArgNum, void **ArgBases,
426                   void **Args, int64_t *ArgSizes, int64_t *ArgTypes,
427                   void **ArgMappers, __tgt_async_info *AsyncInfo) {
428   int Ret;
429   // process each input.
430   for (int32_t I = ArgNum - 1; I >= 0; --I) {
431     // Ignore private variables and arrays - there is no mapping for them.
432     // Also, ignore the use_device_ptr directive, it has no effect here.
433     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) ||
434         (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE))
435       continue;
436 
437     if (ArgMappers && ArgMappers[I]) {
438       // Instead of executing the regular path of targetDataEnd, call the
439       // targetDataMapper variant which will call targetDataEnd again
440       // with new arguments.
441       DP("Calling targetDataMapper for the %dth argument\n", I);
442 
443       Ret = targetDataMapper(Device, ArgBases[I], Args[I], ArgSizes[I],
444                              ArgTypes[I], ArgMappers[I], targetDataEnd);
445 
446       if (Ret != OFFLOAD_SUCCESS) {
447         DP("Call to targetDataEnd via targetDataMapper for custom mapper"
448            " failed.\n");
449         return OFFLOAD_FAIL;
450       }
451 
452       // Skip the rest of this function, continue to the next argument.
453       continue;
454     }
455 
456     void *HstPtrBegin = Args[I];
457     int64_t DataSize = ArgSizes[I];
458     // Adjust for proper alignment if this is a combined entry (for structs).
459     // Look at the next argument - if that is MEMBER_OF this one, then this one
460     // is a combined entry.
461     const int NextI = I + 1;
462     if (getParentIndex(ArgTypes[I]) < 0 && NextI < ArgNum &&
463         getParentIndex(ArgTypes[NextI]) == I) {
464       int64_t Padding = (int64_t)HstPtrBegin % Alignment;
465       if (Padding) {
466         DP("Using a Padding of %" PRId64 " bytes for begin address " DPxMOD
467            "\n",
468            Padding, DPxPTR(HstPtrBegin));
469         HstPtrBegin = (char *)HstPtrBegin - Padding;
470         DataSize += Padding;
471       }
472     }
473 
474     bool IsLast, IsHostPtr;
475     bool UpdateRef = !(ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) ||
476                      (ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ);
477     bool ForceDelete = ArgTypes[I] & OMP_TGT_MAPTYPE_DELETE;
478     bool HasCloseModifier = ArgTypes[I] & OMP_TGT_MAPTYPE_CLOSE;
479     bool HasPresentModifier = ArgTypes[I] & OMP_TGT_MAPTYPE_PRESENT;
480 
481     // If PTR_AND_OBJ, HstPtrBegin is address of pointee
482     void *TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, DataSize, IsLast,
483                                               UpdateRef, IsHostPtr);
484     if (!TgtPtrBegin && (DataSize || HasPresentModifier)) {
485       DP("Mapping does not exist (%s)\n",
486          (HasPresentModifier ? "'present' map type modifier" : "ignored"));
487       if (HasPresentModifier) {
488         // FIXME: This should not be an error on exit from "omp target data",
489         // but it should be an error upon entering an "omp target exit data".
490         MESSAGE("device mapping required by 'present' map type modifier does "
491                 "not exist for host address " DPxMOD " (%ld bytes)",
492                 DPxPTR(HstPtrBegin), DataSize);
493         return OFFLOAD_FAIL;
494       }
495     } else {
496       DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
497          " - is%s last\n",
498          DataSize, DPxPTR(TgtPtrBegin), (IsLast ? "" : " not"));
499     }
500 
501     bool DelEntry = IsLast || ForceDelete;
502 
503     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
504         !(ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
505       DelEntry = false; // protect parent struct from being deallocated
506     }
507 
508     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) || DelEntry) {
509       // Move data back to the host
510       if (ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) {
511         bool Always = ArgTypes[I] & OMP_TGT_MAPTYPE_ALWAYS;
512         bool CopyMember = false;
513         if (!(RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) ||
514             HasCloseModifier) {
515           if ((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
516               !(ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
517             // Copy data only if the "parent" struct has RefCount==1.
518             int32_t ParentIdx = getParentIndex(ArgTypes[I]);
519             uint64_t ParentRC = Device.getMapEntryRefCnt(Args[ParentIdx]);
520             assert(ParentRC > 0 && "parent struct not found");
521             if (ParentRC == 1)
522               CopyMember = true;
523           }
524         }
525 
526         if ((DelEntry || Always || CopyMember) &&
527             !(RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
528               TgtPtrBegin == HstPtrBegin)) {
529           DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
530              DataSize, DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
531           Ret = Device.retrieveData(HstPtrBegin, TgtPtrBegin, DataSize,
532                                     AsyncInfo);
533           if (Ret != OFFLOAD_SUCCESS) {
534             DP("Copying data from device failed.\n");
535             return OFFLOAD_FAIL;
536           }
537         }
538       }
539 
540       // If we copied back to the host a struct/array containing pointers, we
541       // need to restore the original host pointer values from their shadow
542       // copies. If the struct is going to be deallocated, remove any remaining
543       // shadow pointer entries for this struct.
544       uintptr_t LB = (uintptr_t)HstPtrBegin;
545       uintptr_t UB = (uintptr_t)HstPtrBegin + DataSize;
546       Device.ShadowMtx.lock();
547       for (ShadowPtrListTy::iterator Itr = Device.ShadowPtrMap.begin();
548            Itr != Device.ShadowPtrMap.end();) {
549         void **ShadowHstPtrAddr = (void **)Itr->first;
550 
551         // An STL map is sorted on its keys; use this property
552         // to quickly determine when to break out of the loop.
553         if ((uintptr_t)ShadowHstPtrAddr < LB) {
554           ++Itr;
555           continue;
556         }
557         if ((uintptr_t)ShadowHstPtrAddr >= UB)
558           break;
559 
560         // If we copied the struct to the host, we need to restore the pointer.
561         if (ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) {
562           DP("Restoring original host pointer value " DPxMOD " for host "
563              "pointer " DPxMOD "\n",
564              DPxPTR(Itr->second.HstPtrVal), DPxPTR(ShadowHstPtrAddr));
565           *ShadowHstPtrAddr = Itr->second.HstPtrVal;
566         }
567         // If the struct is to be deallocated, remove the shadow entry.
568         if (DelEntry) {
569           DP("Removing shadow pointer " DPxMOD "\n", DPxPTR(ShadowHstPtrAddr));
570           Itr = Device.ShadowPtrMap.erase(Itr);
571         } else {
572           ++Itr;
573         }
574       }
575       Device.ShadowMtx.unlock();
576 
577       // Deallocate map
578       if (DelEntry) {
579         Ret = Device.deallocTgtPtr(HstPtrBegin, DataSize, ForceDelete,
580                                    HasCloseModifier);
581         if (Ret != OFFLOAD_SUCCESS) {
582           DP("Deallocating data from device failed.\n");
583           return OFFLOAD_FAIL;
584         }
585       }
586     }
587   }
588 
589   return OFFLOAD_SUCCESS;
590 }
591 
592 /// Internal function to pass data to/from the target.
593 // async_info_ptr is currently unused, added here so target_data_update has the
594 // same signature as targetDataBegin and targetDataEnd.
595 int target_data_update(DeviceTy &Device, int32_t arg_num,
596     void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types,
597     void **arg_mappers, __tgt_async_info *async_info_ptr) {
598   // process each input.
599   for (int32_t i = 0; i < arg_num; ++i) {
600     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
601         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
602       continue;
603 
604     if (arg_mappers && arg_mappers[i]) {
605       // Instead of executing the regular path of target_data_update, call the
606       // targetDataMapper variant which will call target_data_update again
607       // with new arguments.
608       DP("Calling targetDataMapper for the %dth argument\n", i);
609 
610       int rc =
611           targetDataMapper(Device, args_base[i], args[i], arg_sizes[i],
612                            arg_types[i], arg_mappers[i], target_data_update);
613 
614       if (rc != OFFLOAD_SUCCESS) {
615         DP("Call to target_data_update via targetDataMapper for custom mapper"
616            " failed.\n");
617         return OFFLOAD_FAIL;
618       }
619 
620       // Skip the rest of this function, continue to the next argument.
621       continue;
622     }
623 
624     void *HstPtrBegin = args[i];
625     int64_t MapSize = arg_sizes[i];
626     bool IsLast, IsHostPtr;
627     void *TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, MapSize, IsLast,
628         false, IsHostPtr);
629     if (!TgtPtrBegin) {
630       DP("hst data:" DPxMOD " not found, becomes a noop\n", DPxPTR(HstPtrBegin));
631       if (arg_types[i] & OMP_TGT_MAPTYPE_PRESENT) {
632         MESSAGE("device mapping required by 'present' motion modifier does not "
633                 "exist for host address " DPxMOD " (%ld bytes)",
634                 DPxPTR(HstPtrBegin), MapSize);
635         return OFFLOAD_FAIL;
636       }
637       continue;
638     }
639 
640     if (RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
641         TgtPtrBegin == HstPtrBegin) {
642       DP("hst data:" DPxMOD " unified and shared, becomes a noop\n",
643          DPxPTR(HstPtrBegin));
644       continue;
645     }
646 
647     if (arg_types[i] & OMP_TGT_MAPTYPE_FROM) {
648       DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
649           arg_sizes[i], DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
650       int rt = Device.retrieveData(HstPtrBegin, TgtPtrBegin, MapSize, nullptr);
651       if (rt != OFFLOAD_SUCCESS) {
652         DP("Copying data from device failed.\n");
653         return OFFLOAD_FAIL;
654       }
655 
656       uintptr_t lb = (uintptr_t) HstPtrBegin;
657       uintptr_t ub = (uintptr_t) HstPtrBegin + MapSize;
658       Device.ShadowMtx.lock();
659       for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
660           it != Device.ShadowPtrMap.end(); ++it) {
661         void **ShadowHstPtrAddr = (void**) it->first;
662         if ((uintptr_t) ShadowHstPtrAddr < lb)
663           continue;
664         if ((uintptr_t) ShadowHstPtrAddr >= ub)
665           break;
666         DP("Restoring original host pointer value " DPxMOD " for host pointer "
667             DPxMOD "\n", DPxPTR(it->second.HstPtrVal),
668             DPxPTR(ShadowHstPtrAddr));
669         *ShadowHstPtrAddr = it->second.HstPtrVal;
670       }
671       Device.ShadowMtx.unlock();
672     }
673 
674     if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
675       DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
676           arg_sizes[i], DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
677       int rt = Device.submitData(TgtPtrBegin, HstPtrBegin, MapSize, nullptr);
678       if (rt != OFFLOAD_SUCCESS) {
679         DP("Copying data to device failed.\n");
680         return OFFLOAD_FAIL;
681       }
682 
683       uintptr_t lb = (uintptr_t) HstPtrBegin;
684       uintptr_t ub = (uintptr_t) HstPtrBegin + MapSize;
685       Device.ShadowMtx.lock();
686       for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
687           it != Device.ShadowPtrMap.end(); ++it) {
688         void **ShadowHstPtrAddr = (void **)it->first;
689         if ((uintptr_t)ShadowHstPtrAddr < lb)
690           continue;
691         if ((uintptr_t)ShadowHstPtrAddr >= ub)
692           break;
693         DP("Restoring original target pointer value " DPxMOD " for target "
694            "pointer " DPxMOD "\n",
695            DPxPTR(it->second.TgtPtrVal), DPxPTR(it->second.TgtPtrAddr));
696         rt = Device.submitData(it->second.TgtPtrAddr, &it->second.TgtPtrVal,
697                                sizeof(void *), nullptr);
698         if (rt != OFFLOAD_SUCCESS) {
699           DP("Copying data to device failed.\n");
700           Device.ShadowMtx.unlock();
701           return OFFLOAD_FAIL;
702         }
703       }
704       Device.ShadowMtx.unlock();
705     }
706   }
707   return OFFLOAD_SUCCESS;
708 }
709 
710 static const unsigned LambdaMapping = OMP_TGT_MAPTYPE_PTR_AND_OBJ |
711                                       OMP_TGT_MAPTYPE_LITERAL |
712                                       OMP_TGT_MAPTYPE_IMPLICIT;
713 static bool isLambdaMapping(int64_t Mapping) {
714   return (Mapping & LambdaMapping) == LambdaMapping;
715 }
716 
717 namespace {
718 /// Find the table information in the map or look it up in the translation
719 /// tables.
720 TableMap *getTableMap(void *HostPtr) {
721   std::lock_guard<std::mutex> TblMapLock(*TblMapMtx);
722   HostPtrToTableMapTy::iterator TableMapIt = HostPtrToTableMap->find(HostPtr);
723 
724   if (TableMapIt != HostPtrToTableMap->end())
725     return &TableMapIt->second;
726 
727   // We don't have a map. So search all the registered libraries.
728   TableMap *TM = nullptr;
729   std::lock_guard<std::mutex> TrlTblLock(*TrlTblMtx);
730   for (HostEntriesBeginToTransTableTy::iterator Itr =
731            HostEntriesBeginToTransTable->begin();
732        Itr != HostEntriesBeginToTransTable->end(); ++Itr) {
733     // get the translation table (which contains all the good info).
734     TranslationTable *TransTable = &Itr->second;
735     // iterate over all the host table entries to see if we can locate the
736     // host_ptr.
737     __tgt_offload_entry *Cur = TransTable->HostTable.EntriesBegin;
738     for (uint32_t I = 0; Cur < TransTable->HostTable.EntriesEnd; ++Cur, ++I) {
739       if (Cur->addr != HostPtr)
740         continue;
741       // we got a match, now fill the HostPtrToTableMap so that we
742       // may avoid this search next time.
743       TM = &(*HostPtrToTableMap)[HostPtr];
744       TM->Table = TransTable;
745       TM->Index = I;
746       return TM;
747     }
748   }
749 
750   return nullptr;
751 }
752 
753 /// Get loop trip count
754 /// FIXME: This function will not work right if calling
755 /// __kmpc_push_target_tripcount in one thread but doing offloading in another
756 /// thread, which might occur when we call task yield.
757 uint64_t getLoopTripCount(int64_t DeviceId) {
758   DeviceTy &Device = Devices[DeviceId];
759   uint64_t LoopTripCount = 0;
760 
761   {
762     std::lock_guard<std::mutex> TblMapLock(*TblMapMtx);
763     auto I = Device.LoopTripCnt.find(__kmpc_global_thread_num(NULL));
764     if (I != Device.LoopTripCnt.end()) {
765       LoopTripCount = I->second;
766       Device.LoopTripCnt.erase(I);
767       DP("loop trip count is %lu.\n", LoopTripCount);
768     }
769   }
770 
771   return LoopTripCount;
772 }
773 
774 /// Process data before launching the kernel, including calling targetDataBegin
775 /// to map and transfer data to target device, transferring (first-)private
776 /// variables.
777 int processDataBefore(int64_t DeviceId, void *HostPtr, int32_t ArgNum,
778                       void **ArgBases, void **Args, int64_t *ArgSizes,
779                       int64_t *ArgTypes, void **ArgMappers,
780                       std::vector<void *> &TgtArgs,
781                       std::vector<ptrdiff_t> &TgtOffsets,
782                       std::vector<void *> &FPArrays,
783                       __tgt_async_info *AsyncInfo) {
784   DeviceTy &Device = Devices[DeviceId];
785   int Ret = targetDataBegin(Device, ArgNum, ArgBases, Args, ArgSizes, ArgTypes,
786                             ArgMappers, AsyncInfo);
787   if (Ret != OFFLOAD_SUCCESS) {
788     DP("Call to targetDataBegin failed, abort target.\n");
789     return OFFLOAD_FAIL;
790   }
791 
792   // List of (first-)private arrays allocated for this target region
793   std::vector<int> TgtArgsPositions(ArgNum, -1);
794 
795   for (int32_t I = 0; I < ArgNum; ++I) {
796     if (!(ArgTypes[I] & OMP_TGT_MAPTYPE_TARGET_PARAM)) {
797       // This is not a target parameter, do not push it into TgtArgs.
798       // Check for lambda mapping.
799       if (isLambdaMapping(ArgTypes[I])) {
800         assert((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
801                "PTR_AND_OBJ must be also MEMBER_OF.");
802         unsigned Idx = getParentIndex(ArgTypes[I]);
803         int TgtIdx = TgtArgsPositions[Idx];
804         assert(TgtIdx != -1 && "Base address must be translated already.");
805         // The parent lambda must be processed already and it must be the last
806         // in TgtArgs and TgtOffsets arrays.
807         void *HstPtrVal = Args[I];
808         void *HstPtrBegin = ArgBases[I];
809         void *HstPtrBase = Args[Idx];
810         bool IsLast, IsHostPtr; // unused.
811         void *TgtPtrBase =
812             (void *)((intptr_t)TgtArgs[TgtIdx] + TgtOffsets[TgtIdx]);
813         DP("Parent lambda base " DPxMOD "\n", DPxPTR(TgtPtrBase));
814         uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
815         void *TgtPtrBegin = (void *)((uintptr_t)TgtPtrBase + Delta);
816         void *PointerTgtPtrBegin = Device.getTgtPtrBegin(
817             HstPtrVal, ArgSizes[I], IsLast, false, IsHostPtr);
818         if (!PointerTgtPtrBegin) {
819           DP("No lambda captured variable mapped (" DPxMOD ") - ignored\n",
820              DPxPTR(HstPtrVal));
821           continue;
822         }
823         if (RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
824             TgtPtrBegin == HstPtrBegin) {
825           DP("Unified memory is active, no need to map lambda captured"
826              "variable (" DPxMOD ")\n",
827              DPxPTR(HstPtrVal));
828           continue;
829         }
830         DP("Update lambda reference (" DPxMOD ") -> [" DPxMOD "]\n",
831            DPxPTR(PointerTgtPtrBegin), DPxPTR(TgtPtrBegin));
832         Ret = Device.submitData(TgtPtrBegin, &PointerTgtPtrBegin,
833                                 sizeof(void *), AsyncInfo);
834         if (Ret != OFFLOAD_SUCCESS) {
835           DP("Copying data to device failed.\n");
836           return OFFLOAD_FAIL;
837         }
838       }
839       continue;
840     }
841     void *HstPtrBegin = Args[I];
842     void *HstPtrBase = ArgBases[I];
843     void *TgtPtrBegin;
844     ptrdiff_t TgtBaseOffset;
845     bool IsLast, IsHostPtr; // unused.
846     if (ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) {
847       DP("Forwarding first-private value " DPxMOD " to the target construct\n",
848          DPxPTR(HstPtrBase));
849       TgtPtrBegin = HstPtrBase;
850       TgtBaseOffset = 0;
851     } else if (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE) {
852       // Allocate memory for (first-)private array
853       TgtPtrBegin = Device.allocData(ArgSizes[I], HstPtrBegin);
854       if (!TgtPtrBegin) {
855         DP("Data allocation for %sprivate array " DPxMOD " failed, "
856            "abort target.\n",
857            (ArgTypes[I] & OMP_TGT_MAPTYPE_TO ? "first-" : ""),
858            DPxPTR(HstPtrBegin));
859         return OFFLOAD_FAIL;
860       }
861       FPArrays.push_back(TgtPtrBegin);
862       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
863 #ifdef OMPTARGET_DEBUG
864       void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
865       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD " for "
866          "%sprivate array " DPxMOD " - pushing target argument " DPxMOD "\n",
867          ArgSizes[I], DPxPTR(TgtPtrBegin),
868          (ArgTypes[I] & OMP_TGT_MAPTYPE_TO ? "first-" : ""),
869          DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBase));
870 #endif
871       // If first-private, copy data from host
872       if (ArgTypes[I] & OMP_TGT_MAPTYPE_TO) {
873         Ret =
874             Device.submitData(TgtPtrBegin, HstPtrBegin, ArgSizes[I], AsyncInfo);
875         if (Ret != OFFLOAD_SUCCESS) {
876           DP("Copying data to device failed, failed.\n");
877           return OFFLOAD_FAIL;
878         }
879       }
880     } else {
881       if (ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)
882         HstPtrBase = *reinterpret_cast<void **>(HstPtrBase);
883       TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, ArgSizes[I], IsLast,
884                                           false, IsHostPtr);
885       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
886 #ifdef OMPTARGET_DEBUG
887       void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
888       DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD "\n",
889          DPxPTR(TgtPtrBase), DPxPTR(HstPtrBegin));
890 #endif
891     }
892     TgtArgsPositions[I] = TgtArgs.size();
893     TgtArgs.push_back(TgtPtrBegin);
894     TgtOffsets.push_back(TgtBaseOffset);
895   }
896 
897   assert(TgtArgs.size() == TgtOffsets.size() &&
898          "Size mismatch in arguments and offsets");
899 
900   return OFFLOAD_SUCCESS;
901 }
902 
903 /// Process data after launching the kernel, including transferring data back to
904 /// host if needed and deallocating target memory of (first-)private variables.
905 /// FIXME: This function has correctness issue that target memory might be
906 /// deallocated when they're being used.
907 int processDataAfter(int64_t DeviceId, void *HostPtr, int32_t ArgNum,
908                      void **ArgBases, void **Args, int64_t *ArgSizes,
909                      int64_t *ArgTypes, void **ArgMappers,
910                      std::vector<void *> &FPArrays,
911                      __tgt_async_info *AsyncInfo) {
912   DeviceTy &Device = Devices[DeviceId];
913 
914   // Move data from device.
915   int Ret = targetDataEnd(Device, ArgNum, ArgBases, Args, ArgSizes, ArgTypes,
916                           ArgMappers, AsyncInfo);
917   if (Ret != OFFLOAD_SUCCESS) {
918     DP("Call to targetDataEnd failed, abort targe.\n");
919     return OFFLOAD_FAIL;
920   }
921 
922   // Deallocate (first-)private arrays
923   for (void *P : FPArrays) {
924     Ret = Device.deleteData(P);
925     if (Ret != OFFLOAD_SUCCESS) {
926       DP("Deallocation of (first-)private arrays failed.\n");
927       return OFFLOAD_FAIL;
928     }
929   }
930 
931   return OFFLOAD_SUCCESS;
932 }
933 } // namespace
934 
935 /// performs the same actions as data_begin in case arg_num is
936 /// non-zero and initiates run of the offloaded region on the target platform;
937 /// if arg_num is non-zero after the region execution is done it also
938 /// performs the same action as data_update and data_end above. This function
939 /// returns 0 if it was able to transfer the execution to a target and an
940 /// integer different from zero otherwise.
941 int target(int64_t DeviceId, void *HostPtr, int32_t ArgNum, void **ArgBases,
942            void **Args, int64_t *ArgSizes, int64_t *ArgTypes, void **ArgMappers,
943            int32_t TeamNum, int32_t ThreadLimit, int IsTeamConstruct) {
944   DeviceTy &Device = Devices[DeviceId];
945 
946   TableMap *TM = getTableMap(HostPtr);
947   // No map for this host pointer found!
948   if (!TM) {
949     DP("Host ptr " DPxMOD " does not have a matching target pointer.\n",
950        DPxPTR(HostPtr));
951     return OFFLOAD_FAIL;
952   }
953 
954   // get target table.
955   __tgt_target_table *TargetTable = nullptr;
956   {
957     std::lock_guard<std::mutex> TrlTblLock(*TrlTblMtx);
958     assert(TM->Table->TargetsTable.size() > (size_t)DeviceId &&
959            "Not expecting a device ID outside the table's bounds!");
960     TargetTable = TM->Table->TargetsTable[DeviceId];
961   }
962   assert(TargetTable && "Global data has not been mapped\n");
963 
964   __tgt_async_info AsyncInfo;
965 
966   std::vector<void *> TgtArgs;
967   std::vector<ptrdiff_t> TgtOffsets;
968   std::vector<void *> FPArrays;
969 
970   // Process data, such as data mapping, before launching the kernel
971   int Ret = processDataBefore(DeviceId, HostPtr, ArgNum, ArgBases, Args,
972                               ArgSizes, ArgTypes, ArgMappers, TgtArgs,
973                               TgtOffsets, FPArrays, &AsyncInfo);
974   if (Ret != OFFLOAD_SUCCESS) {
975     DP("Failed to process data before launching the kernel.\n");
976     return OFFLOAD_FAIL;
977   }
978 
979   // Get loop trip count
980   uint64_t LoopTripCount = getLoopTripCount(DeviceId);
981 
982   // Launch device execution.
983   void *TgtEntryPtr = TargetTable->EntriesBegin[TM->Index].addr;
984   DP("Launching target execution %s with pointer " DPxMOD " (index=%d).\n",
985      TargetTable->EntriesBegin[TM->Index].name, DPxPTR(TgtEntryPtr), TM->Index);
986 
987   if (IsTeamConstruct)
988     Ret = Device.runTeamRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
989                                TgtArgs.size(), TeamNum, ThreadLimit,
990                                LoopTripCount, &AsyncInfo);
991   else
992     Ret = Device.runRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
993                            TgtArgs.size(), &AsyncInfo);
994 
995   if (Ret != OFFLOAD_SUCCESS) {
996     DP("Executing target region abort target.\n");
997     return OFFLOAD_FAIL;
998   }
999 
1000   // Transfer data back and deallocate target memory for (first-)private
1001   // variables
1002   Ret = processDataAfter(DeviceId, HostPtr, ArgNum, ArgBases, Args, ArgSizes,
1003                          ArgTypes, ArgMappers, FPArrays, &AsyncInfo);
1004   if (Ret != OFFLOAD_SUCCESS) {
1005     DP("Failed to process data after launching the kernel.\n");
1006     return OFFLOAD_FAIL;
1007   }
1008 
1009   return Device.synchronize(&AsyncInfo);
1010 }
1011