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