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