1 //===--- amdgpu/src/rtl.cpp --------------------------------------- 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 // RTL for AMD hsa machine
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include <algorithm>
14 #include <assert.h>
15 #include <cstdio>
16 #include <cstdlib>
17 #include <cstring>
18 #include <functional>
19 #include <libelf.h>
20 #include <list>
21 #include <memory>
22 #include <mutex>
23 #include <shared_mutex>
24 #include <unordered_map>
25 #include <vector>
26 
27 #include "interop_hsa.h"
28 #include "impl_runtime.h"
29 
30 #include "internal.h"
31 #include "rt.h"
32 
33 #include "DeviceEnvironment.h"
34 #include "get_elf_mach_gfx_name.h"
35 #include "omptargetplugin.h"
36 #include "print_tracing.h"
37 
38 #include "llvm/Frontend/OpenMP/OMPConstants.h"
39 #include "llvm/Frontend/OpenMP/OMPGridValues.h"
40 
41 // hostrpc interface, FIXME: consider moving to its own include these are
42 // statically linked into amdgpu/plugin if present from hostrpc_services.a,
43 // linked as --whole-archive to override the weak symbols that are used to
44 // implement a fallback for toolchains that do not yet have a hostrpc library.
45 extern "C" {
46 uint64_t hostrpc_assign_buffer(hsa_agent_t agent, hsa_queue_t *this_Q,
47                                uint32_t device_id);
48 hsa_status_t hostrpc_init();
49 hsa_status_t hostrpc_terminate();
50 
51 __attribute__((weak)) hsa_status_t hostrpc_init() { return HSA_STATUS_SUCCESS; }
52 __attribute__((weak)) hsa_status_t hostrpc_terminate() {
53   return HSA_STATUS_SUCCESS;
54 }
55 __attribute__((weak)) uint64_t hostrpc_assign_buffer(hsa_agent_t, hsa_queue_t *,
56                                                      uint32_t device_id) {
57   DP("Warning: Attempting to assign hostrpc to device %u, but hostrpc library "
58      "missing\n",
59      device_id);
60   return 0;
61 }
62 }
63 
64 // Heuristic parameters used for kernel launch
65 // Number of teams per CU to allow scheduling flexibility
66 static const unsigned DefaultTeamsPerCU = 4;
67 
68 int print_kernel_trace;
69 
70 #ifdef OMPTARGET_DEBUG
71 #define check(msg, status)                                                     \
72   if (status != HSA_STATUS_SUCCESS) {                                          \
73     DP(#msg " failed\n");                                                      \
74   } else {                                                                     \
75     DP(#msg " succeeded\n");                                                   \
76   }
77 #else
78 #define check(msg, status)                                                     \
79   {}
80 #endif
81 
82 #include "elf_common.h"
83 
84 namespace hsa {
85 template <typename C> hsa_status_t iterate_agents(C cb) {
86   auto L = [](hsa_agent_t agent, void *data) -> hsa_status_t {
87     C *unwrapped = static_cast<C *>(data);
88     return (*unwrapped)(agent);
89   };
90   return hsa_iterate_agents(L, static_cast<void *>(&cb));
91 }
92 
93 template <typename C>
94 hsa_status_t amd_agent_iterate_memory_pools(hsa_agent_t Agent, C cb) {
95   auto L = [](hsa_amd_memory_pool_t MemoryPool, void *data) -> hsa_status_t {
96     C *unwrapped = static_cast<C *>(data);
97     return (*unwrapped)(MemoryPool);
98   };
99 
100   return hsa_amd_agent_iterate_memory_pools(Agent, L, static_cast<void *>(&cb));
101 }
102 
103 } // namespace hsa
104 
105 /// Keep entries table per device
106 struct FuncOrGblEntryTy {
107   __tgt_target_table Table;
108   std::vector<__tgt_offload_entry> Entries;
109 };
110 
111 struct KernelArgPool {
112 private:
113   static pthread_mutex_t mutex;
114 
115 public:
116   uint32_t kernarg_segment_size;
117   void *kernarg_region = nullptr;
118   std::queue<int> free_kernarg_segments;
119 
120   uint32_t kernarg_size_including_implicit() {
121     return kernarg_segment_size + sizeof(impl_implicit_args_t);
122   }
123 
124   ~KernelArgPool() {
125     if (kernarg_region) {
126       auto r = hsa_amd_memory_pool_free(kernarg_region);
127       if (r != HSA_STATUS_SUCCESS) {
128         DP("hsa_amd_memory_pool_free failed: %s\n", get_error_string(r));
129       }
130     }
131   }
132 
133   // Can't really copy or move a mutex
134   KernelArgPool() = default;
135   KernelArgPool(const KernelArgPool &) = delete;
136   KernelArgPool(KernelArgPool &&) = delete;
137 
138   KernelArgPool(uint32_t kernarg_segment_size,
139                 hsa_amd_memory_pool_t &memory_pool)
140       : kernarg_segment_size(kernarg_segment_size) {
141 
142     // impl uses one pool per kernel for all gpus, with a fixed upper size
143     // preserving that exact scheme here, including the queue<int>
144 
145     hsa_status_t err = hsa_amd_memory_pool_allocate(
146         memory_pool, kernarg_size_including_implicit() * MAX_NUM_KERNELS, 0,
147         &kernarg_region);
148 
149     if (err != HSA_STATUS_SUCCESS) {
150       DP("hsa_amd_memory_pool_allocate failed: %s\n", get_error_string(err));
151       kernarg_region = nullptr; // paranoid
152       return;
153     }
154 
155     err = core::allow_access_to_all_gpu_agents(kernarg_region);
156     if (err != HSA_STATUS_SUCCESS) {
157       DP("hsa allow_access_to_all_gpu_agents failed: %s\n",
158          get_error_string(err));
159       auto r = hsa_amd_memory_pool_free(kernarg_region);
160       if (r != HSA_STATUS_SUCCESS) {
161         // if free failed, can't do anything more to resolve it
162         DP("hsa memory poll free failed: %s\n", get_error_string(err));
163       }
164       kernarg_region = nullptr;
165       return;
166     }
167 
168     for (int i = 0; i < MAX_NUM_KERNELS; i++) {
169       free_kernarg_segments.push(i);
170     }
171   }
172 
173   void *allocate(uint64_t arg_num) {
174     assert((arg_num * sizeof(void *)) == kernarg_segment_size);
175     lock l(&mutex);
176     void *res = nullptr;
177     if (!free_kernarg_segments.empty()) {
178 
179       int free_idx = free_kernarg_segments.front();
180       res = static_cast<void *>(static_cast<char *>(kernarg_region) +
181                                 (free_idx * kernarg_size_including_implicit()));
182       assert(free_idx == pointer_to_index(res));
183       free_kernarg_segments.pop();
184     }
185     return res;
186   }
187 
188   void deallocate(void *ptr) {
189     lock l(&mutex);
190     int idx = pointer_to_index(ptr);
191     free_kernarg_segments.push(idx);
192   }
193 
194 private:
195   int pointer_to_index(void *ptr) {
196     ptrdiff_t bytes =
197         static_cast<char *>(ptr) - static_cast<char *>(kernarg_region);
198     assert(bytes >= 0);
199     assert(bytes % kernarg_size_including_implicit() == 0);
200     return bytes / kernarg_size_including_implicit();
201   }
202   struct lock {
203     lock(pthread_mutex_t *m) : m(m) { pthread_mutex_lock(m); }
204     ~lock() { pthread_mutex_unlock(m); }
205     pthread_mutex_t *m;
206   };
207 };
208 pthread_mutex_t KernelArgPool::mutex = PTHREAD_MUTEX_INITIALIZER;
209 
210 std::unordered_map<std::string /*kernel*/, std::unique_ptr<KernelArgPool>>
211     KernelArgPoolMap;
212 
213 /// Use a single entity to encode a kernel and a set of flags
214 struct KernelTy {
215   llvm::omp::OMPTgtExecModeFlags ExecutionMode;
216   int16_t ConstWGSize;
217   int32_t device_id;
218   void *CallStackAddr = nullptr;
219   const char *Name;
220 
221   KernelTy(llvm::omp::OMPTgtExecModeFlags _ExecutionMode, int16_t _ConstWGSize,
222            int32_t _device_id, void *_CallStackAddr, const char *_Name,
223            uint32_t _kernarg_segment_size,
224            hsa_amd_memory_pool_t &KernArgMemoryPool)
225       : ExecutionMode(_ExecutionMode), ConstWGSize(_ConstWGSize),
226         device_id(_device_id), CallStackAddr(_CallStackAddr), Name(_Name) {
227     DP("Construct kernelinfo: ExecMode %d\n", ExecutionMode);
228 
229     std::string N(_Name);
230     if (KernelArgPoolMap.find(N) == KernelArgPoolMap.end()) {
231       KernelArgPoolMap.insert(
232           std::make_pair(N, std::unique_ptr<KernelArgPool>(new KernelArgPool(
233                                 _kernarg_segment_size, KernArgMemoryPool))));
234     }
235   }
236 };
237 
238 /// List that contains all the kernels.
239 /// FIXME: we may need this to be per device and per library.
240 std::list<KernelTy> KernelsList;
241 
242 template <typename Callback> static hsa_status_t FindAgents(Callback CB) {
243 
244   hsa_status_t err =
245       hsa::iterate_agents([&](hsa_agent_t agent) -> hsa_status_t {
246         hsa_device_type_t device_type;
247         // get_info fails iff HSA runtime not yet initialized
248         hsa_status_t err =
249             hsa_agent_get_info(agent, HSA_AGENT_INFO_DEVICE, &device_type);
250 
251         if (err != HSA_STATUS_SUCCESS) {
252           if (print_kernel_trace > 0)
253             DP("rtl.cpp: err %s\n", get_error_string(err));
254 
255           return err;
256         }
257 
258         CB(device_type, agent);
259         return HSA_STATUS_SUCCESS;
260       });
261 
262   // iterate_agents fails iff HSA runtime not yet initialized
263   if (print_kernel_trace > 0 && err != HSA_STATUS_SUCCESS) {
264     DP("rtl.cpp: err %s\n", get_error_string(err));
265   }
266 
267   return err;
268 }
269 
270 static void callbackQueue(hsa_status_t status, hsa_queue_t *source,
271                           void *data) {
272   if (status != HSA_STATUS_SUCCESS) {
273     const char *status_string;
274     if (hsa_status_string(status, &status_string) != HSA_STATUS_SUCCESS) {
275       status_string = "unavailable";
276     }
277     DP("[%s:%d] GPU error in queue %p %d (%s)\n", __FILE__, __LINE__, source,
278        status, status_string);
279     abort();
280   }
281 }
282 
283 namespace core {
284 namespace {
285 void packet_store_release(uint32_t *packet, uint16_t header, uint16_t rest) {
286   __atomic_store_n(packet, header | (rest << 16), __ATOMIC_RELEASE);
287 }
288 
289 uint16_t create_header() {
290   uint16_t header = HSA_PACKET_TYPE_KERNEL_DISPATCH << HSA_PACKET_HEADER_TYPE;
291   header |= HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_ACQUIRE_FENCE_SCOPE;
292   header |= HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_RELEASE_FENCE_SCOPE;
293   return header;
294 }
295 
296 hsa_status_t isValidMemoryPool(hsa_amd_memory_pool_t MemoryPool) {
297   bool AllocAllowed = false;
298   hsa_status_t Err = hsa_amd_memory_pool_get_info(
299       MemoryPool, HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED,
300       &AllocAllowed);
301   if (Err != HSA_STATUS_SUCCESS) {
302     DP("Alloc allowed in memory pool check failed: %s\n",
303        get_error_string(Err));
304     return Err;
305   }
306 
307   size_t Size = 0;
308   Err = hsa_amd_memory_pool_get_info(MemoryPool, HSA_AMD_MEMORY_POOL_INFO_SIZE,
309                                      &Size);
310   if (Err != HSA_STATUS_SUCCESS) {
311     DP("Get memory pool size failed: %s\n", get_error_string(Err));
312     return Err;
313   }
314 
315   return (AllocAllowed && Size > 0) ? HSA_STATUS_SUCCESS : HSA_STATUS_ERROR;
316 }
317 
318 hsa_status_t addMemoryPool(hsa_amd_memory_pool_t MemoryPool, void *Data) {
319   std::vector<hsa_amd_memory_pool_t> *Result =
320       static_cast<std::vector<hsa_amd_memory_pool_t> *>(Data);
321 
322   hsa_status_t err;
323   if ((err = isValidMemoryPool(MemoryPool)) != HSA_STATUS_SUCCESS) {
324     return err;
325   }
326 
327   Result->push_back(MemoryPool);
328   return HSA_STATUS_SUCCESS;
329 }
330 
331 } // namespace
332 } // namespace core
333 
334 struct EnvironmentVariables {
335   int NumTeams;
336   int TeamLimit;
337   int TeamThreadLimit;
338   int MaxTeamsDefault;
339 };
340 
341 template <uint32_t wavesize>
342 static constexpr const llvm::omp::GV &getGridValue() {
343   return llvm::omp::getAMDGPUGridValues<wavesize>();
344 }
345 
346 struct HSALifetime {
347   // Wrapper around HSA used to ensure it is constructed before other types
348   // and destructed after, which means said other types can use raii for
349   // cleanup without risking running outside of the lifetime of HSA
350   const hsa_status_t S;
351 
352   bool HSAInitSuccess() { return S == HSA_STATUS_SUCCESS; }
353   HSALifetime() : S(hsa_init()) {}
354 
355   ~HSALifetime() {
356     if (S == HSA_STATUS_SUCCESS) {
357       hsa_status_t Err = hsa_shut_down();
358       if (Err != HSA_STATUS_SUCCESS) {
359         // Can't call into HSA to get a string from the integer
360         DP("Shutting down HSA failed: %d\n", Err);
361       }
362     }
363   }
364 };
365 
366 // Handle scheduling of multiple hsa_queue's per device to
367 // multiple threads (one scheduler per device)
368 class HSAQueueScheduler {
369 public:
370   HSAQueueScheduler() : current(0) {}
371 
372   HSAQueueScheduler(const HSAQueueScheduler &) = delete;
373 
374   HSAQueueScheduler(HSAQueueScheduler &&q) {
375     current = q.current.load();
376     for (uint8_t i = 0; i < NUM_QUEUES_PER_DEVICE; i++) {
377       HSAQueues[i] = q.HSAQueues[i];
378       q.HSAQueues[i] = nullptr;
379     }
380   }
381 
382   // \return false if any HSA queue creation fails
383   bool CreateQueues(hsa_agent_t HSAAgent, uint32_t queue_size) {
384     for (uint8_t i = 0; i < NUM_QUEUES_PER_DEVICE; i++) {
385       hsa_queue_t *Q = nullptr;
386       hsa_status_t rc =
387           hsa_queue_create(HSAAgent, queue_size, HSA_QUEUE_TYPE_MULTI,
388                            callbackQueue, NULL, UINT32_MAX, UINT32_MAX, &Q);
389       if (rc != HSA_STATUS_SUCCESS) {
390         DP("Failed to create HSA queue %d\n", i);
391         return false;
392       }
393       HSAQueues[i] = Q;
394     }
395     return true;
396   }
397 
398   ~HSAQueueScheduler() {
399     for (uint8_t i = 0; i < NUM_QUEUES_PER_DEVICE; i++) {
400       if (HSAQueues[i]) {
401         hsa_status_t err = hsa_queue_destroy(HSAQueues[i]);
402         if (err != HSA_STATUS_SUCCESS)
403           DP("Error destroying HSA queue");
404       }
405     }
406   }
407 
408   // \return next queue to use for device
409   hsa_queue_t *Next() {
410     return HSAQueues[(current.fetch_add(1, std::memory_order_relaxed)) %
411                      NUM_QUEUES_PER_DEVICE];
412   }
413 
414 private:
415   // Number of queues per device
416   enum : uint8_t { NUM_QUEUES_PER_DEVICE = 4 };
417   hsa_queue_t *HSAQueues[NUM_QUEUES_PER_DEVICE] = {};
418   std::atomic<uint8_t> current;
419 };
420 
421 /// Class containing all the device information
422 class RTLDeviceInfoTy : HSALifetime {
423   std::vector<std::list<FuncOrGblEntryTy>> FuncGblEntries;
424 
425   struct QueueDeleter {
426     void operator()(hsa_queue_t *Q) {
427       if (Q) {
428         hsa_status_t Err = hsa_queue_destroy(Q);
429         if (Err != HSA_STATUS_SUCCESS) {
430           DP("Error destroying hsa queue: %s\n", get_error_string(Err));
431         }
432       }
433     }
434   };
435 
436 public:
437   bool ConstructionSucceeded = false;
438 
439   // load binary populates symbol tables and mutates various global state
440   // run uses those symbol tables
441   std::shared_timed_mutex load_run_lock;
442 
443   int NumberOfDevices = 0;
444 
445   // GPU devices
446   std::vector<hsa_agent_t> HSAAgents;
447   std::vector<HSAQueueScheduler> HSAQueueSchedulers; // one per gpu
448 
449   // CPUs
450   std::vector<hsa_agent_t> CPUAgents;
451 
452   // Device properties
453   std::vector<int> ComputeUnits;
454   std::vector<int> GroupsPerDevice;
455   std::vector<int> ThreadsPerGroup;
456   std::vector<int> WarpSize;
457   std::vector<std::string> GPUName;
458 
459   // OpenMP properties
460   std::vector<int> NumTeams;
461   std::vector<int> NumThreads;
462 
463   // OpenMP Environment properties
464   EnvironmentVariables Env;
465 
466   // OpenMP Requires Flags
467   int64_t RequiresFlags;
468 
469   // Resource pools
470   SignalPoolT FreeSignalPool;
471 
472   bool hostcall_required = false;
473 
474   std::vector<hsa_executable_t> HSAExecutables;
475 
476   std::vector<std::map<std::string, atl_kernel_info_t>> KernelInfoTable;
477   std::vector<std::map<std::string, atl_symbol_info_t>> SymbolInfoTable;
478 
479   hsa_amd_memory_pool_t KernArgPool;
480 
481   // fine grained memory pool for host allocations
482   hsa_amd_memory_pool_t HostFineGrainedMemoryPool;
483 
484   // fine and coarse-grained memory pools per offloading device
485   std::vector<hsa_amd_memory_pool_t> DeviceFineGrainedMemoryPools;
486   std::vector<hsa_amd_memory_pool_t> DeviceCoarseGrainedMemoryPools;
487 
488   struct implFreePtrDeletor {
489     void operator()(void *p) {
490       core::Runtime::Memfree(p); // ignore failure to free
491     }
492   };
493 
494   // device_State shared across loaded binaries, error if inconsistent size
495   std::vector<std::pair<std::unique_ptr<void, implFreePtrDeletor>, uint64_t>>
496       deviceStateStore;
497 
498   static const unsigned HardTeamLimit =
499       (1 << 16) - 1; // 64K needed to fit in uint16
500   static const int DefaultNumTeams = 128;
501 
502   // These need to be per-device since different devices can have different
503   // wave sizes, but are currently the same number for each so that refactor
504   // can be postponed.
505   static_assert(getGridValue<32>().GV_Max_Teams ==
506                     getGridValue<64>().GV_Max_Teams,
507                 "");
508   static const int Max_Teams = getGridValue<64>().GV_Max_Teams;
509 
510   static_assert(getGridValue<32>().GV_Max_WG_Size ==
511                     getGridValue<64>().GV_Max_WG_Size,
512                 "");
513   static const int Max_WG_Size = getGridValue<64>().GV_Max_WG_Size;
514 
515   static_assert(getGridValue<32>().GV_Default_WG_Size ==
516                     getGridValue<64>().GV_Default_WG_Size,
517                 "");
518   static const int Default_WG_Size = getGridValue<64>().GV_Default_WG_Size;
519 
520   using MemcpyFunc = hsa_status_t (*)(hsa_signal_t, void *, void *, size_t size,
521                                       hsa_agent_t, hsa_amd_memory_pool_t);
522   hsa_status_t freesignalpool_memcpy(void *dest, void *src, size_t size,
523                                      MemcpyFunc Func, int32_t deviceId) {
524     hsa_agent_t agent = HSAAgents[deviceId];
525     hsa_signal_t s = FreeSignalPool.pop();
526     if (s.handle == 0) {
527       return HSA_STATUS_ERROR;
528     }
529     hsa_status_t r = Func(s, dest, src, size, agent, HostFineGrainedMemoryPool);
530     FreeSignalPool.push(s);
531     return r;
532   }
533 
534   hsa_status_t freesignalpool_memcpy_d2h(void *dest, void *src, size_t size,
535                                          int32_t deviceId) {
536     return freesignalpool_memcpy(dest, src, size, impl_memcpy_d2h, deviceId);
537   }
538 
539   hsa_status_t freesignalpool_memcpy_h2d(void *dest, void *src, size_t size,
540                                          int32_t deviceId) {
541     return freesignalpool_memcpy(dest, src, size, impl_memcpy_h2d, deviceId);
542   }
543 
544   // Record entry point associated with device
545   void addOffloadEntry(int32_t device_id, __tgt_offload_entry entry) {
546     assert(device_id < (int32_t)FuncGblEntries.size() &&
547            "Unexpected device id!");
548     FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
549 
550     E.Entries.push_back(entry);
551   }
552 
553   // Return true if the entry is associated with device
554   bool findOffloadEntry(int32_t device_id, void *addr) {
555     assert(device_id < (int32_t)FuncGblEntries.size() &&
556            "Unexpected device id!");
557     FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
558 
559     for (auto &it : E.Entries) {
560       if (it.addr == addr)
561         return true;
562     }
563 
564     return false;
565   }
566 
567   // Return the pointer to the target entries table
568   __tgt_target_table *getOffloadEntriesTable(int32_t device_id) {
569     assert(device_id < (int32_t)FuncGblEntries.size() &&
570            "Unexpected device id!");
571     FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
572 
573     int32_t size = E.Entries.size();
574 
575     // Table is empty
576     if (!size)
577       return 0;
578 
579     __tgt_offload_entry *begin = &E.Entries[0];
580     __tgt_offload_entry *end = &E.Entries[size - 1];
581 
582     // Update table info according to the entries and return the pointer
583     E.Table.EntriesBegin = begin;
584     E.Table.EntriesEnd = ++end;
585 
586     return &E.Table;
587   }
588 
589   // Clear entries table for a device
590   void clearOffloadEntriesTable(int device_id) {
591     assert(device_id < (int32_t)FuncGblEntries.size() &&
592            "Unexpected device id!");
593     FuncGblEntries[device_id].emplace_back();
594     FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
595     // KernelArgPoolMap.clear();
596     E.Entries.clear();
597     E.Table.EntriesBegin = E.Table.EntriesEnd = 0;
598   }
599 
600   hsa_status_t addDeviceMemoryPool(hsa_amd_memory_pool_t MemoryPool,
601                                    int DeviceId) {
602     assert(DeviceId < DeviceFineGrainedMemoryPools.size() && "Error here.");
603     uint32_t GlobalFlags = 0;
604     hsa_status_t Err = hsa_amd_memory_pool_get_info(
605         MemoryPool, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &GlobalFlags);
606 
607     if (Err != HSA_STATUS_SUCCESS) {
608       return Err;
609     }
610 
611     if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED) {
612       DeviceFineGrainedMemoryPools[DeviceId] = MemoryPool;
613     } else if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_COARSE_GRAINED) {
614       DeviceCoarseGrainedMemoryPools[DeviceId] = MemoryPool;
615     }
616 
617     return HSA_STATUS_SUCCESS;
618   }
619 
620   hsa_status_t setupDevicePools(const std::vector<hsa_agent_t> &Agents) {
621     for (int DeviceId = 0; DeviceId < Agents.size(); DeviceId++) {
622       hsa_status_t Err = hsa::amd_agent_iterate_memory_pools(
623           Agents[DeviceId], [&](hsa_amd_memory_pool_t MemoryPool) {
624             hsa_status_t ValidStatus = core::isValidMemoryPool(MemoryPool);
625             if (ValidStatus != HSA_STATUS_SUCCESS) {
626               DP("Alloc allowed in memory pool check failed: %s\n",
627                  get_error_string(ValidStatus));
628               return HSA_STATUS_SUCCESS;
629             }
630             return addDeviceMemoryPool(MemoryPool, DeviceId);
631           });
632 
633       if (Err != HSA_STATUS_SUCCESS) {
634         DP("[%s:%d] %s failed: %s\n", __FILE__, __LINE__,
635            "Iterate all memory pools", get_error_string(Err));
636         return Err;
637       }
638     }
639     return HSA_STATUS_SUCCESS;
640   }
641 
642   hsa_status_t setupHostMemoryPools(std::vector<hsa_agent_t> &Agents) {
643     std::vector<hsa_amd_memory_pool_t> HostPools;
644 
645     // collect all the "valid" pools for all the given agents.
646     for (const auto &Agent : Agents) {
647       hsa_status_t Err = hsa_amd_agent_iterate_memory_pools(
648           Agent, core::addMemoryPool, static_cast<void *>(&HostPools));
649       if (Err != HSA_STATUS_SUCCESS) {
650         DP("addMemoryPool returned %s, continuing\n", get_error_string(Err));
651       }
652     }
653 
654     // We need two fine-grained pools.
655     //  1. One with kernarg flag set for storing kernel arguments
656     //  2. Second for host allocations
657     bool FineGrainedMemoryPoolSet = false;
658     bool KernArgPoolSet = false;
659     for (const auto &MemoryPool : HostPools) {
660       hsa_status_t Err = HSA_STATUS_SUCCESS;
661       uint32_t GlobalFlags = 0;
662       Err = hsa_amd_memory_pool_get_info(
663           MemoryPool, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &GlobalFlags);
664       if (Err != HSA_STATUS_SUCCESS) {
665         DP("Get memory pool info failed: %s\n", get_error_string(Err));
666         return Err;
667       }
668 
669       if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED) {
670         if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_KERNARG_INIT) {
671           KernArgPool = MemoryPool;
672           KernArgPoolSet = true;
673         }
674         HostFineGrainedMemoryPool = MemoryPool;
675         FineGrainedMemoryPoolSet = true;
676       }
677     }
678 
679     if (FineGrainedMemoryPoolSet && KernArgPoolSet)
680       return HSA_STATUS_SUCCESS;
681 
682     return HSA_STATUS_ERROR;
683   }
684 
685   hsa_amd_memory_pool_t getDeviceMemoryPool(int DeviceId) {
686     assert(DeviceId >= 0 && DeviceId < DeviceCoarseGrainedMemoryPools.size() &&
687            "Invalid device Id");
688     return DeviceCoarseGrainedMemoryPools[DeviceId];
689   }
690 
691   hsa_amd_memory_pool_t getHostMemoryPool() {
692     return HostFineGrainedMemoryPool;
693   }
694 
695   static int readEnvElseMinusOne(const char *Env) {
696     const char *envStr = getenv(Env);
697     int res = -1;
698     if (envStr) {
699       res = std::stoi(envStr);
700       DP("Parsed %s=%d\n", Env, res);
701     }
702     return res;
703   }
704 
705   RTLDeviceInfoTy() {
706     DP("Start initializing " GETNAME(TARGET_NAME) "\n");
707 
708     // LIBOMPTARGET_KERNEL_TRACE provides a kernel launch trace to stderr
709     // anytime. You do not need a debug library build.
710     //  0 => no tracing
711     //  1 => tracing dispatch only
712     // >1 => verbosity increase
713 
714     if (!HSAInitSuccess()) {
715       DP("Error when initializing HSA in " GETNAME(TARGET_NAME) "\n");
716       return;
717     }
718 
719     if (char *envStr = getenv("LIBOMPTARGET_KERNEL_TRACE"))
720       print_kernel_trace = atoi(envStr);
721     else
722       print_kernel_trace = 0;
723 
724     hsa_status_t err = core::atl_init_gpu_context();
725     if (err != HSA_STATUS_SUCCESS) {
726       DP("Error when initializing " GETNAME(TARGET_NAME) "\n");
727       return;
728     }
729 
730     // Init hostcall soon after initializing hsa
731     hostrpc_init();
732 
733     err = FindAgents([&](hsa_device_type_t DeviceType, hsa_agent_t Agent) {
734       if (DeviceType == HSA_DEVICE_TYPE_CPU) {
735         CPUAgents.push_back(Agent);
736       } else {
737         HSAAgents.push_back(Agent);
738       }
739     });
740     if (err != HSA_STATUS_SUCCESS)
741       return;
742 
743     NumberOfDevices = (int)HSAAgents.size();
744 
745     if (NumberOfDevices == 0) {
746       DP("There are no devices supporting HSA.\n");
747       return;
748     } else {
749       DP("There are %d devices supporting HSA.\n", NumberOfDevices);
750     }
751 
752     // Init the device info
753     HSAQueueSchedulers.reserve(NumberOfDevices);
754     FuncGblEntries.resize(NumberOfDevices);
755     ThreadsPerGroup.resize(NumberOfDevices);
756     ComputeUnits.resize(NumberOfDevices);
757     GPUName.resize(NumberOfDevices);
758     GroupsPerDevice.resize(NumberOfDevices);
759     WarpSize.resize(NumberOfDevices);
760     NumTeams.resize(NumberOfDevices);
761     NumThreads.resize(NumberOfDevices);
762     deviceStateStore.resize(NumberOfDevices);
763     KernelInfoTable.resize(NumberOfDevices);
764     SymbolInfoTable.resize(NumberOfDevices);
765     DeviceCoarseGrainedMemoryPools.resize(NumberOfDevices);
766     DeviceFineGrainedMemoryPools.resize(NumberOfDevices);
767 
768     err = setupDevicePools(HSAAgents);
769     if (err != HSA_STATUS_SUCCESS) {
770       DP("Setup for Device Memory Pools failed\n");
771       return;
772     }
773 
774     err = setupHostMemoryPools(CPUAgents);
775     if (err != HSA_STATUS_SUCCESS) {
776       DP("Setup for Host Memory Pools failed\n");
777       return;
778     }
779 
780     for (int i = 0; i < NumberOfDevices; i++) {
781       uint32_t queue_size = 0;
782       {
783         hsa_status_t err = hsa_agent_get_info(
784             HSAAgents[i], HSA_AGENT_INFO_QUEUE_MAX_SIZE, &queue_size);
785         if (err != HSA_STATUS_SUCCESS) {
786           DP("HSA query QUEUE_MAX_SIZE failed for agent %d\n", i);
787           return;
788         }
789         enum { MaxQueueSize = 4096 };
790         if (queue_size > MaxQueueSize) {
791           queue_size = MaxQueueSize;
792         }
793       }
794 
795       {
796         HSAQueueScheduler QSched;
797         if (!QSched.CreateQueues(HSAAgents[i], queue_size))
798           return;
799         HSAQueueSchedulers.emplace_back(std::move(QSched));
800       }
801 
802       deviceStateStore[i] = {nullptr, 0};
803     }
804 
805     for (int i = 0; i < NumberOfDevices; i++) {
806       ThreadsPerGroup[i] = RTLDeviceInfoTy::Default_WG_Size;
807       GroupsPerDevice[i] = RTLDeviceInfoTy::DefaultNumTeams;
808       ComputeUnits[i] = 1;
809       DP("Device %d: Initial groupsPerDevice %d & threadsPerGroup %d\n", i,
810          GroupsPerDevice[i], ThreadsPerGroup[i]);
811     }
812 
813     // Get environment variables regarding teams
814     Env.TeamLimit = readEnvElseMinusOne("OMP_TEAM_LIMIT");
815     Env.NumTeams = readEnvElseMinusOne("OMP_NUM_TEAMS");
816     Env.MaxTeamsDefault = readEnvElseMinusOne("OMP_MAX_TEAMS_DEFAULT");
817     Env.TeamThreadLimit = readEnvElseMinusOne("OMP_TEAMS_THREAD_LIMIT");
818 
819     // Default state.
820     RequiresFlags = OMP_REQ_UNDEFINED;
821 
822     ConstructionSucceeded = true;
823   }
824 
825   ~RTLDeviceInfoTy() {
826     DP("Finalizing the " GETNAME(TARGET_NAME) " DeviceInfo.\n");
827     if (!HSAInitSuccess()) {
828       // Then none of these can have been set up and they can't be torn down
829       return;
830     }
831     // Run destructors on types that use HSA before
832     // impl_finalize removes access to it
833     deviceStateStore.clear();
834     KernelArgPoolMap.clear();
835     // Terminate hostrpc before finalizing hsa
836     hostrpc_terminate();
837 
838     hsa_status_t Err;
839     for (uint32_t I = 0; I < HSAExecutables.size(); I++) {
840       Err = hsa_executable_destroy(HSAExecutables[I]);
841       if (Err != HSA_STATUS_SUCCESS) {
842         DP("[%s:%d] %s failed: %s\n", __FILE__, __LINE__,
843            "Destroying executable", get_error_string(Err));
844       }
845     }
846   }
847 };
848 
849 pthread_mutex_t SignalPoolT::mutex = PTHREAD_MUTEX_INITIALIZER;
850 
851 static RTLDeviceInfoTy DeviceInfo;
852 
853 namespace {
854 
855 int32_t dataRetrieve(int32_t DeviceId, void *HstPtr, void *TgtPtr, int64_t Size,
856                      __tgt_async_info *AsyncInfo) {
857   assert(AsyncInfo && "AsyncInfo is nullptr");
858   assert(DeviceId < DeviceInfo.NumberOfDevices && "Device ID too large");
859   // Return success if we are not copying back to host from target.
860   if (!HstPtr)
861     return OFFLOAD_SUCCESS;
862   hsa_status_t err;
863   DP("Retrieve data %ld bytes, (tgt:%016llx) -> (hst:%016llx).\n", Size,
864      (long long unsigned)(Elf64_Addr)TgtPtr,
865      (long long unsigned)(Elf64_Addr)HstPtr);
866 
867   err = DeviceInfo.freesignalpool_memcpy_d2h(HstPtr, TgtPtr, (size_t)Size,
868                                              DeviceId);
869 
870   if (err != HSA_STATUS_SUCCESS) {
871     DP("Error when copying data from device to host. Pointers: "
872        "host = 0x%016lx, device = 0x%016lx, size = %lld\n",
873        (Elf64_Addr)HstPtr, (Elf64_Addr)TgtPtr, (unsigned long long)Size);
874     return OFFLOAD_FAIL;
875   }
876   DP("DONE Retrieve data %ld bytes, (tgt:%016llx) -> (hst:%016llx).\n", Size,
877      (long long unsigned)(Elf64_Addr)TgtPtr,
878      (long long unsigned)(Elf64_Addr)HstPtr);
879   return OFFLOAD_SUCCESS;
880 }
881 
882 int32_t dataSubmit(int32_t DeviceId, void *TgtPtr, void *HstPtr, int64_t Size,
883                    __tgt_async_info *AsyncInfo) {
884   assert(AsyncInfo && "AsyncInfo is nullptr");
885   hsa_status_t err;
886   assert(DeviceId < DeviceInfo.NumberOfDevices && "Device ID too large");
887   // Return success if we are not doing host to target.
888   if (!HstPtr)
889     return OFFLOAD_SUCCESS;
890 
891   DP("Submit data %ld bytes, (hst:%016llx) -> (tgt:%016llx).\n", Size,
892      (long long unsigned)(Elf64_Addr)HstPtr,
893      (long long unsigned)(Elf64_Addr)TgtPtr);
894   err = DeviceInfo.freesignalpool_memcpy_h2d(TgtPtr, HstPtr, (size_t)Size,
895                                              DeviceId);
896   if (err != HSA_STATUS_SUCCESS) {
897     DP("Error when copying data from host to device. Pointers: "
898        "host = 0x%016lx, device = 0x%016lx, size = %lld\n",
899        (Elf64_Addr)HstPtr, (Elf64_Addr)TgtPtr, (unsigned long long)Size);
900     return OFFLOAD_FAIL;
901   }
902   return OFFLOAD_SUCCESS;
903 }
904 
905 // Async.
906 // The implementation was written with cuda streams in mind. The semantics of
907 // that are to execute kernels on a queue in order of insertion. A synchronise
908 // call then makes writes visible between host and device. This means a series
909 // of N data_submit_async calls are expected to execute serially. HSA offers
910 // various options to run the data copies concurrently. This may require changes
911 // to libomptarget.
912 
913 // __tgt_async_info* contains a void * Queue. Queue = 0 is used to indicate that
914 // there are no outstanding kernels that need to be synchronized. Any async call
915 // may be passed a Queue==0, at which point the cuda implementation will set it
916 // to non-null (see getStream). The cuda streams are per-device. Upstream may
917 // change this interface to explicitly initialize the AsyncInfo_pointer, but
918 // until then hsa lazily initializes it as well.
919 
920 void initAsyncInfo(__tgt_async_info *AsyncInfo) {
921   // set non-null while using async calls, return to null to indicate completion
922   assert(AsyncInfo);
923   if (!AsyncInfo->Queue) {
924     AsyncInfo->Queue = reinterpret_cast<void *>(UINT64_MAX);
925   }
926 }
927 void finiAsyncInfo(__tgt_async_info *AsyncInfo) {
928   assert(AsyncInfo);
929   assert(AsyncInfo->Queue);
930   AsyncInfo->Queue = 0;
931 }
932 
933 // Determine launch values for kernel.
934 struct launchVals {
935   int WorkgroupSize;
936   int GridSize;
937 };
938 launchVals getLaunchVals(int WarpSize, EnvironmentVariables Env,
939                          int ConstWGSize,
940                          llvm::omp::OMPTgtExecModeFlags ExecutionMode,
941                          int num_teams, int thread_limit,
942                          uint64_t loop_tripcount, int DeviceNumTeams) {
943 
944   int threadsPerGroup = RTLDeviceInfoTy::Default_WG_Size;
945   int num_groups = 0;
946 
947   int Max_Teams =
948       Env.MaxTeamsDefault > 0 ? Env.MaxTeamsDefault : DeviceNumTeams;
949   if (Max_Teams > RTLDeviceInfoTy::HardTeamLimit)
950     Max_Teams = RTLDeviceInfoTy::HardTeamLimit;
951 
952   if (print_kernel_trace & STARTUP_DETAILS) {
953     DP("RTLDeviceInfoTy::Max_Teams: %d\n", RTLDeviceInfoTy::Max_Teams);
954     DP("Max_Teams: %d\n", Max_Teams);
955     DP("RTLDeviceInfoTy::Warp_Size: %d\n", WarpSize);
956     DP("RTLDeviceInfoTy::Max_WG_Size: %d\n", RTLDeviceInfoTy::Max_WG_Size);
957     DP("RTLDeviceInfoTy::Default_WG_Size: %d\n",
958        RTLDeviceInfoTy::Default_WG_Size);
959     DP("thread_limit: %d\n", thread_limit);
960     DP("threadsPerGroup: %d\n", threadsPerGroup);
961     DP("ConstWGSize: %d\n", ConstWGSize);
962   }
963   // check for thread_limit() clause
964   if (thread_limit > 0) {
965     threadsPerGroup = thread_limit;
966     DP("Setting threads per block to requested %d\n", thread_limit);
967     // Add master warp for GENERIC
968     if (ExecutionMode ==
969         llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC) {
970       threadsPerGroup += WarpSize;
971       DP("Adding master wavefront: +%d threads\n", WarpSize);
972     }
973     if (threadsPerGroup > RTLDeviceInfoTy::Max_WG_Size) { // limit to max
974       threadsPerGroup = RTLDeviceInfoTy::Max_WG_Size;
975       DP("Setting threads per block to maximum %d\n", threadsPerGroup);
976     }
977   }
978   // check flat_max_work_group_size attr here
979   if (threadsPerGroup > ConstWGSize) {
980     threadsPerGroup = ConstWGSize;
981     DP("Reduced threadsPerGroup to flat-attr-group-size limit %d\n",
982        threadsPerGroup);
983   }
984   if (print_kernel_trace & STARTUP_DETAILS)
985     DP("threadsPerGroup: %d\n", threadsPerGroup);
986   DP("Preparing %d threads\n", threadsPerGroup);
987 
988   // Set default num_groups (teams)
989   if (Env.TeamLimit > 0)
990     num_groups = (Max_Teams < Env.TeamLimit) ? Max_Teams : Env.TeamLimit;
991   else
992     num_groups = Max_Teams;
993   DP("Set default num of groups %d\n", num_groups);
994 
995   if (print_kernel_trace & STARTUP_DETAILS) {
996     DP("num_groups: %d\n", num_groups);
997     DP("num_teams: %d\n", num_teams);
998   }
999 
1000   // Reduce num_groups if threadsPerGroup exceeds RTLDeviceInfoTy::Max_WG_Size
1001   // This reduction is typical for default case (no thread_limit clause).
1002   // or when user goes crazy with num_teams clause.
1003   // FIXME: We cant distinguish between a constant or variable thread limit.
1004   // So we only handle constant thread_limits.
1005   if (threadsPerGroup >
1006       RTLDeviceInfoTy::Default_WG_Size) //  256 < threadsPerGroup <= 1024
1007     // Should we round threadsPerGroup up to nearest WarpSize
1008     // here?
1009     num_groups = (Max_Teams * RTLDeviceInfoTy::Max_WG_Size) / threadsPerGroup;
1010 
1011   // check for num_teams() clause
1012   if (num_teams > 0) {
1013     num_groups = (num_teams < num_groups) ? num_teams : num_groups;
1014   }
1015   if (print_kernel_trace & STARTUP_DETAILS) {
1016     DP("num_groups: %d\n", num_groups);
1017     DP("Env.NumTeams %d\n", Env.NumTeams);
1018     DP("Env.TeamLimit %d\n", Env.TeamLimit);
1019   }
1020 
1021   if (Env.NumTeams > 0) {
1022     num_groups = (Env.NumTeams < num_groups) ? Env.NumTeams : num_groups;
1023     DP("Modifying teams based on Env.NumTeams %d\n", Env.NumTeams);
1024   } else if (Env.TeamLimit > 0) {
1025     num_groups = (Env.TeamLimit < num_groups) ? Env.TeamLimit : num_groups;
1026     DP("Modifying teams based on Env.TeamLimit%d\n", Env.TeamLimit);
1027   } else {
1028     if (num_teams <= 0) {
1029       if (loop_tripcount > 0) {
1030         if (ExecutionMode ==
1031             llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_SPMD) {
1032           // round up to the nearest integer
1033           num_groups = ((loop_tripcount - 1) / threadsPerGroup) + 1;
1034         } else if (ExecutionMode ==
1035                    llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC) {
1036           num_groups = loop_tripcount;
1037         } else /* OMP_TGT_EXEC_MODE_GENERIC_SPMD */ {
1038           // This is a generic kernel that was transformed to use SPMD-mode
1039           // execution but uses Generic-mode semantics for scheduling.
1040           num_groups = loop_tripcount;
1041         }
1042         DP("Using %d teams due to loop trip count %" PRIu64 " and number of "
1043            "threads per block %d\n",
1044            num_groups, loop_tripcount, threadsPerGroup);
1045       }
1046     } else {
1047       num_groups = num_teams;
1048     }
1049     if (num_groups > Max_Teams) {
1050       num_groups = Max_Teams;
1051       if (print_kernel_trace & STARTUP_DETAILS)
1052         DP("Limiting num_groups %d to Max_Teams %d \n", num_groups, Max_Teams);
1053     }
1054     if (num_groups > num_teams && num_teams > 0) {
1055       num_groups = num_teams;
1056       if (print_kernel_trace & STARTUP_DETAILS)
1057         DP("Limiting num_groups %d to clause num_teams %d \n", num_groups,
1058            num_teams);
1059     }
1060   }
1061 
1062   // num_teams clause always honored, no matter what, unless DEFAULT is active.
1063   if (num_teams > 0) {
1064     num_groups = num_teams;
1065     // Cap num_groups to EnvMaxTeamsDefault if set.
1066     if (Env.MaxTeamsDefault > 0 && num_groups > Env.MaxTeamsDefault)
1067       num_groups = Env.MaxTeamsDefault;
1068   }
1069   if (print_kernel_trace & STARTUP_DETAILS) {
1070     DP("threadsPerGroup: %d\n", threadsPerGroup);
1071     DP("num_groups: %d\n", num_groups);
1072     DP("loop_tripcount: %ld\n", loop_tripcount);
1073   }
1074   DP("Final %d num_groups and %d threadsPerGroup\n", num_groups,
1075      threadsPerGroup);
1076 
1077   launchVals res;
1078   res.WorkgroupSize = threadsPerGroup;
1079   res.GridSize = threadsPerGroup * num_groups;
1080   return res;
1081 }
1082 
1083 static uint64_t acquire_available_packet_id(hsa_queue_t *queue) {
1084   uint64_t packet_id = hsa_queue_add_write_index_relaxed(queue, 1);
1085   bool full = true;
1086   while (full) {
1087     full =
1088         packet_id >= (queue->size + hsa_queue_load_read_index_scacquire(queue));
1089   }
1090   return packet_id;
1091 }
1092 
1093 int32_t runRegionLocked(int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
1094                         ptrdiff_t *tgt_offsets, int32_t arg_num,
1095                         int32_t num_teams, int32_t thread_limit,
1096                         uint64_t loop_tripcount) {
1097   // Set the context we are using
1098   // update thread limit content in gpu memory if un-initialized or specified
1099   // from host
1100 
1101   DP("Run target team region thread_limit %d\n", thread_limit);
1102 
1103   // All args are references.
1104   std::vector<void *> args(arg_num);
1105   std::vector<void *> ptrs(arg_num);
1106 
1107   DP("Arg_num: %d\n", arg_num);
1108   for (int32_t i = 0; i < arg_num; ++i) {
1109     ptrs[i] = (void *)((intptr_t)tgt_args[i] + tgt_offsets[i]);
1110     args[i] = &ptrs[i];
1111     DP("Offseted base: arg[%d]:" DPxMOD "\n", i, DPxPTR(ptrs[i]));
1112   }
1113 
1114   KernelTy *KernelInfo = (KernelTy *)tgt_entry_ptr;
1115 
1116   std::string kernel_name = std::string(KernelInfo->Name);
1117   auto &KernelInfoTable = DeviceInfo.KernelInfoTable;
1118   if (KernelInfoTable[device_id].find(kernel_name) ==
1119       KernelInfoTable[device_id].end()) {
1120     DP("Kernel %s not found\n", kernel_name.c_str());
1121     return OFFLOAD_FAIL;
1122   }
1123 
1124   const atl_kernel_info_t KernelInfoEntry =
1125       KernelInfoTable[device_id][kernel_name];
1126   const uint32_t group_segment_size = KernelInfoEntry.group_segment_size;
1127   const uint32_t sgpr_count = KernelInfoEntry.sgpr_count;
1128   const uint32_t vgpr_count = KernelInfoEntry.vgpr_count;
1129   const uint32_t sgpr_spill_count = KernelInfoEntry.sgpr_spill_count;
1130   const uint32_t vgpr_spill_count = KernelInfoEntry.vgpr_spill_count;
1131 
1132   assert(arg_num == (int)KernelInfoEntry.explicit_argument_count);
1133 
1134   /*
1135    * Set limit based on ThreadsPerGroup and GroupsPerDevice
1136    */
1137   launchVals LV =
1138       getLaunchVals(DeviceInfo.WarpSize[device_id], DeviceInfo.Env,
1139                     KernelInfo->ConstWGSize, KernelInfo->ExecutionMode,
1140                     num_teams,      // From run_region arg
1141                     thread_limit,   // From run_region arg
1142                     loop_tripcount, // From run_region arg
1143                     DeviceInfo.NumTeams[KernelInfo->device_id]);
1144   const int GridSize = LV.GridSize;
1145   const int WorkgroupSize = LV.WorkgroupSize;
1146 
1147   if (print_kernel_trace >= LAUNCH) {
1148     int num_groups = GridSize / WorkgroupSize;
1149     // enum modes are SPMD, GENERIC, NONE 0,1,2
1150     // if doing rtl timing, print to stderr, unless stdout requested.
1151     bool traceToStdout = print_kernel_trace & (RTL_TO_STDOUT | RTL_TIMING);
1152     fprintf(traceToStdout ? stdout : stderr,
1153             "DEVID:%2d SGN:%1d ConstWGSize:%-4d args:%2d teamsXthrds:(%4dX%4d) "
1154             "reqd:(%4dX%4d) lds_usage:%uB sgpr_count:%u vgpr_count:%u "
1155             "sgpr_spill_count:%u vgpr_spill_count:%u tripcount:%lu n:%s\n",
1156             device_id, KernelInfo->ExecutionMode, KernelInfo->ConstWGSize,
1157             arg_num, num_groups, WorkgroupSize, num_teams, thread_limit,
1158             group_segment_size, sgpr_count, vgpr_count, sgpr_spill_count,
1159             vgpr_spill_count, loop_tripcount, KernelInfo->Name);
1160   }
1161 
1162   // Run on the device.
1163   {
1164     hsa_queue_t *queue = DeviceInfo.HSAQueueSchedulers[device_id].Next();
1165     if (!queue) {
1166       return OFFLOAD_FAIL;
1167     }
1168     uint64_t packet_id = acquire_available_packet_id(queue);
1169 
1170     const uint32_t mask = queue->size - 1; // size is a power of 2
1171     hsa_kernel_dispatch_packet_t *packet =
1172         (hsa_kernel_dispatch_packet_t *)queue->base_address +
1173         (packet_id & mask);
1174 
1175     // packet->header is written last
1176     packet->setup = UINT16_C(1) << HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS;
1177     packet->workgroup_size_x = WorkgroupSize;
1178     packet->workgroup_size_y = 1;
1179     packet->workgroup_size_z = 1;
1180     packet->reserved0 = 0;
1181     packet->grid_size_x = GridSize;
1182     packet->grid_size_y = 1;
1183     packet->grid_size_z = 1;
1184     packet->private_segment_size = KernelInfoEntry.private_segment_size;
1185     packet->group_segment_size = KernelInfoEntry.group_segment_size;
1186     packet->kernel_object = KernelInfoEntry.kernel_object;
1187     packet->kernarg_address = 0;     // use the block allocator
1188     packet->reserved2 = 0;           // impl writes id_ here
1189     packet->completion_signal = {0}; // may want a pool of signals
1190 
1191     KernelArgPool *ArgPool = nullptr;
1192     void *kernarg = nullptr;
1193     {
1194       auto it = KernelArgPoolMap.find(std::string(KernelInfo->Name));
1195       if (it != KernelArgPoolMap.end()) {
1196         ArgPool = (it->second).get();
1197       }
1198     }
1199     if (!ArgPool) {
1200       DP("Warning: No ArgPool for %s on device %d\n", KernelInfo->Name,
1201          device_id);
1202     }
1203     {
1204       if (ArgPool) {
1205         assert(ArgPool->kernarg_segment_size == (arg_num * sizeof(void *)));
1206         kernarg = ArgPool->allocate(arg_num);
1207       }
1208       if (!kernarg) {
1209         DP("Allocate kernarg failed\n");
1210         return OFFLOAD_FAIL;
1211       }
1212 
1213       // Copy explicit arguments
1214       for (int i = 0; i < arg_num; i++) {
1215         memcpy((char *)kernarg + sizeof(void *) * i, args[i], sizeof(void *));
1216       }
1217 
1218       // Initialize implicit arguments. TODO: Which of these can be dropped
1219       impl_implicit_args_t *impl_args =
1220           reinterpret_cast<impl_implicit_args_t *>(
1221               static_cast<char *>(kernarg) + ArgPool->kernarg_segment_size);
1222       memset(impl_args, 0,
1223              sizeof(impl_implicit_args_t)); // may not be necessary
1224       impl_args->offset_x = 0;
1225       impl_args->offset_y = 0;
1226       impl_args->offset_z = 0;
1227 
1228       // assign a hostcall buffer for the selected Q
1229       if (__atomic_load_n(&DeviceInfo.hostcall_required, __ATOMIC_ACQUIRE)) {
1230         // hostrpc_assign_buffer is not thread safe, and this function is
1231         // under a multiple reader lock, not a writer lock.
1232         static pthread_mutex_t hostcall_init_lock = PTHREAD_MUTEX_INITIALIZER;
1233         pthread_mutex_lock(&hostcall_init_lock);
1234         uint64_t buffer = hostrpc_assign_buffer(DeviceInfo.HSAAgents[device_id],
1235                                                 queue, device_id);
1236         pthread_mutex_unlock(&hostcall_init_lock);
1237         if (!buffer) {
1238           DP("hostrpc_assign_buffer failed, gpu would dereference null and "
1239              "error\n");
1240           return OFFLOAD_FAIL;
1241         }
1242 
1243         DP("Implicit argument count: %d\n",
1244            KernelInfoEntry.implicit_argument_count);
1245         if (KernelInfoEntry.implicit_argument_count >= 4) {
1246           // Initialise pointer for implicit_argument_count != 0 ABI
1247           // Guess that the right implicit argument is at offset 24 after
1248           // the explicit arguments. In the future, should be able to read
1249           // the offset from msgpack. Clang is not annotating it at present.
1250           uint64_t Offset =
1251               sizeof(void *) * (KernelInfoEntry.explicit_argument_count + 3);
1252           if ((Offset + 8) > ArgPool->kernarg_size_including_implicit()) {
1253             DP("Bad offset of hostcall: %lu, exceeds kernarg size w/ implicit "
1254                "args: %d\n",
1255                Offset + 8, ArgPool->kernarg_size_including_implicit());
1256           } else {
1257             memcpy(static_cast<char *>(kernarg) + Offset, &buffer, 8);
1258           }
1259         }
1260 
1261         // initialise pointer for implicit_argument_count == 0 ABI
1262         impl_args->hostcall_ptr = buffer;
1263       }
1264 
1265       packet->kernarg_address = kernarg;
1266     }
1267 
1268     hsa_signal_t s = DeviceInfo.FreeSignalPool.pop();
1269     if (s.handle == 0) {
1270       DP("Failed to get signal instance\n");
1271       return OFFLOAD_FAIL;
1272     }
1273     packet->completion_signal = s;
1274     hsa_signal_store_relaxed(packet->completion_signal, 1);
1275 
1276     // Publish the packet indicating it is ready to be processed
1277     core::packet_store_release(reinterpret_cast<uint32_t *>(packet),
1278                                core::create_header(), packet->setup);
1279 
1280     // Since the packet is already published, its contents must not be
1281     // accessed any more
1282     hsa_signal_store_relaxed(queue->doorbell_signal, packet_id);
1283 
1284     while (hsa_signal_wait_scacquire(s, HSA_SIGNAL_CONDITION_EQ, 0, UINT64_MAX,
1285                                      HSA_WAIT_STATE_BLOCKED) != 0)
1286       ;
1287 
1288     assert(ArgPool);
1289     ArgPool->deallocate(kernarg);
1290     DeviceInfo.FreeSignalPool.push(s);
1291   }
1292 
1293   DP("Kernel completed\n");
1294   return OFFLOAD_SUCCESS;
1295 }
1296 
1297 bool elf_machine_id_is_amdgcn(__tgt_device_image *image) {
1298   const uint16_t amdgcnMachineID = 224; // EM_AMDGPU may not be in system elf.h
1299   int32_t r = elf_check_machine(image, amdgcnMachineID);
1300   if (!r) {
1301     DP("Supported machine ID not found\n");
1302   }
1303   return r;
1304 }
1305 
1306 uint32_t elf_e_flags(__tgt_device_image *image) {
1307   char *img_begin = (char *)image->ImageStart;
1308   size_t img_size = (char *)image->ImageEnd - img_begin;
1309 
1310   Elf *e = elf_memory(img_begin, img_size);
1311   if (!e) {
1312     DP("Unable to get ELF handle: %s!\n", elf_errmsg(-1));
1313     return 0;
1314   }
1315 
1316   Elf64_Ehdr *eh64 = elf64_getehdr(e);
1317 
1318   if (!eh64) {
1319     DP("Unable to get machine ID from ELF file!\n");
1320     elf_end(e);
1321     return 0;
1322   }
1323 
1324   uint32_t Flags = eh64->e_flags;
1325 
1326   elf_end(e);
1327   DP("ELF Flags: 0x%x\n", Flags);
1328   return Flags;
1329 }
1330 
1331 template <typename T> bool enforce_upper_bound(T *value, T upper) {
1332   bool changed = *value > upper;
1333   if (changed) {
1334     *value = upper;
1335   }
1336   return changed;
1337 }
1338 
1339 Elf64_Shdr *find_only_SHT_HASH(Elf *elf) {
1340   size_t N;
1341   int rc = elf_getshdrnum(elf, &N);
1342   if (rc != 0) {
1343     return nullptr;
1344   }
1345 
1346   Elf64_Shdr *result = nullptr;
1347   for (size_t i = 0; i < N; i++) {
1348     Elf_Scn *scn = elf_getscn(elf, i);
1349     if (scn) {
1350       Elf64_Shdr *shdr = elf64_getshdr(scn);
1351       if (shdr) {
1352         if (shdr->sh_type == SHT_HASH) {
1353           if (result == nullptr) {
1354             result = shdr;
1355           } else {
1356             // multiple SHT_HASH sections not handled
1357             return nullptr;
1358           }
1359         }
1360       }
1361     }
1362   }
1363   return result;
1364 }
1365 
1366 const Elf64_Sym *elf_lookup(Elf *elf, char *base, Elf64_Shdr *section_hash,
1367                             const char *symname) {
1368 
1369   assert(section_hash);
1370   size_t section_symtab_index = section_hash->sh_link;
1371   Elf64_Shdr *section_symtab =
1372       elf64_getshdr(elf_getscn(elf, section_symtab_index));
1373   size_t section_strtab_index = section_symtab->sh_link;
1374 
1375   const Elf64_Sym *symtab =
1376       reinterpret_cast<const Elf64_Sym *>(base + section_symtab->sh_offset);
1377 
1378   const uint32_t *hashtab =
1379       reinterpret_cast<const uint32_t *>(base + section_hash->sh_offset);
1380 
1381   // Layout:
1382   // nbucket
1383   // nchain
1384   // bucket[nbucket]
1385   // chain[nchain]
1386   uint32_t nbucket = hashtab[0];
1387   const uint32_t *bucket = &hashtab[2];
1388   const uint32_t *chain = &hashtab[nbucket + 2];
1389 
1390   const size_t max = strlen(symname) + 1;
1391   const uint32_t hash = elf_hash(symname);
1392   for (uint32_t i = bucket[hash % nbucket]; i != 0; i = chain[i]) {
1393     char *n = elf_strptr(elf, section_strtab_index, symtab[i].st_name);
1394     if (strncmp(symname, n, max) == 0) {
1395       return &symtab[i];
1396     }
1397   }
1398 
1399   return nullptr;
1400 }
1401 
1402 struct symbol_info {
1403   void *addr = nullptr;
1404   uint32_t size = UINT32_MAX;
1405   uint32_t sh_type = SHT_NULL;
1406 };
1407 
1408 int get_symbol_info_without_loading(Elf *elf, char *base, const char *symname,
1409                                     symbol_info *res) {
1410   if (elf_kind(elf) != ELF_K_ELF) {
1411     return 1;
1412   }
1413 
1414   Elf64_Shdr *section_hash = find_only_SHT_HASH(elf);
1415   if (!section_hash) {
1416     return 1;
1417   }
1418 
1419   const Elf64_Sym *sym = elf_lookup(elf, base, section_hash, symname);
1420   if (!sym) {
1421     return 1;
1422   }
1423 
1424   if (sym->st_size > UINT32_MAX) {
1425     return 1;
1426   }
1427 
1428   if (sym->st_shndx == SHN_UNDEF) {
1429     return 1;
1430   }
1431 
1432   Elf_Scn *section = elf_getscn(elf, sym->st_shndx);
1433   if (!section) {
1434     return 1;
1435   }
1436 
1437   Elf64_Shdr *header = elf64_getshdr(section);
1438   if (!header) {
1439     return 1;
1440   }
1441 
1442   res->addr = sym->st_value + base;
1443   res->size = static_cast<uint32_t>(sym->st_size);
1444   res->sh_type = header->sh_type;
1445   return 0;
1446 }
1447 
1448 int get_symbol_info_without_loading(char *base, size_t img_size,
1449                                     const char *symname, symbol_info *res) {
1450   Elf *elf = elf_memory(base, img_size);
1451   if (elf) {
1452     int rc = get_symbol_info_without_loading(elf, base, symname, res);
1453     elf_end(elf);
1454     return rc;
1455   }
1456   return 1;
1457 }
1458 
1459 hsa_status_t interop_get_symbol_info(char *base, size_t img_size,
1460                                      const char *symname, void **var_addr,
1461                                      uint32_t *var_size) {
1462   symbol_info si;
1463   int rc = get_symbol_info_without_loading(base, img_size, symname, &si);
1464   if (rc == 0) {
1465     *var_addr = si.addr;
1466     *var_size = si.size;
1467     return HSA_STATUS_SUCCESS;
1468   } else {
1469     return HSA_STATUS_ERROR;
1470   }
1471 }
1472 
1473 template <typename C>
1474 hsa_status_t module_register_from_memory_to_place(
1475     std::map<std::string, atl_kernel_info_t> &KernelInfoTable,
1476     std::map<std::string, atl_symbol_info_t> &SymbolInfoTable,
1477     void *module_bytes, size_t module_size, int DeviceId, C cb,
1478     std::vector<hsa_executable_t> &HSAExecutables) {
1479   auto L = [](void *data, size_t size, void *cb_state) -> hsa_status_t {
1480     C *unwrapped = static_cast<C *>(cb_state);
1481     return (*unwrapped)(data, size);
1482   };
1483   return core::RegisterModuleFromMemory(
1484       KernelInfoTable, SymbolInfoTable, module_bytes, module_size,
1485       DeviceInfo.HSAAgents[DeviceId], L, static_cast<void *>(&cb),
1486       HSAExecutables);
1487 }
1488 
1489 uint64_t get_device_State_bytes(char *ImageStart, size_t img_size) {
1490   uint64_t device_State_bytes = 0;
1491   {
1492     // If this is the deviceRTL, get the state variable size
1493     symbol_info size_si;
1494     int rc = get_symbol_info_without_loading(
1495         ImageStart, img_size, "omptarget_nvptx_device_State_size", &size_si);
1496 
1497     if (rc == 0) {
1498       if (size_si.size != sizeof(uint64_t)) {
1499         DP("Found device_State_size variable with wrong size\n");
1500         return 0;
1501       }
1502 
1503       // Read number of bytes directly from the elf
1504       memcpy(&device_State_bytes, size_si.addr, sizeof(uint64_t));
1505     }
1506   }
1507   return device_State_bytes;
1508 }
1509 
1510 struct device_environment {
1511   // initialise an DeviceEnvironmentTy in the deviceRTL
1512   // patches around differences in the deviceRTL between trunk, aomp,
1513   // rocmcc. Over time these differences will tend to zero and this class
1514   // simplified.
1515   // Symbol may be in .data or .bss, and may be missing fields, todo:
1516   // review aomp/trunk/rocm and simplify the following
1517 
1518   // The symbol may also have been deadstripped because the device side
1519   // accessors were unused.
1520 
1521   // If the symbol is in .data (aomp, rocm) it can be written directly.
1522   // If it is in .bss, we must wait for it to be allocated space on the
1523   // gpu (trunk) and initialize after loading.
1524   const char *sym() { return "omptarget_device_environment"; }
1525 
1526   DeviceEnvironmentTy host_device_env;
1527   symbol_info si;
1528   bool valid = false;
1529 
1530   __tgt_device_image *image;
1531   const size_t img_size;
1532 
1533   device_environment(int device_id, int number_devices,
1534                      __tgt_device_image *image, const size_t img_size)
1535       : image(image), img_size(img_size) {
1536 
1537     host_device_env.NumDevices = number_devices;
1538     host_device_env.DeviceNum = device_id;
1539     host_device_env.DebugKind = 0;
1540     host_device_env.DynamicMemSize = 0;
1541     if (char *envStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG")) {
1542       host_device_env.DebugKind = std::stoi(envStr);
1543     }
1544 
1545     int rc = get_symbol_info_without_loading((char *)image->ImageStart,
1546                                              img_size, sym(), &si);
1547     if (rc != 0) {
1548       DP("Finding global device environment '%s' - symbol missing.\n", sym());
1549       return;
1550     }
1551 
1552     if (si.size > sizeof(host_device_env)) {
1553       DP("Symbol '%s' has size %u, expected at most %zu.\n", sym(), si.size,
1554          sizeof(host_device_env));
1555       return;
1556     }
1557 
1558     valid = true;
1559   }
1560 
1561   bool in_image() { return si.sh_type != SHT_NOBITS; }
1562 
1563   hsa_status_t before_loading(void *data, size_t size) {
1564     if (valid) {
1565       if (in_image()) {
1566         DP("Setting global device environment before load (%u bytes)\n",
1567            si.size);
1568         uint64_t offset = (char *)si.addr - (char *)image->ImageStart;
1569         void *pos = (char *)data + offset;
1570         memcpy(pos, &host_device_env, si.size);
1571       }
1572     }
1573     return HSA_STATUS_SUCCESS;
1574   }
1575 
1576   hsa_status_t after_loading() {
1577     if (valid) {
1578       if (!in_image()) {
1579         DP("Setting global device environment after load (%u bytes)\n",
1580            si.size);
1581         int device_id = host_device_env.DeviceNum;
1582         auto &SymbolInfo = DeviceInfo.SymbolInfoTable[device_id];
1583         void *state_ptr;
1584         uint32_t state_ptr_size;
1585         hsa_status_t err = interop_hsa_get_symbol_info(
1586             SymbolInfo, device_id, sym(), &state_ptr, &state_ptr_size);
1587         if (err != HSA_STATUS_SUCCESS) {
1588           DP("failed to find %s in loaded image\n", sym());
1589           return err;
1590         }
1591 
1592         if (state_ptr_size != si.size) {
1593           DP("Symbol had size %u before loading, %u after\n", state_ptr_size,
1594              si.size);
1595           return HSA_STATUS_ERROR;
1596         }
1597 
1598         return DeviceInfo.freesignalpool_memcpy_h2d(state_ptr, &host_device_env,
1599                                                     state_ptr_size, device_id);
1600       }
1601     }
1602     return HSA_STATUS_SUCCESS;
1603   }
1604 };
1605 
1606 hsa_status_t impl_calloc(void **ret_ptr, size_t size, int DeviceId) {
1607   uint64_t rounded = 4 * ((size + 3) / 4);
1608   void *ptr;
1609   hsa_amd_memory_pool_t MemoryPool = DeviceInfo.getDeviceMemoryPool(DeviceId);
1610   hsa_status_t err = hsa_amd_memory_pool_allocate(MemoryPool, rounded, 0, &ptr);
1611   if (err != HSA_STATUS_SUCCESS) {
1612     return err;
1613   }
1614 
1615   hsa_status_t rc = hsa_amd_memory_fill(ptr, 0, rounded / 4);
1616   if (rc != HSA_STATUS_SUCCESS) {
1617     DP("zero fill device_state failed with %u\n", rc);
1618     core::Runtime::Memfree(ptr);
1619     return HSA_STATUS_ERROR;
1620   }
1621 
1622   *ret_ptr = ptr;
1623   return HSA_STATUS_SUCCESS;
1624 }
1625 
1626 bool image_contains_symbol(void *data, size_t size, const char *sym) {
1627   symbol_info si;
1628   int rc = get_symbol_info_without_loading((char *)data, size, sym, &si);
1629   return (rc == 0) && (si.addr != nullptr);
1630 }
1631 
1632 } // namespace
1633 
1634 namespace core {
1635 hsa_status_t allow_access_to_all_gpu_agents(void *ptr) {
1636   return hsa_amd_agents_allow_access(DeviceInfo.HSAAgents.size(),
1637                                      &DeviceInfo.HSAAgents[0], NULL, ptr);
1638 }
1639 } // namespace core
1640 
1641 extern "C" {
1642 int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
1643   return elf_machine_id_is_amdgcn(image);
1644 }
1645 
1646 int __tgt_rtl_number_of_devices() {
1647   // If the construction failed, no methods are safe to call
1648   if (DeviceInfo.ConstructionSucceeded) {
1649     return DeviceInfo.NumberOfDevices;
1650   } else {
1651     DP("AMDGPU plugin construction failed. Zero devices available\n");
1652     return 0;
1653   }
1654 }
1655 
1656 int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
1657   DP("Init requires flags to %ld\n", RequiresFlags);
1658   DeviceInfo.RequiresFlags = RequiresFlags;
1659   return RequiresFlags;
1660 }
1661 
1662 int32_t __tgt_rtl_init_device(int device_id) {
1663   hsa_status_t err;
1664 
1665   // this is per device id init
1666   DP("Initialize the device id: %d\n", device_id);
1667 
1668   hsa_agent_t agent = DeviceInfo.HSAAgents[device_id];
1669 
1670   // Get number of Compute Unit
1671   uint32_t compute_units = 0;
1672   err = hsa_agent_get_info(
1673       agent, (hsa_agent_info_t)HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT,
1674       &compute_units);
1675   if (err != HSA_STATUS_SUCCESS) {
1676     DeviceInfo.ComputeUnits[device_id] = 1;
1677     DP("Error getting compute units : settiing to 1\n");
1678   } else {
1679     DeviceInfo.ComputeUnits[device_id] = compute_units;
1680     DP("Using %d compute unis per grid\n", DeviceInfo.ComputeUnits[device_id]);
1681   }
1682 
1683   char GetInfoName[64]; // 64 max size returned by get info
1684   err = hsa_agent_get_info(agent, (hsa_agent_info_t)HSA_AGENT_INFO_NAME,
1685                            (void *)GetInfoName);
1686   if (err)
1687     DeviceInfo.GPUName[device_id] = "--unknown gpu--";
1688   else {
1689     DeviceInfo.GPUName[device_id] = GetInfoName;
1690   }
1691 
1692   if (print_kernel_trace & STARTUP_DETAILS)
1693     DP("Device#%-2d CU's: %2d %s\n", device_id,
1694        DeviceInfo.ComputeUnits[device_id],
1695        DeviceInfo.GPUName[device_id].c_str());
1696 
1697   // Query attributes to determine number of threads/block and blocks/grid.
1698   uint16_t workgroup_max_dim[3];
1699   err = hsa_agent_get_info(agent, HSA_AGENT_INFO_WORKGROUP_MAX_DIM,
1700                            &workgroup_max_dim);
1701   if (err != HSA_STATUS_SUCCESS) {
1702     DeviceInfo.GroupsPerDevice[device_id] = RTLDeviceInfoTy::DefaultNumTeams;
1703     DP("Error getting grid dims: num groups : %d\n",
1704        RTLDeviceInfoTy::DefaultNumTeams);
1705   } else if (workgroup_max_dim[0] <= RTLDeviceInfoTy::HardTeamLimit) {
1706     DeviceInfo.GroupsPerDevice[device_id] = workgroup_max_dim[0];
1707     DP("Using %d ROCm blocks per grid\n",
1708        DeviceInfo.GroupsPerDevice[device_id]);
1709   } else {
1710     DeviceInfo.GroupsPerDevice[device_id] = RTLDeviceInfoTy::HardTeamLimit;
1711     DP("Max ROCm blocks per grid %d exceeds the hard team limit %d, capping "
1712        "at the hard limit\n",
1713        workgroup_max_dim[0], RTLDeviceInfoTy::HardTeamLimit);
1714   }
1715 
1716   // Get thread limit
1717   hsa_dim3_t grid_max_dim;
1718   err = hsa_agent_get_info(agent, HSA_AGENT_INFO_GRID_MAX_DIM, &grid_max_dim);
1719   if (err == HSA_STATUS_SUCCESS) {
1720     DeviceInfo.ThreadsPerGroup[device_id] =
1721         reinterpret_cast<uint32_t *>(&grid_max_dim)[0] /
1722         DeviceInfo.GroupsPerDevice[device_id];
1723 
1724     if (DeviceInfo.ThreadsPerGroup[device_id] == 0) {
1725       DeviceInfo.ThreadsPerGroup[device_id] = RTLDeviceInfoTy::Max_WG_Size;
1726       DP("Default thread limit: %d\n", RTLDeviceInfoTy::Max_WG_Size);
1727     } else if (enforce_upper_bound(&DeviceInfo.ThreadsPerGroup[device_id],
1728                                    RTLDeviceInfoTy::Max_WG_Size)) {
1729       DP("Capped thread limit: %d\n", RTLDeviceInfoTy::Max_WG_Size);
1730     } else {
1731       DP("Using ROCm Queried thread limit: %d\n",
1732          DeviceInfo.ThreadsPerGroup[device_id]);
1733     }
1734   } else {
1735     DeviceInfo.ThreadsPerGroup[device_id] = RTLDeviceInfoTy::Max_WG_Size;
1736     DP("Error getting max block dimension, use default:%d \n",
1737        RTLDeviceInfoTy::Max_WG_Size);
1738   }
1739 
1740   // Get wavefront size
1741   uint32_t wavefront_size = 0;
1742   err =
1743       hsa_agent_get_info(agent, HSA_AGENT_INFO_WAVEFRONT_SIZE, &wavefront_size);
1744   if (err == HSA_STATUS_SUCCESS) {
1745     DP("Queried wavefront size: %d\n", wavefront_size);
1746     DeviceInfo.WarpSize[device_id] = wavefront_size;
1747   } else {
1748     // TODO: Burn the wavefront size into the code object
1749     DP("Warning: Unknown wavefront size, assuming 64\n");
1750     DeviceInfo.WarpSize[device_id] = 64;
1751   }
1752 
1753   // Adjust teams to the env variables
1754 
1755   if (DeviceInfo.Env.TeamLimit > 0 &&
1756       (enforce_upper_bound(&DeviceInfo.GroupsPerDevice[device_id],
1757                            DeviceInfo.Env.TeamLimit))) {
1758     DP("Capping max groups per device to OMP_TEAM_LIMIT=%d\n",
1759        DeviceInfo.Env.TeamLimit);
1760   }
1761 
1762   // Set default number of teams
1763   if (DeviceInfo.Env.NumTeams > 0) {
1764     DeviceInfo.NumTeams[device_id] = DeviceInfo.Env.NumTeams;
1765     DP("Default number of teams set according to environment %d\n",
1766        DeviceInfo.Env.NumTeams);
1767   } else {
1768     char *TeamsPerCUEnvStr = getenv("OMP_TARGET_TEAMS_PER_PROC");
1769     int TeamsPerCU = DefaultTeamsPerCU;
1770     if (TeamsPerCUEnvStr) {
1771       TeamsPerCU = std::stoi(TeamsPerCUEnvStr);
1772     }
1773 
1774     DeviceInfo.NumTeams[device_id] =
1775         TeamsPerCU * DeviceInfo.ComputeUnits[device_id];
1776     DP("Default number of teams = %d * number of compute units %d\n",
1777        TeamsPerCU, DeviceInfo.ComputeUnits[device_id]);
1778   }
1779 
1780   if (enforce_upper_bound(&DeviceInfo.NumTeams[device_id],
1781                           DeviceInfo.GroupsPerDevice[device_id])) {
1782     DP("Default number of teams exceeds device limit, capping at %d\n",
1783        DeviceInfo.GroupsPerDevice[device_id]);
1784   }
1785 
1786   // Adjust threads to the env variables
1787   if (DeviceInfo.Env.TeamThreadLimit > 0 &&
1788       (enforce_upper_bound(&DeviceInfo.NumThreads[device_id],
1789                            DeviceInfo.Env.TeamThreadLimit))) {
1790     DP("Capping max number of threads to OMP_TEAMS_THREAD_LIMIT=%d\n",
1791        DeviceInfo.Env.TeamThreadLimit);
1792   }
1793 
1794   // Set default number of threads
1795   DeviceInfo.NumThreads[device_id] = RTLDeviceInfoTy::Default_WG_Size;
1796   DP("Default number of threads set according to library's default %d\n",
1797      RTLDeviceInfoTy::Default_WG_Size);
1798   if (enforce_upper_bound(&DeviceInfo.NumThreads[device_id],
1799                           DeviceInfo.ThreadsPerGroup[device_id])) {
1800     DP("Default number of threads exceeds device limit, capping at %d\n",
1801        DeviceInfo.ThreadsPerGroup[device_id]);
1802   }
1803 
1804   DP("Device %d: default limit for groupsPerDevice %d & threadsPerGroup %d\n",
1805      device_id, DeviceInfo.GroupsPerDevice[device_id],
1806      DeviceInfo.ThreadsPerGroup[device_id]);
1807 
1808   DP("Device %d: wavefront size %d, total threads %d x %d = %d\n", device_id,
1809      DeviceInfo.WarpSize[device_id], DeviceInfo.ThreadsPerGroup[device_id],
1810      DeviceInfo.GroupsPerDevice[device_id],
1811      DeviceInfo.GroupsPerDevice[device_id] *
1812          DeviceInfo.ThreadsPerGroup[device_id]);
1813 
1814   return OFFLOAD_SUCCESS;
1815 }
1816 
1817 static __tgt_target_table *
1818 __tgt_rtl_load_binary_locked(int32_t device_id, __tgt_device_image *image);
1819 
1820 __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
1821                                           __tgt_device_image *image) {
1822   DeviceInfo.load_run_lock.lock();
1823   __tgt_target_table *res = __tgt_rtl_load_binary_locked(device_id, image);
1824   DeviceInfo.load_run_lock.unlock();
1825   return res;
1826 }
1827 
1828 __tgt_target_table *__tgt_rtl_load_binary_locked(int32_t device_id,
1829                                                  __tgt_device_image *image) {
1830   // This function loads the device image onto gpu[device_id] and does other
1831   // per-image initialization work. Specifically:
1832   //
1833   // - Initialize an DeviceEnvironmentTy instance embedded in the
1834   //   image at the symbol "omptarget_device_environment"
1835   //   Fields DebugKind, DeviceNum, NumDevices. Used by the deviceRTL.
1836   //
1837   // - Allocate a large array per-gpu (could be moved to init_device)
1838   //   - Read a uint64_t at symbol omptarget_nvptx_device_State_size
1839   //   - Allocate at least that many bytes of gpu memory
1840   //   - Zero initialize it
1841   //   - Write the pointer to the symbol omptarget_nvptx_device_State
1842   //
1843   // - Pulls some per-kernel information together from various sources and
1844   //   records it in the KernelsList for quicker access later
1845   //
1846   // The initialization can be done before or after loading the image onto the
1847   // gpu. This function presently does a mixture. Using the hsa api to get/set
1848   // the information is simpler to implement, in exchange for more complicated
1849   // runtime behaviour. E.g. launching a kernel or using dma to get eight bytes
1850   // back from the gpu vs a hashtable lookup on the host.
1851 
1852   const size_t img_size = (char *)image->ImageEnd - (char *)image->ImageStart;
1853 
1854   DeviceInfo.clearOffloadEntriesTable(device_id);
1855 
1856   // We do not need to set the ELF version because the caller of this function
1857   // had to do that to decide the right runtime to use
1858 
1859   if (!elf_machine_id_is_amdgcn(image)) {
1860     return NULL;
1861   }
1862 
1863   {
1864     auto env = device_environment(device_id, DeviceInfo.NumberOfDevices, image,
1865                                   img_size);
1866 
1867     auto &KernelInfo = DeviceInfo.KernelInfoTable[device_id];
1868     auto &SymbolInfo = DeviceInfo.SymbolInfoTable[device_id];
1869     hsa_status_t err = module_register_from_memory_to_place(
1870         KernelInfo, SymbolInfo, (void *)image->ImageStart, img_size, device_id,
1871         [&](void *data, size_t size) {
1872           if (image_contains_symbol(data, size, "needs_hostcall_buffer")) {
1873             __atomic_store_n(&DeviceInfo.hostcall_required, true,
1874                              __ATOMIC_RELEASE);
1875           }
1876           return env.before_loading(data, size);
1877         },
1878         DeviceInfo.HSAExecutables);
1879 
1880     check("Module registering", err);
1881     if (err != HSA_STATUS_SUCCESS) {
1882       const char *DeviceName = DeviceInfo.GPUName[device_id].c_str();
1883       const char *ElfName = get_elf_mach_gfx_name(elf_e_flags(image));
1884 
1885       if (strcmp(DeviceName, ElfName) != 0) {
1886         DP("Possible gpu arch mismatch: device:%s, image:%s please check"
1887            " compiler flag: -march=<gpu>\n",
1888            DeviceName, ElfName);
1889       } else {
1890         DP("Error loading image onto GPU: %s\n", get_error_string(err));
1891       }
1892 
1893       return NULL;
1894     }
1895 
1896     err = env.after_loading();
1897     if (err != HSA_STATUS_SUCCESS) {
1898       return NULL;
1899     }
1900   }
1901 
1902   DP("AMDGPU module successfully loaded!\n");
1903 
1904   {
1905     // the device_State array is either large value in bss or a void* that
1906     // needs to be assigned to a pointer to an array of size device_state_bytes
1907     // If absent, it has been deadstripped and needs no setup.
1908 
1909     void *state_ptr;
1910     uint32_t state_ptr_size;
1911     auto &SymbolInfoMap = DeviceInfo.SymbolInfoTable[device_id];
1912     hsa_status_t err = interop_hsa_get_symbol_info(
1913         SymbolInfoMap, device_id, "omptarget_nvptx_device_State", &state_ptr,
1914         &state_ptr_size);
1915 
1916     if (err != HSA_STATUS_SUCCESS) {
1917       DP("No device_state symbol found, skipping initialization\n");
1918     } else {
1919       if (state_ptr_size < sizeof(void *)) {
1920         DP("unexpected size of state_ptr %u != %zu\n", state_ptr_size,
1921            sizeof(void *));
1922         return NULL;
1923       }
1924 
1925       // if it's larger than a void*, assume it's a bss array and no further
1926       // initialization is required. Only try to set up a pointer for
1927       // sizeof(void*)
1928       if (state_ptr_size == sizeof(void *)) {
1929         uint64_t device_State_bytes =
1930             get_device_State_bytes((char *)image->ImageStart, img_size);
1931         if (device_State_bytes == 0) {
1932           DP("Can't initialize device_State, missing size information\n");
1933           return NULL;
1934         }
1935 
1936         auto &dss = DeviceInfo.deviceStateStore[device_id];
1937         if (dss.first.get() == nullptr) {
1938           assert(dss.second == 0);
1939           void *ptr = NULL;
1940           hsa_status_t err = impl_calloc(&ptr, device_State_bytes, device_id);
1941           if (err != HSA_STATUS_SUCCESS) {
1942             DP("Failed to allocate device_state array\n");
1943             return NULL;
1944           }
1945           dss = {
1946               std::unique_ptr<void, RTLDeviceInfoTy::implFreePtrDeletor>{ptr},
1947               device_State_bytes,
1948           };
1949         }
1950 
1951         void *ptr = dss.first.get();
1952         if (device_State_bytes != dss.second) {
1953           DP("Inconsistent sizes of device_State unsupported\n");
1954           return NULL;
1955         }
1956 
1957         // write ptr to device memory so it can be used by later kernels
1958         err = DeviceInfo.freesignalpool_memcpy_h2d(state_ptr, &ptr,
1959                                                    sizeof(void *), device_id);
1960         if (err != HSA_STATUS_SUCCESS) {
1961           DP("memcpy install of state_ptr failed\n");
1962           return NULL;
1963         }
1964       }
1965     }
1966   }
1967 
1968   // Here, we take advantage of the data that is appended after img_end to get
1969   // the symbols' name we need to load. This data consist of the host entries
1970   // begin and end as well as the target name (see the offloading linker script
1971   // creation in clang compiler).
1972 
1973   // Find the symbols in the module by name. The name can be obtain by
1974   // concatenating the host entry name with the target name
1975 
1976   __tgt_offload_entry *HostBegin = image->EntriesBegin;
1977   __tgt_offload_entry *HostEnd = image->EntriesEnd;
1978 
1979   for (__tgt_offload_entry *e = HostBegin; e != HostEnd; ++e) {
1980 
1981     if (!e->addr) {
1982       // The host should have always something in the address to
1983       // uniquely identify the target region.
1984       DP("Analyzing host entry '<null>' (size = %lld)...\n",
1985          (unsigned long long)e->size);
1986       return NULL;
1987     }
1988 
1989     if (e->size) {
1990       __tgt_offload_entry entry = *e;
1991 
1992       void *varptr;
1993       uint32_t varsize;
1994 
1995       auto &SymbolInfoMap = DeviceInfo.SymbolInfoTable[device_id];
1996       hsa_status_t err = interop_hsa_get_symbol_info(
1997           SymbolInfoMap, device_id, e->name, &varptr, &varsize);
1998 
1999       if (err != HSA_STATUS_SUCCESS) {
2000         // Inform the user what symbol prevented offloading
2001         DP("Loading global '%s' (Failed)\n", e->name);
2002         return NULL;
2003       }
2004 
2005       if (varsize != e->size) {
2006         DP("Loading global '%s' - size mismatch (%u != %lu)\n", e->name,
2007            varsize, e->size);
2008         return NULL;
2009       }
2010 
2011       DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
2012          DPxPTR(e - HostBegin), e->name, DPxPTR(varptr));
2013       entry.addr = (void *)varptr;
2014 
2015       DeviceInfo.addOffloadEntry(device_id, entry);
2016 
2017       if (DeviceInfo.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
2018           e->flags & OMP_DECLARE_TARGET_LINK) {
2019         // If unified memory is present any target link variables
2020         // can access host addresses directly. There is no longer a
2021         // need for device copies.
2022         err = DeviceInfo.freesignalpool_memcpy_h2d(varptr, e->addr,
2023                                                    sizeof(void *), device_id);
2024         if (err != HSA_STATUS_SUCCESS)
2025           DP("Error when copying USM\n");
2026         DP("Copy linked variable host address (" DPxMOD ")"
2027            "to device address (" DPxMOD ")\n",
2028            DPxPTR(*((void **)e->addr)), DPxPTR(varptr));
2029       }
2030 
2031       continue;
2032     }
2033 
2034     DP("to find the kernel name: %s size: %lu\n", e->name, strlen(e->name));
2035 
2036     // errors in kernarg_segment_size previously treated as = 0 (or as undef)
2037     uint32_t kernarg_segment_size = 0;
2038     auto &KernelInfoMap = DeviceInfo.KernelInfoTable[device_id];
2039     hsa_status_t err = HSA_STATUS_SUCCESS;
2040     if (!e->name) {
2041       err = HSA_STATUS_ERROR;
2042     } else {
2043       std::string kernelStr = std::string(e->name);
2044       auto It = KernelInfoMap.find(kernelStr);
2045       if (It != KernelInfoMap.end()) {
2046         atl_kernel_info_t info = It->second;
2047         kernarg_segment_size = info.kernel_segment_size;
2048       } else {
2049         err = HSA_STATUS_ERROR;
2050       }
2051     }
2052 
2053     // default value GENERIC (in case symbol is missing from cubin file)
2054     llvm::omp::OMPTgtExecModeFlags ExecModeVal =
2055         llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC;
2056 
2057     // get flat group size if present, else Default_WG_Size
2058     int16_t WGSizeVal = RTLDeviceInfoTy::Default_WG_Size;
2059 
2060     // get Kernel Descriptor if present.
2061     // Keep struct in sync wih getTgtAttributeStructQTy in CGOpenMPRuntime.cpp
2062     struct KernDescValType {
2063       uint16_t Version;
2064       uint16_t TSize;
2065       uint16_t WG_Size;
2066     };
2067     struct KernDescValType KernDescVal;
2068     std::string KernDescNameStr(e->name);
2069     KernDescNameStr += "_kern_desc";
2070     const char *KernDescName = KernDescNameStr.c_str();
2071 
2072     void *KernDescPtr;
2073     uint32_t KernDescSize;
2074     void *CallStackAddr = nullptr;
2075     err = interop_get_symbol_info((char *)image->ImageStart, img_size,
2076                                   KernDescName, &KernDescPtr, &KernDescSize);
2077 
2078     if (err == HSA_STATUS_SUCCESS) {
2079       if ((size_t)KernDescSize != sizeof(KernDescVal))
2080         DP("Loading global computation properties '%s' - size mismatch (%u != "
2081            "%lu)\n",
2082            KernDescName, KernDescSize, sizeof(KernDescVal));
2083 
2084       memcpy(&KernDescVal, KernDescPtr, (size_t)KernDescSize);
2085 
2086       // Check structure size against recorded size.
2087       if ((size_t)KernDescSize != KernDescVal.TSize)
2088         DP("KernDescVal size %lu does not match advertized size %d for '%s'\n",
2089            sizeof(KernDescVal), KernDescVal.TSize, KernDescName);
2090 
2091       DP("After loading global for %s KernDesc \n", KernDescName);
2092       DP("KernDesc: Version: %d\n", KernDescVal.Version);
2093       DP("KernDesc: TSize: %d\n", KernDescVal.TSize);
2094       DP("KernDesc: WG_Size: %d\n", KernDescVal.WG_Size);
2095 
2096       if (KernDescVal.WG_Size == 0) {
2097         KernDescVal.WG_Size = RTLDeviceInfoTy::Default_WG_Size;
2098         DP("Setting KernDescVal.WG_Size to default %d\n", KernDescVal.WG_Size);
2099       }
2100       WGSizeVal = KernDescVal.WG_Size;
2101       DP("WGSizeVal %d\n", WGSizeVal);
2102       check("Loading KernDesc computation property", err);
2103     } else {
2104       DP("Warning: Loading KernDesc '%s' - symbol not found, ", KernDescName);
2105 
2106       // Flat group size
2107       std::string WGSizeNameStr(e->name);
2108       WGSizeNameStr += "_wg_size";
2109       const char *WGSizeName = WGSizeNameStr.c_str();
2110 
2111       void *WGSizePtr;
2112       uint32_t WGSize;
2113       err = interop_get_symbol_info((char *)image->ImageStart, img_size,
2114                                     WGSizeName, &WGSizePtr, &WGSize);
2115 
2116       if (err == HSA_STATUS_SUCCESS) {
2117         if ((size_t)WGSize != sizeof(int16_t)) {
2118           DP("Loading global computation properties '%s' - size mismatch (%u "
2119              "!= "
2120              "%lu)\n",
2121              WGSizeName, WGSize, sizeof(int16_t));
2122           return NULL;
2123         }
2124 
2125         memcpy(&WGSizeVal, WGSizePtr, (size_t)WGSize);
2126 
2127         DP("After loading global for %s WGSize = %d\n", WGSizeName, WGSizeVal);
2128 
2129         if (WGSizeVal < RTLDeviceInfoTy::Default_WG_Size ||
2130             WGSizeVal > RTLDeviceInfoTy::Max_WG_Size) {
2131           DP("Error wrong WGSize value specified in HSA code object file: "
2132              "%d\n",
2133              WGSizeVal);
2134           WGSizeVal = RTLDeviceInfoTy::Default_WG_Size;
2135         }
2136       } else {
2137         DP("Warning: Loading WGSize '%s' - symbol not found, "
2138            "using default value %d\n",
2139            WGSizeName, WGSizeVal);
2140       }
2141 
2142       check("Loading WGSize computation property", err);
2143     }
2144 
2145     // Read execution mode from global in binary
2146     std::string ExecModeNameStr(e->name);
2147     ExecModeNameStr += "_exec_mode";
2148     const char *ExecModeName = ExecModeNameStr.c_str();
2149 
2150     void *ExecModePtr;
2151     uint32_t varsize;
2152     err = interop_get_symbol_info((char *)image->ImageStart, img_size,
2153                                   ExecModeName, &ExecModePtr, &varsize);
2154 
2155     if (err == HSA_STATUS_SUCCESS) {
2156       if ((size_t)varsize != sizeof(llvm::omp::OMPTgtExecModeFlags)) {
2157         DP("Loading global computation properties '%s' - size mismatch(%u != "
2158            "%lu)\n",
2159            ExecModeName, varsize, sizeof(llvm::omp::OMPTgtExecModeFlags));
2160         return NULL;
2161       }
2162 
2163       memcpy(&ExecModeVal, ExecModePtr, (size_t)varsize);
2164 
2165       DP("After loading global for %s ExecMode = %d\n", ExecModeName,
2166          ExecModeVal);
2167 
2168       if (ExecModeVal < 0 ||
2169           ExecModeVal > llvm::omp::OMP_TGT_EXEC_MODE_GENERIC_SPMD) {
2170         DP("Error wrong exec_mode value specified in HSA code object file: "
2171            "%d\n",
2172            ExecModeVal);
2173         return NULL;
2174       }
2175     } else {
2176       DP("Loading global exec_mode '%s' - symbol missing, using default "
2177          "value "
2178          "GENERIC (1)\n",
2179          ExecModeName);
2180     }
2181     check("Loading computation property", err);
2182 
2183     KernelsList.push_back(KernelTy(ExecModeVal, WGSizeVal, device_id,
2184                                    CallStackAddr, e->name, kernarg_segment_size,
2185                                    DeviceInfo.KernArgPool));
2186     __tgt_offload_entry entry = *e;
2187     entry.addr = (void *)&KernelsList.back();
2188     DeviceInfo.addOffloadEntry(device_id, entry);
2189     DP("Entry point %ld maps to %s\n", e - HostBegin, e->name);
2190   }
2191 
2192   return DeviceInfo.getOffloadEntriesTable(device_id);
2193 }
2194 
2195 void *__tgt_rtl_data_alloc(int device_id, int64_t size, void *, int32_t kind) {
2196   void *ptr = NULL;
2197   assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large");
2198 
2199   if (kind != TARGET_ALLOC_DEFAULT) {
2200     REPORT("Invalid target data allocation kind or requested allocator not "
2201            "implemented yet\n");
2202     return NULL;
2203   }
2204 
2205   hsa_amd_memory_pool_t MemoryPool = DeviceInfo.getDeviceMemoryPool(device_id);
2206   hsa_status_t err = hsa_amd_memory_pool_allocate(MemoryPool, size, 0, &ptr);
2207   DP("Tgt alloc data %ld bytes, (tgt:%016llx).\n", size,
2208      (long long unsigned)(Elf64_Addr)ptr);
2209   ptr = (err == HSA_STATUS_SUCCESS) ? ptr : NULL;
2210   return ptr;
2211 }
2212 
2213 int32_t __tgt_rtl_data_submit(int device_id, void *tgt_ptr, void *hst_ptr,
2214                               int64_t size) {
2215   assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large");
2216   __tgt_async_info AsyncInfo;
2217   int32_t rc = dataSubmit(device_id, tgt_ptr, hst_ptr, size, &AsyncInfo);
2218   if (rc != OFFLOAD_SUCCESS)
2219     return OFFLOAD_FAIL;
2220 
2221   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
2222 }
2223 
2224 int32_t __tgt_rtl_data_submit_async(int device_id, void *tgt_ptr, void *hst_ptr,
2225                                     int64_t size, __tgt_async_info *AsyncInfo) {
2226   assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large");
2227   if (AsyncInfo) {
2228     initAsyncInfo(AsyncInfo);
2229     return dataSubmit(device_id, tgt_ptr, hst_ptr, size, AsyncInfo);
2230   } else {
2231     return __tgt_rtl_data_submit(device_id, tgt_ptr, hst_ptr, size);
2232   }
2233 }
2234 
2235 int32_t __tgt_rtl_data_retrieve(int device_id, void *hst_ptr, void *tgt_ptr,
2236                                 int64_t size) {
2237   assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large");
2238   __tgt_async_info AsyncInfo;
2239   int32_t rc = dataRetrieve(device_id, hst_ptr, tgt_ptr, size, &AsyncInfo);
2240   if (rc != OFFLOAD_SUCCESS)
2241     return OFFLOAD_FAIL;
2242 
2243   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
2244 }
2245 
2246 int32_t __tgt_rtl_data_retrieve_async(int device_id, void *hst_ptr,
2247                                       void *tgt_ptr, int64_t size,
2248                                       __tgt_async_info *AsyncInfo) {
2249   assert(AsyncInfo && "AsyncInfo is nullptr");
2250   assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large");
2251   initAsyncInfo(AsyncInfo);
2252   return dataRetrieve(device_id, hst_ptr, tgt_ptr, size, AsyncInfo);
2253 }
2254 
2255 int32_t __tgt_rtl_data_delete(int device_id, void *tgt_ptr) {
2256   assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large");
2257   hsa_status_t err;
2258   DP("Tgt free data (tgt:%016llx).\n", (long long unsigned)(Elf64_Addr)tgt_ptr);
2259   err = core::Runtime::Memfree(tgt_ptr);
2260   if (err != HSA_STATUS_SUCCESS) {
2261     DP("Error when freeing CUDA memory\n");
2262     return OFFLOAD_FAIL;
2263   }
2264   return OFFLOAD_SUCCESS;
2265 }
2266 
2267 int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
2268                                          void **tgt_args,
2269                                          ptrdiff_t *tgt_offsets,
2270                                          int32_t arg_num, int32_t num_teams,
2271                                          int32_t thread_limit,
2272                                          uint64_t loop_tripcount) {
2273 
2274   DeviceInfo.load_run_lock.lock_shared();
2275   int32_t res =
2276       runRegionLocked(device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
2277                       num_teams, thread_limit, loop_tripcount);
2278 
2279   DeviceInfo.load_run_lock.unlock_shared();
2280   return res;
2281 }
2282 
2283 int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
2284                                     void **tgt_args, ptrdiff_t *tgt_offsets,
2285                                     int32_t arg_num) {
2286   // use one team and one thread
2287   // fix thread num
2288   int32_t team_num = 1;
2289   int32_t thread_limit = 0; // use default
2290   return __tgt_rtl_run_target_team_region(device_id, tgt_entry_ptr, tgt_args,
2291                                           tgt_offsets, arg_num, team_num,
2292                                           thread_limit, 0);
2293 }
2294 
2295 int32_t __tgt_rtl_run_target_team_region_async(
2296     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
2297     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t num_teams,
2298     int32_t thread_limit, uint64_t loop_tripcount,
2299     __tgt_async_info *AsyncInfo) {
2300   assert(AsyncInfo && "AsyncInfo is nullptr");
2301   initAsyncInfo(AsyncInfo);
2302 
2303   DeviceInfo.load_run_lock.lock_shared();
2304   int32_t res =
2305       runRegionLocked(device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
2306                       num_teams, thread_limit, loop_tripcount);
2307 
2308   DeviceInfo.load_run_lock.unlock_shared();
2309   return res;
2310 }
2311 
2312 int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
2313                                           void *tgt_entry_ptr, void **tgt_args,
2314                                           ptrdiff_t *tgt_offsets,
2315                                           int32_t arg_num,
2316                                           __tgt_async_info *AsyncInfo) {
2317   // use one team and one thread
2318   // fix thread num
2319   int32_t team_num = 1;
2320   int32_t thread_limit = 0; // use default
2321   return __tgt_rtl_run_target_team_region_async(
2322       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
2323       thread_limit, 0, AsyncInfo);
2324 }
2325 
2326 int32_t __tgt_rtl_synchronize(int32_t device_id, __tgt_async_info *AsyncInfo) {
2327   assert(AsyncInfo && "AsyncInfo is nullptr");
2328 
2329   // Cuda asserts that AsyncInfo->Queue is non-null, but this invariant
2330   // is not ensured by devices.cpp for amdgcn
2331   // assert(AsyncInfo->Queue && "AsyncInfo->Queue is nullptr");
2332   if (AsyncInfo->Queue) {
2333     finiAsyncInfo(AsyncInfo);
2334   }
2335   return OFFLOAD_SUCCESS;
2336 }
2337 } // extern "C"
2338