1=============================
2Offloading Design & Internals
3=============================
4
5.. contents::
6   :local:
7
8Introduction
9============
10
11This document describes the Clang driver and code generation steps for creating
12offloading applications. Clang supports offloading to various architectures
13using programming models like CUDA, HIP, and OpenMP. The purpose of this
14document is to illustrate the steps necessary to create an offloading
15application using Clang.
16
17OpenMP Offloading
18=================
19
20.. note::
21   This documentation describes Clang's behavior using the new offloading driver
22   which. This currently must be enabled manually using ``-fopenmp-new-driver``.
23
24Clang supports OpenMP target offloading to several different architectures such
25as NVPTX, AMDGPU, X86_64, Arm, and PowerPC. Offloading code is generated by
26Clang and then executed using the ``libomptarget`` runtime and the associated
27plugin for the target architecture, e.g. ``libomptarget.rtl.cuda``. This section
28describes the steps necessary to create a functioning device image that can be
29loaded by the OpenMP runtime.  More information on the OpenMP runtimes can be
30found at the `OpenMP documentation page <https://openmp.llvm.org>`__.
31
32.. _Offloading Overview:
33
34Offloading Overview
35-------------------
36
37The goal of offloading compilation is to create an executable device image that
38can be run on the target device. OpenMP offloading creates executable images by
39compiling the input file for both the host and the target device. The output
40from the device phase then needs to be embedded into the host to create a fat
41object. A special tool then needs to extract the device code from the fat
42objects, run the device linking step, and embed the final image in a symbol the
43host can use to register the library and access the symbols on the device.
44
45Compilation Process
46^^^^^^^^^^^^^^^^^^^
47
48The compiler performs the following high-level actions to generate offloading
49code:
50
51* Compile the input file for the host to produce a bitcode file. Lower ``#pragma
52  omp target`` declarations to :ref:`offloading entries <Generating Offloading
53  Entries>` and create metadata to indicate which entries are on the device.
54* Compile the input file for the target :ref:`device <Device Compilation>` using
55  the :ref:`offloading entry <Generating Offloading Entries>` metadata created
56  by the host.
57* Link the OpenMP device runtime library and run the backend to create a device
58  object file.
59* Run the backend on the host bitcode file and create a :ref:`fat object file
60  <Creating Fat Objects>` using the device object file.
61* Pass the fat object file to the :ref:`linker wrapper tool <Device Linking>`
62  and extract the device objects. Run the device linking action on the extracted
63  objects.
64* :ref:`Wrap <Device Binary Wrapping>` the :ref:`device images <Device linking>`
65  and :ref:`offload entries <Generating Offloading Entries>` in a symbol that
66  can be accessed by the host.
67* Add the :ref:`wrapped binary <Device Binary Wrapping>` to the linker input and
68  run the host linking action. Link with ``libomptarget`` to register and
69  execute the images.
70
71   .. _Generating Offloading Entries:
72
73Generating Offloading Entries
74-----------------------------
75
76The first step in compilation is to generate offloading entries for the host.
77This information is used to identify function kernels or global values that will
78be provided by the device. Blocks contained in a ``#pragma omp target`` or
79symbols inside a ``#pragma omp declare target`` directive will have offloading
80entries generated. The following table shows the :ref:`offload entry structure
81<table-tgt_offload_entry_structure>`.
82
83  .. table:: __tgt_offload_entry Structure
84    :name: table-tgt_offload_entry_structure
85
86    +---------+------------+------------------------------------------------------------------------+
87    |   Type  | Identifier | Description                                                            |
88    +=========+============+========================================================================+
89    |  void*  |    addr    | Address of global symbol within device image (function or global)      |
90    +---------+------------+------------------------------------------------------------------------+
91    |  char*  |    name    | Name of the symbol                                                     |
92    +---------+------------+------------------------------------------------------------------------+
93    |  size_t |    size    | Size of the entry info (0 if it is a function)                         |
94    +---------+------------+------------------------------------------------------------------------+
95    | int32_t |    flags   | Flags associated with the entry (see :ref:`table-offload_entry_flags`) |
96    +---------+------------+------------------------------------------------------------------------+
97    | int32_t |  reserved  | Reserved, to be used by the runtime library.                           |
98    +---------+------------+------------------------------------------------------------------------+
99
100The address of the global symbol will be set to the appropriate value by the
101runtime once the device image is loaded. The flags are set to indicate the
102handling required for the offloading entry. If the offloading entry is an entry
103to a target region it can have one of the following
104:ref:`entry flags <table-offload_entry_flags>`.
105
106  .. table:: Target Region Entry Flags
107    :name: table-offload_entry_flags
108
109    +----------------------------------+-------+-----------------------------------------+
110    |                Name              | Value | Description                             |
111    +==================================+=======+=========================================+
112    | OMPTargetRegionEntryTargetRegion | 0x00  | Mark the entry as generic target region |
113    +----------------------------------+-------+-----------------------------------------+
114    | OMPTargetRegionEntryCtor         | 0x02  | Mark the entry as a global constructor  |
115    +----------------------------------+-------+-----------------------------------------+
116    | OMPTargetRegionEntryDtor         | 0x04  | Mark the entry as a global destructor   |
117    +----------------------------------+-------+-----------------------------------------+
118
119If the offloading entry is a global variable, indicated by a non-zero size, it
120will instead have one of the following :ref:`global
121<table-offload_global_flags>` flags.
122
123  .. table:: Target Region Global
124    :name: table-offload_global_flags
125
126    +-----------------------------+-------+---------------------------------------------------------------+
127    |          Name               | Value | Description                                                   |
128    +=============================+=======+===============================================================+
129    | OMPTargetGlobalVarEntryTo   | 0x00  | Mark the entry as a 'to' attribute (w.r.t. the to clause)     |
130    +-----------------------------+-------+---------------------------------------------------------------+
131    | OMPTargetGlobalVarEntryLink | 0x01  | Mark the entry as a 'link' attribute (w.r.t. the link clause) |
132    +-----------------------------+-------+---------------------------------------------------------------+
133
134The target offload entries are used by the runtime to access the device kernels
135and globals that will be provided by the final device image. Each offloading
136entry is set to use the ``omp_offloading_entries`` section. When the final
137application is created the linker will provide the
138``__start_omp_offloading_entries`` and ``__stop_omp_offloading_entries`` symbols
139which are used to create the :ref:`final image <Device Binary Wrapping>`.
140
141This information is by the device compilation stage to determine which symbols
142need to be exported from the device. We use the ``omp_offload.info`` metadata
143node to pass this information device compilation stage.
144
145Accessing Entries on the Device
146^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
147
148Accessing the entries in the device is done using the address field in the
149:ref:`offload entry<table-tgt_offload_entry_structure>`. The runtime will set
150the address to the pointer associated with the device image during runtime
151initialization. This is used to call the corresponding kernel function when
152entering a ``#pragma omp target`` region. For variables, the runtime maintains a
153table mapping host pointers to device pointers. Global variables inside a
154``#pragma omp target reclare`` directive are first initialized to the host's
155address. Once the device address is initialized we insert it into the table to
156map the host address to the device address.
157
158Debugging Information
159^^^^^^^^^^^^^^^^^^^^^
160
161We generate structures to hold debugging information that is passed to
162``libomptarget``. This allows the front-end to generate information the runtime
163library uses for more informative error messages. This is done using the
164standard :ref:`identifier structure <table-ident_t_structure>` used in
165``libomp`` and ``libomptarget``. This is used to pass information and source
166locations to the runtime.
167
168  .. table:: ident_t Structure
169    :name: table-ident_t_structure
170
171    +---------+------------+-----------------------------------------------------------------------------+
172    |   Type  | Identifier | Description                                                                 |
173    +=========+============+=============================================================================+
174    | int32_t |  reserved  | Reserved, to be used by the runtime library.                                |
175    +---------+------------+-----------------------------------------------------------------------------+
176    | int32_t |   flags    | Flags used to indicate some features, mostly unused.                        |
177    +---------+------------+-----------------------------------------------------------------------------+
178    | int32_t |  reserved  | Reserved, to be used by the runtime library.                                |
179    +---------+------------+-----------------------------------------------------------------------------+
180    | int32_t |  reserved  | Reserved, to be used by the runtime library.                                |
181    +---------+------------+-----------------------------------------------------------------------------+
182    |  char*  |  psource   | Program source information, stored as ";filename;function;line;column;;\\0" |
183    +---------+------------+-----------------------------------------------------------------------------+
184
185If debugging information is enabled, we will also create strings to indicate the
186names and declarations of variables mapped in target regions. These have the
187same format as the source location in the :ref:`identifier structure
188<table-ident_t_structure>`, but the filename is replaced with the variable name.
189
190.. _Device Compilation:
191
192Offload Device Compilation
193--------------------------
194
195The input file is compiled for each active device toolchain. The device
196compilation stage is performed differently from the host stage. Namely, we do
197not generate any offloading entries. This is set by passing the
198``-fopenmp-is-device`` flag to the front-end. We use the host bitcode to
199determine which symbols to export from the device. The bitcode file is passed in
200from the previous stage using the ``-fopenmp-host-ir-file-path`` flag.
201Compilation is otherwise performed as it would be for any other target triple.
202
203When compiling for the OpenMP device, we set the visibility of all device
204symbols to be ``protected`` by default. This improves performance and prevents a
205class of errors where a symbol in the target device could preempt a host
206library.
207
208The OpenMP runtime library is linked in during compilation to provide the
209implementations for standard OpenMP functionality. For GPU targets this is done
210by linking in a special bitcode library during compilation, (e.g.
211``libomptarget-nvptx64-sm_70.bc``) using the ``-mlink-builtin-bitcode`` flag.
212Other device libraries, such as CUDA's libdevice, are also linked this way. If
213the target is a standard architecture with an existing ``libomp``
214implementation, that will be linked instead. Finally, device tools are used to
215create a relocatable device object file that can be embedded in the host.
216
217.. _Creating Fat Objects:
218
219Creating Fat Objects
220--------------------
221
222A fat binary is a binary file that contains information intended for another
223device. We create a fat object by embedding the output of the device compilation
224stage into the host as a named section. The output from the device compilation
225is passed to the host backend using the ``-fembed-offload-object`` flag. This
226inserts the object as a global in the host's IR. The section name contains the
227target triple and architecture that the data corresponds to for later use.
228Typically we will also add an extra string to the section name to prevent it
229from being merged with other sections if the user performs relocatable linking
230on the object.
231
232.. code-block:: llvm
233
234  @llvm.embedded.object = private constant [1 x i8] c"\00", section ".llvm.offloading.nvptx64.sm_70."
235
236The device code will then be placed in the corresponding section one the backend
237is run on the host, creating a fat object. Using fat objects allows us to treat
238offloading objects as standard host objects. The final object file should
239contain the following :ref:`offloading sections <table-offloading_sections>`. We
240will use this information when :ref:`Device Linking`.
241
242  .. table:: Offloading Sections
243    :name: table-offloading_sections
244
245    +----------------------------------+--------------------------------------------------------------------+
246    |             Section              | Description                                                        |
247    +==================================+====================================================================+
248    | omp_offloading_entries           | Offloading entry information (see :ref:`table-tgt_offload_entry`)  |
249    +----------------------------------+--------------------------------------------------------------------+
250    | .llvm.offloading.<triple>.<arch> | Embedded device object file for the target device and architecture |
251    +----------------------------------+--------------------------------------------------------------------+
252
253.. _Device Linking:
254
255Linking Target Device Code
256--------------------------
257
258Objects containing :ref:`table-offloading_sections` require special handling to
259create an executable device image. This is done using a Clang tool, see
260:doc:`ClangLinkerWrapper` for more information. This tool works as a wrapper
261over the host linking job. It scans the input object files for the offloading
262sections and runs the appropriate device linking action. The linked device image
263is then :ref:`wrapped <Device Binary Wrapping>` to create the symbols used to load the
264device image and link it with the host.
265
266The linker wrapper tool supports linking bitcode files through link time
267optimization (LTO). This is used whenever the object files embedded in the host
268contain LLVM bitcode. Bitcode will be embedded for architectures that do not
269support a relocatable object format, such as AMDGPU or SPIR-V, or if the user
270passed in ``-foffload-lto``.
271
272.. _Device Binary Wrapping:
273
274Device Binary Wrapping
275----------------------
276
277Various structures and functions are used to create the information necessary to
278offload code on the device. We use the :ref:`linked device executable <Device
279Linking>` with the corresponding offloading entries to create the symbols
280necessary to load and execute the device image.
281
282Structure Types
283^^^^^^^^^^^^^^^
284
285Several different structures are used to store offloading information. The
286:ref:`device image structure <table-device_image_structure>` stores a single
287linked device image and its associated offloading entries. The offloading
288entries are stored using the ``__start_omp_offloading_entries`` and
289``__stop_omp_offloading_entries`` symbols generated by the linker using the
290:ref:`table-tgt_offload_entry`.
291
292  .. table:: __tgt_device_image Structure
293    :name: table-device_image_structure
294
295    +----------------------+--------------+----------------------------------------+
296    |         Type         |  Identifier  | Description                            |
297    +======================+==============+========================================+
298    |         void*        |  ImageStart  | Pointer to the target code start       |
299    +----------------------+--------------+----------------------------------------+
300    |         void*        |   ImageEnd   | Pointer to the target code end         |
301    +----------------------+--------------+----------------------------------------+
302    | __tgt_offload_entry* | EntriesBegin | Begin of table with all target entries |
303    +----------------------+--------------+----------------------------------------+
304    | __tgt_offload_entry* |  EntriesEnd  | End of table (non inclusive)           |
305    +----------------------+--------------+----------------------------------------+
306
307The target :ref:`target binary descriptor <table-target_binary_descriptor>` is
308used to store all binary images and offloading entries in an array.
309
310  .. table:: __tgt_bin_desc Structure
311    :name: table-target_binary_descriptor
312
313    +----------------------+------------------+------------------------------------------+
314    |         Type         |    Identifier    | Description                              |
315    +======================+==================+==========================================+
316    |        int32_t       |  NumDeviceImages | Number of device types supported         |
317    +----------------------+------------------+------------------------------------------+
318    |  __tgt_device_image* |   DeviceImages   | Array of device images (1 per dev. type) |
319    +----------------------+------------------+------------------------------------------+
320    | __tgt_offload_entry* | HostEntriesBegin | Begin of table with all host entries     |
321    +----------------------+------------------+------------------------------------------+
322    | __tgt_offload_entry* |  HostEntriesEnd  | End of table (non inclusive)             |
323    +----------------------+------------------+------------------------------------------+
324
325Global Variables
326----------------
327
328:ref:`table-global_variables` lists various global variables, along with their
329type and their explicit ELF sections, which are used to store device images and
330related symbols.
331
332  .. table:: Global Variables
333    :name: table-global_variables
334
335    +--------------------------------+---------------------+-------------------------+---------------------------------------------------------+
336    |            Variable            |         Type        |       ELF Section       |                    Description                          |
337    +================================+=====================+=========================+=========================================================+
338    | __start_omp_offloading_entries | __tgt_offload_entry | .omp_offloading_entries | Begin symbol for the offload entries table.             |
339    +--------------------------------+---------------------+-------------------------+---------------------------------------------------------+
340    | __stop_omp_offloading_entries  | __tgt_offload_entry | .omp_offloading_entries | End symbol for the offload entries table.               |
341    +--------------------------------+---------------------+-------------------------+---------------------------------------------------------+
342    | __dummy.omp_offloading.entry   | __tgt_offload_entry | .omp_offloading_entries | Dummy zero-sized object in the offload entries          |
343    |                                |                     |                         | section to force linker to define begin/end             |
344    |                                |                     |                         | symbols defined above.                                  |
345    +--------------------------------+---------------------+-------------------------+---------------------------------------------------------+
346    | .omp_offloading.device_image   |  __tgt_device_image | .omp_offloading_entries | ELF device code object of the first image.              |
347    +--------------------------------+---------------------+-------------------------+---------------------------------------------------------+
348    | .omp_offloading.device_image.N |  __tgt_device_image | .omp_offloading_entries | ELF device code object of the (N+1)th image.            |
349    +--------------------------------+---------------------+-------------------------+---------------------------------------------------------+
350    | .omp_offloading.device_images  |  __tgt_device_image | .omp_offloading_entries | Array of images.                                        |
351    +--------------------------------+---------------------+-------------------------+---------------------------------------------------------+
352    | .omp_offloading.descriptor     | __tgt_bin_desc      | .omp_offloading_entries | Binary descriptor object (see :ref:`binary_descriptor`) |
353    +--------------------------------+---------------------+-------------------------+---------------------------------------------------------+
354
355.. _binary_descriptor:
356
357Binary Descriptor for Device Images
358^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
359
360This object is passed to the offloading runtime at program startup and it
361describes all device images available in the executable or shared library. It
362is defined as follows:
363
364.. code-block:: c
365
366  __attribute__((visibility("hidden")))
367  extern __tgt_offload_entry *__start_omp_offloading_entries;
368  __attribute__((visibility("hidden")))
369  extern __tgt_offload_entry *__stop_omp_offloading_entries;
370  static const char Image0[] = { <Bufs.front() contents> };
371  ...
372  static const char ImageN[] = { <Bufs.back() contents> };
373  static const __tgt_device_image Images[] = {
374    {
375      Image0,                            /*ImageStart*/
376      Image0 + sizeof(Image0),           /*ImageEnd*/
377      __start_omp_offloading_entries,    /*EntriesBegin*/
378      __stop_omp_offloading_entries      /*EntriesEnd*/
379    },
380    ...
381    {
382      ImageN,                            /*ImageStart*/
383      ImageN + sizeof(ImageN),           /*ImageEnd*/
384      __start_omp_offloading_entries,    /*EntriesBegin*/
385      __stop_omp_offloading_entries      /*EntriesEnd*/
386    }
387  };
388  static const __tgt_bin_desc BinDesc = {
389    sizeof(Images) / sizeof(Images[0]),  /*NumDeviceImages*/
390    Images,                              /*DeviceImages*/
391    __start_omp_offloading_entries,      /*HostEntriesBegin*/
392    __stop_omp_offloading_entries        /*HostEntriesEnd*/
393  };
394
395Global Constructor and Destructor
396^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
397
398The global constructor (``.omp_offloading.descriptor_reg()``) registers the
399device images with the runtime by calling the ``__tgt_register_lib()`` runtime
400function. The constructor is explicitly defined in ``.text.startup`` section and
401is run once when the program starts. Similarly, the global destructor
402(``.omp_offloading.descriptor_unreg()``) calls ``__tgt_unregister_lib()`` for
403the destructor and is also defined in ``.text.startup`` section and run when the
404program exits.
405
406Offloading Example
407------------------
408
409This section contains a simple example of generating offloading code using
410OpenMP offloading. We will use a simple ``ZAXPY`` BLAS routine.
411
412.. code-block:: c++
413
414    #include <complex>
415
416    using complex = std::complex<double>;
417
418    void zaxpy(complex *X, complex *Y, complex D, std::size_t N) {
419    #pragma omp target teams distribute parallel for
420      for (std::size_t i = 0; i < N; ++i)
421        Y[i] = D * X[i] + Y[i];
422    }
423
424    int main() {
425      const std::size_t N = 1024;
426      complex X[N], Y[N], D;
427    #pragma omp target data map(to:X[0 : N]) map(tofrom:Y[0 : N])
428      zaxpy(X, Y, D, N);
429    }
430
431This code is compiled using the following Clang flags.
432
433.. code-block:: console
434
435    $ clang++ -fopenmp -fopenmp-targets=nvptx64 -O3 zaxpy.cpp -c
436
437The output section in the object file can be seen using the ``readelf`` utility
438
439.. code-block:: text
440
441  $ llvm-readelf -WS zaxpy.o
442  [Nr] Name                                       Type
443  ...
444  [34] omp_offloading_entries                     PROGBITS
445  [35] .llvm.offloading.nvptx64-nvidia-cuda.sm_70 PROGBITS
446
447Compiling this file again will invoke the ``clang-linker-wrapper`` utility to
448extract and link the device code stored at the section named
449``.llvm.offloading.nvptx64-nvidia-cuda.sm_70`` and then use entries stored in
450the section named ``omp_offloading_entries`` to create the symbols necessary for
451``libomptarget`` to register the device image and call the entry function.
452
453.. code-block:: console
454
455    $ clang++ -fopenmp -fopenmp-targets=nvptx64 zaxpy.o -o zaxpy
456    $ ./zaxpy
457
458We can see the steps created by clang to generate the offloading code using the
459``-ccc-print-phases`` option in Clang. This matches the description in
460:ref:`Offloading Overview`.
461
462.. code-block:: console
463
464    $ clang++ -fopenmp -fopenmp-targets=nvptx64 -ccc-print-phases zaxpy.cpp
465    # "x86_64-unknown-linux-gnu" - "clang", inputs: ["zaxpy.cpp"], output: "/tmp/zaxpy-host.bc"
466    # "nvptx64-nvidia-cuda" - "clang", inputs: ["zaxpy.cpp", "/tmp/zaxpy-e6a41b.bc"], output: "/tmp/zaxpy-07f434.s"
467    # "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["/tmp/zaxpy-07f434.s"], output: "/tmp/zaxpy-0af7b7.o"
468    # "x86_64-unknown-linux-gnu" - "clang", inputs: ["/tmp/zaxpy-e6a41b.bc", "/tmp/zaxpy-0af7b7.o"], output: "/tmp/zaxpy-416cad.o"
469    # "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["/tmp/zaxpy-416cad.o"], output: "a.out"
470