1 //===----------- rtl.cpp - Target independent OpenMP target RTL -----------===//
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 // Functionality for handling RTL plugins.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "rtl.h"
14 #include "device.h"
15 #include "private.h"
16 
17 #if OMPT_SUPPORT
18 #include "ompt-target.h"
19 #endif
20 
21 #include <cassert>
22 #include <cstdlib>
23 #include <cstring>
24 #include <dlfcn.h>
25 #include <mutex>
26 #include <string>
27 
28 // List of all plugins that can support offloading.
29 static const char *RTLNames[] = {
30     /* PowerPC target       */ "libomptarget.rtl.ppc64.so",
31     /* x86_64 target        */ "libomptarget.rtl.x86_64.so",
32     /* CUDA target          */ "libomptarget.rtl.cuda.so",
33     /* AArch64 target       */ "libomptarget.rtl.aarch64.so",
34     /* SX-Aurora VE target  */ "libomptarget.rtl.ve.so",
35     /* AMDGPU target        */ "libomptarget.rtl.amdgpu.so",
36     /* Remote target        */ "libomptarget.rtl.rpc.so",
37 };
38 
39 PluginManager *PM;
40 
41 #if OMPTARGET_PROFILE_ENABLED
42 static char *ProfileTraceFile = nullptr;
43 #endif
44 
45 __attribute__((constructor(101))) void init() {
46   DP("Init target library!\n");
47   PM = new PluginManager();
48 
49 #ifdef OMPTARGET_PROFILE_ENABLED
50   ProfileTraceFile = getenv("LIBOMPTARGET_PROFILE");
51   // TODO: add a configuration option for time granularity
52   if (ProfileTraceFile)
53     llvm::timeTraceProfilerInitialize(500 /* us */, "libomptarget");
54 #endif
55 }
56 
57 __attribute__((destructor(101))) void deinit() {
58   DP("Deinit target library!\n");
59   delete PM;
60 
61 #ifdef OMPTARGET_PROFILE_ENABLED
62   if (ProfileTraceFile) {
63     // TODO: add env var for file output
64     if (auto E = llvm::timeTraceProfilerWrite(ProfileTraceFile, "-"))
65       fprintf(stderr, "Error writing out the time trace\n");
66 
67     llvm::timeTraceProfilerCleanup();
68   }
69 #endif
70 }
71 
72 void RTLsTy::LoadRTLs() {
73   // Parse environment variable OMP_TARGET_OFFLOAD (if set)
74   PM->TargetOffloadPolicy =
75       (kmp_target_offload_kind_t)__kmpc_get_target_offload();
76   if (PM->TargetOffloadPolicy == tgt_disabled) {
77     return;
78   }
79 
80   DP("Loading RTLs...\n");
81 
82   // Attempt to open all the plugins and, if they exist, check if the interface
83   // is correct and if they are supporting any devices.
84   for (auto *Name : RTLNames) {
85     DP("Loading library '%s'...\n", Name);
86     void *dynlib_handle = dlopen(Name, RTLD_NOW);
87 
88     if (!dynlib_handle) {
89       // Library does not exist or cannot be found.
90       DP("Unable to load library '%s': %s!\n", Name, dlerror());
91       continue;
92     }
93 
94     DP("Successfully loaded library '%s'!\n", Name);
95 
96     AllRTLs.emplace_back();
97 
98     // Retrieve the RTL information from the runtime library.
99     RTLInfoTy &R = AllRTLs.back();
100 
101     bool ValidPlugin = true;
102 
103     if (!(*((void **)&R.is_valid_binary) =
104               dlsym(dynlib_handle, "__tgt_rtl_is_valid_binary")))
105       ValidPlugin = false;
106     if (!(*((void **)&R.number_of_devices) =
107               dlsym(dynlib_handle, "__tgt_rtl_number_of_devices")))
108       ValidPlugin = false;
109     if (!(*((void **)&R.init_device) =
110               dlsym(dynlib_handle, "__tgt_rtl_init_device")))
111       ValidPlugin = false;
112     if (!(*((void **)&R.load_binary) =
113               dlsym(dynlib_handle, "__tgt_rtl_load_binary")))
114       ValidPlugin = false;
115     if (!(*((void **)&R.data_alloc) =
116               dlsym(dynlib_handle, "__tgt_rtl_data_alloc")))
117       ValidPlugin = false;
118     if (!(*((void **)&R.data_submit) =
119               dlsym(dynlib_handle, "__tgt_rtl_data_submit")))
120       ValidPlugin = false;
121     if (!(*((void **)&R.data_retrieve) =
122               dlsym(dynlib_handle, "__tgt_rtl_data_retrieve")))
123       ValidPlugin = false;
124     if (!(*((void **)&R.data_delete) =
125               dlsym(dynlib_handle, "__tgt_rtl_data_delete")))
126       ValidPlugin = false;
127     if (!(*((void **)&R.run_region) =
128               dlsym(dynlib_handle, "__tgt_rtl_run_target_region")))
129       ValidPlugin = false;
130     if (!(*((void **)&R.run_team_region) =
131               dlsym(dynlib_handle, "__tgt_rtl_run_target_team_region")))
132       ValidPlugin = false;
133 
134     // Invalid plugin
135     if (!ValidPlugin) {
136       DP("Invalid plugin as necessary interface is not found.\n");
137       AllRTLs.pop_back();
138       continue;
139     }
140 
141     // No devices are supported by this RTL?
142     if (!(R.NumberOfDevices = R.number_of_devices())) {
143       // The RTL is invalid! Will pop the object from the RTLs list.
144       DP("No devices supported in this RTL\n");
145       AllRTLs.pop_back();
146       continue;
147     }
148 
149     R.LibraryHandler = dynlib_handle;
150 
151 #ifdef OMPTARGET_DEBUG
152     R.RTLName = Name;
153 #endif
154 
155     DP("Registering RTL %s supporting %d devices!\n", R.RTLName.c_str(),
156        R.NumberOfDevices);
157 
158     // Optional functions
159     *((void **)&R.init_requires) =
160         dlsym(dynlib_handle, "__tgt_rtl_init_requires");
161     *((void **)&R.data_submit_async) =
162         dlsym(dynlib_handle, "__tgt_rtl_data_submit_async");
163     *((void **)&R.data_retrieve_async) =
164         dlsym(dynlib_handle, "__tgt_rtl_data_retrieve_async");
165     *((void **)&R.run_region_async) =
166         dlsym(dynlib_handle, "__tgt_rtl_run_target_region_async");
167     *((void **)&R.run_team_region_async) =
168         dlsym(dynlib_handle, "__tgt_rtl_run_target_team_region_async");
169     *((void **)&R.synchronize) = dlsym(dynlib_handle, "__tgt_rtl_synchronize");
170     *((void **)&R.data_exchange) =
171         dlsym(dynlib_handle, "__tgt_rtl_data_exchange");
172     *((void **)&R.data_exchange_async) =
173         dlsym(dynlib_handle, "__tgt_rtl_data_exchange_async");
174     *((void **)&R.is_data_exchangable) =
175         dlsym(dynlib_handle, "__tgt_rtl_is_data_exchangable");
176     *((void **)&R.register_lib) =
177         dlsym(dynlib_handle, "__tgt_rtl_register_lib");
178     *((void **)&R.unregister_lib) =
179         dlsym(dynlib_handle, "__tgt_rtl_unregister_lib");
180     *((void **)&R.supports_empty_images) =
181         dlsym(dynlib_handle, "__tgt_rtl_supports_empty_images");
182     *((void **)&R.set_info_flag) =
183         dlsym(dynlib_handle, "__tgt_rtl_set_info_flag");
184     *((void **)&R.print_device_info) =
185         dlsym(dynlib_handle, "__tgt_rtl_print_device_info");
186   }
187 
188 #if OMPT_SUPPORT
189   DP("OMPT_SUPPORT is enabled in libomptarget\n");
190   DP("Init OMPT for libomptarget\n");
191   if (libomp_start_tool) {
192     DP("Retrieve libomp_start_tool successfully\n");
193     if (!libomp_start_tool(&ompt_target_enabled)) {
194       DP("Turn off OMPT in libomptarget because libomp_start_tool returns "
195          "false\n");
196       memset(&ompt_target_enabled, 0, sizeof(ompt_target_enabled));
197     }
198   }
199 #endif
200 
201   DP("RTLs loaded!\n");
202 
203   return;
204 }
205 
206 ////////////////////////////////////////////////////////////////////////////////
207 // Functionality for registering libs
208 
209 static void RegisterImageIntoTranslationTable(TranslationTable &TT,
210                                               RTLInfoTy &RTL,
211                                               __tgt_device_image *image) {
212 
213   // same size, as when we increase one, we also increase the other.
214   assert(TT.TargetsTable.size() == TT.TargetsImages.size() &&
215          "We should have as many images as we have tables!");
216 
217   // Resize the Targets Table and Images to accommodate the new targets if
218   // required
219   unsigned TargetsTableMinimumSize = RTL.Idx + RTL.NumberOfDevices;
220 
221   if (TT.TargetsTable.size() < TargetsTableMinimumSize) {
222     TT.TargetsImages.resize(TargetsTableMinimumSize, 0);
223     TT.TargetsTable.resize(TargetsTableMinimumSize, 0);
224   }
225 
226   // Register the image in all devices for this target type.
227   for (int32_t i = 0; i < RTL.NumberOfDevices; ++i) {
228     // If we are changing the image we are also invalidating the target table.
229     if (TT.TargetsImages[RTL.Idx + i] != image) {
230       TT.TargetsImages[RTL.Idx + i] = image;
231       TT.TargetsTable[RTL.Idx + i] = 0; // lazy initialization of target table.
232     }
233   }
234 }
235 
236 ////////////////////////////////////////////////////////////////////////////////
237 // Functionality for registering Ctors/Dtors
238 
239 static void RegisterGlobalCtorsDtorsForImage(__tgt_bin_desc *desc,
240                                              __tgt_device_image *img,
241                                              RTLInfoTy *RTL) {
242 
243   for (int32_t i = 0; i < RTL->NumberOfDevices; ++i) {
244     DeviceTy &Device = PM->Devices[RTL->Idx + i];
245     Device.PendingGlobalsMtx.lock();
246     Device.HasPendingGlobals = true;
247     for (__tgt_offload_entry *entry = img->EntriesBegin;
248          entry != img->EntriesEnd; ++entry) {
249       if (entry->flags & OMP_DECLARE_TARGET_CTOR) {
250         DP("Adding ctor " DPxMOD " to the pending list.\n",
251            DPxPTR(entry->addr));
252         Device.PendingCtorsDtors[desc].PendingCtors.push_back(entry->addr);
253       } else if (entry->flags & OMP_DECLARE_TARGET_DTOR) {
254         // Dtors are pushed in reverse order so they are executed from end
255         // to beginning when unregistering the library!
256         DP("Adding dtor " DPxMOD " to the pending list.\n",
257            DPxPTR(entry->addr));
258         Device.PendingCtorsDtors[desc].PendingDtors.push_front(entry->addr);
259       }
260 
261       if (entry->flags & OMP_DECLARE_TARGET_LINK) {
262         DP("The \"link\" attribute is not yet supported!\n");
263       }
264     }
265     Device.PendingGlobalsMtx.unlock();
266   }
267 }
268 
269 void RTLsTy::RegisterRequires(int64_t flags) {
270   // TODO: add more elaborate check.
271   // Minimal check: only set requires flags if previous value
272   // is undefined. This ensures that only the first call to this
273   // function will set the requires flags. All subsequent calls
274   // will be checked for compatibility.
275   assert(flags != OMP_REQ_UNDEFINED &&
276          "illegal undefined flag for requires directive!");
277   if (RequiresFlags == OMP_REQ_UNDEFINED) {
278     RequiresFlags = flags;
279     return;
280   }
281 
282   // If multiple compilation units are present enforce
283   // consistency across all of them for require clauses:
284   //  - reverse_offload
285   //  - unified_address
286   //  - unified_shared_memory
287   if ((RequiresFlags & OMP_REQ_REVERSE_OFFLOAD) !=
288       (flags & OMP_REQ_REVERSE_OFFLOAD)) {
289     FATAL_MESSAGE0(
290         1, "'#pragma omp requires reverse_offload' not used consistently!");
291   }
292   if ((RequiresFlags & OMP_REQ_UNIFIED_ADDRESS) !=
293       (flags & OMP_REQ_UNIFIED_ADDRESS)) {
294     FATAL_MESSAGE0(
295         1, "'#pragma omp requires unified_address' not used consistently!");
296   }
297   if ((RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) !=
298       (flags & OMP_REQ_UNIFIED_SHARED_MEMORY)) {
299     FATAL_MESSAGE0(
300         1,
301         "'#pragma omp requires unified_shared_memory' not used consistently!");
302   }
303 
304   // TODO: insert any other missing checks
305 
306   DP("New requires flags %" PRId64 " compatible with existing %" PRId64 "!\n",
307      flags, RequiresFlags);
308 }
309 
310 void RTLsTy::initRTLonce(RTLInfoTy &R) {
311   // If this RTL is not already in use, initialize it.
312   if (!R.isUsed && R.NumberOfDevices != 0) {
313     // Initialize the device information for the RTL we are about to use.
314     DeviceTy device(&R);
315     size_t Start = PM->Devices.size();
316     PM->Devices.resize(Start + R.NumberOfDevices, device);
317     for (int32_t device_id = 0; device_id < R.NumberOfDevices; device_id++) {
318       // global device ID
319       PM->Devices[Start + device_id].DeviceID = Start + device_id;
320       // RTL local device ID
321       PM->Devices[Start + device_id].RTLDeviceID = device_id;
322     }
323 
324     // Initialize the index of this RTL and save it in the used RTLs.
325     R.Idx = (UsedRTLs.empty())
326                 ? 0
327                 : UsedRTLs.back()->Idx + UsedRTLs.back()->NumberOfDevices;
328     assert((size_t)R.Idx == Start &&
329            "RTL index should equal the number of devices used so far.");
330     R.isUsed = true;
331     UsedRTLs.push_back(&R);
332 
333     DP("RTL " DPxMOD " has index %d!\n", DPxPTR(R.LibraryHandler), R.Idx);
334   }
335 }
336 
337 void RTLsTy::initAllRTLs() {
338   for (auto &R : AllRTLs)
339     initRTLonce(R);
340 }
341 
342 void RTLsTy::RegisterLib(__tgt_bin_desc *desc) {
343   PM->RTLsMtx.lock();
344   // Register the images with the RTLs that understand them, if any.
345   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
346     // Obtain the image.
347     __tgt_device_image *img = &desc->DeviceImages[i];
348 
349     RTLInfoTy *FoundRTL = nullptr;
350 
351     // Scan the RTLs that have associated images until we find one that supports
352     // the current image.
353     for (auto &R : AllRTLs) {
354       if (!R.is_valid_binary(img)) {
355         DP("Image " DPxMOD " is NOT compatible with RTL %s!\n",
356            DPxPTR(img->ImageStart), R.RTLName.c_str());
357         continue;
358       }
359 
360       DP("Image " DPxMOD " is compatible with RTL %s!\n",
361          DPxPTR(img->ImageStart), R.RTLName.c_str());
362 
363       initRTLonce(R);
364 
365       // Initialize (if necessary) translation table for this library.
366       PM->TrlTblMtx.lock();
367       if (!PM->HostEntriesBeginToTransTable.count(desc->HostEntriesBegin)) {
368         PM->HostEntriesBeginRegistrationOrder.push_back(desc->HostEntriesBegin);
369         TranslationTable &TransTable =
370             (PM->HostEntriesBeginToTransTable)[desc->HostEntriesBegin];
371         TransTable.HostTable.EntriesBegin = desc->HostEntriesBegin;
372         TransTable.HostTable.EntriesEnd = desc->HostEntriesEnd;
373       }
374 
375       // Retrieve translation table for this library.
376       TranslationTable &TransTable =
377           (PM->HostEntriesBeginToTransTable)[desc->HostEntriesBegin];
378 
379       DP("Registering image " DPxMOD " with RTL %s!\n", DPxPTR(img->ImageStart),
380          R.RTLName.c_str());
381       RegisterImageIntoTranslationTable(TransTable, R, img);
382       PM->TrlTblMtx.unlock();
383       FoundRTL = &R;
384 
385       // Load ctors/dtors for static objects
386       RegisterGlobalCtorsDtorsForImage(desc, img, FoundRTL);
387 
388       // if an RTL was found we are done - proceed to register the next image
389       break;
390     }
391 
392     if (!FoundRTL) {
393       DP("No RTL found for image " DPxMOD "!\n", DPxPTR(img->ImageStart));
394     }
395   }
396   PM->RTLsMtx.unlock();
397 
398   DP("Done registering entries!\n");
399 }
400 
401 void RTLsTy::UnregisterLib(__tgt_bin_desc *desc) {
402   DP("Unloading target library!\n");
403 
404   PM->RTLsMtx.lock();
405   // Find which RTL understands each image, if any.
406   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
407     // Obtain the image.
408     __tgt_device_image *img = &desc->DeviceImages[i];
409 
410     RTLInfoTy *FoundRTL = NULL;
411 
412     // Scan the RTLs that have associated images until we find one that supports
413     // the current image. We only need to scan RTLs that are already being used.
414     for (auto *R : UsedRTLs) {
415 
416       assert(R->isUsed && "Expecting used RTLs.");
417 
418       if (!R->is_valid_binary(img)) {
419         DP("Image " DPxMOD " is NOT compatible with RTL " DPxMOD "!\n",
420            DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
421         continue;
422       }
423 
424       DP("Image " DPxMOD " is compatible with RTL " DPxMOD "!\n",
425          DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
426 
427       FoundRTL = R;
428 
429       // Execute dtors for static objects if the device has been used, i.e.
430       // if its PendingCtors list has been emptied.
431       for (int32_t i = 0; i < FoundRTL->NumberOfDevices; ++i) {
432         DeviceTy &Device = PM->Devices[FoundRTL->Idx + i];
433         Device.PendingGlobalsMtx.lock();
434         if (Device.PendingCtorsDtors[desc].PendingCtors.empty()) {
435           AsyncInfoTy AsyncInfo(Device);
436           for (auto &dtor : Device.PendingCtorsDtors[desc].PendingDtors) {
437             int rc = target(nullptr, Device, dtor, 0, nullptr, nullptr, nullptr,
438                             nullptr, nullptr, nullptr, 1, 1, true /*team*/,
439                             AsyncInfo);
440             if (rc != OFFLOAD_SUCCESS) {
441               DP("Running destructor " DPxMOD " failed.\n", DPxPTR(dtor));
442             }
443           }
444           // Remove this library's entry from PendingCtorsDtors
445           Device.PendingCtorsDtors.erase(desc);
446           // All constructors have been issued, wait for them now.
447           if (AsyncInfo.synchronize() != OFFLOAD_SUCCESS)
448             DP("Failed synchronizing destructors kernels.\n");
449         }
450         Device.PendingGlobalsMtx.unlock();
451       }
452 
453       DP("Unregistered image " DPxMOD " from RTL " DPxMOD "!\n",
454          DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
455 
456       break;
457     }
458 
459     // if no RTL was found proceed to unregister the next image
460     if (!FoundRTL) {
461       DP("No RTLs in use support the image " DPxMOD "!\n",
462          DPxPTR(img->ImageStart));
463     }
464   }
465   PM->RTLsMtx.unlock();
466   DP("Done unregistering images!\n");
467 
468   // Remove entries from PM->HostPtrToTableMap
469   PM->TblMapMtx.lock();
470   for (__tgt_offload_entry *cur = desc->HostEntriesBegin;
471        cur < desc->HostEntriesEnd; ++cur) {
472     PM->HostPtrToTableMap.erase(cur->addr);
473   }
474 
475   // Remove translation table for this descriptor.
476   auto TransTable =
477       PM->HostEntriesBeginToTransTable.find(desc->HostEntriesBegin);
478   if (TransTable != PM->HostEntriesBeginToTransTable.end()) {
479     DP("Removing translation table for descriptor " DPxMOD "\n",
480        DPxPTR(desc->HostEntriesBegin));
481     PM->HostEntriesBeginToTransTable.erase(TransTable);
482   } else {
483     DP("Translation table for descriptor " DPxMOD " cannot be found, probably "
484        "it has been already removed.\n",
485        DPxPTR(desc->HostEntriesBegin));
486   }
487 
488   PM->TblMapMtx.unlock();
489 
490   // TODO: Remove RTL and the devices it manages if it's not used anymore?
491   // TODO: Write some RTL->unload_image(...) function?
492 
493   DP("Done unregistering library!\n");
494 }
495