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