Debian Codegraph @

clang/docs/HIPSupport.rst

raw
1 .. raw:: html
2
3 <style type="text/css">
4 .none { background-color: #FFCCCC }
5 .part { background-color: #FFFF99 }
6 .good { background-color: #CCFF99 }
7 </style>
8
9 .. role:: none
10 .. role:: part
11 .. role:: good
12
13 .. contents::
14 :local:
15
16 =============
17 HIP Support
18 =============
19
20 HIP (Heterogeneous-Compute Interface for Portability) `<https://github.com/ROCm/HIP>`_ is
21 a C++ Runtime API and Kernel Language. It enables developers to create portable applications for
22 offloading computation to different hardware platforms from a single source code.
23
24 AMD GPU Support
25 ===============
26
27 Clang provides HIP support on AMD GPUs via the ROCm platform `<https://rocm.docs.amd.com/en/latest/#>`_.
28 The ROCm runtime forms the base for HIP host APIs, while HIP device APIs are realized through HIP header
29 files and the ROCm device library. The Clang driver uses the HIPAMD toolchain to compile HIP device code
30 to AMDGPU ISA via the AMDGPU backend, or SPIR-V via the workflow outlined below.
31 The compiled code is then bundled and embedded in the host executables.
32
33 Intel GPU Support
34 =================
35
36 Clang provides partial HIP support on Intel GPUs using the CHIP-Star project `<https://github.com/CHIP-SPV/chipStar>`_.
37 CHIP-Star implements the HIP runtime over oneAPI Level Zero or OpenCL runtime. The Clang driver uses the HIPSPV
38 toolchain to compile HIP device code into LLVM IR, which is subsequently translated to SPIR-V via the SPIR-V
39 backend or the out-of-tree LLVM-SPIRV translator. The SPIR-V is then bundled and embedded into the host executables.
40
41 .. note::
42 While Clang does not directly provide HIP support for NVIDIA GPUs and CPUs, these platforms are supported via other means:
43
44 - NVIDIA GPUs: HIP support is offered through the HIP project `<https://github.com/ROCm/HIP>`_, which provides a header-only library for translating HIP runtime APIs into CUDA runtime APIs. The code is subsequently compiled using NVIDIA's `nvcc`.
45
46 - CPUs: HIP support is available through the HIP-CPU runtime library `<https://github.com/ROCm/HIP-CPU>`_. This header-only library enables CPUs to execute unmodified HIP code.
47
48
49 Example Usage
50 =============
51
52 To compile a HIP program, use the following command:
53
54 .. code-block:: shell
55
56 clang++ -c --offload-arch=gfx906 -xhip sample.cpp -o sample.o
57
58 The ``-xhip`` option indicates that the source is a HIP program. If the file has a ``.hip`` extension,
59 Clang will automatically recognize it as a HIP program:
60
61 .. code-block:: shell
62
63 clang++ -c --offload-arch=gfx906 sample.hip -o sample.o
64
65 To link a HIP program, use this command:
66
67 .. code-block:: shell
68
69 clang++ --hip-link --offload-arch=gfx906 sample.o -o sample
70
71 In the above command, the ``--hip-link`` flag instructs Clang to link the HIP runtime library. However,
72 the use of this flag is unnecessary if a HIP input file is already present in your program.
73
74 For convenience, Clang also supports compiling and linking in a single step:
75
76 .. code-block:: shell
77
78 clang++ --offload-arch=gfx906 -xhip sample.cpp -o sample
79
80 In the above commands, ``gfx906`` is the GPU architecture that the code is being compiled for. The supported GPU
81 architectures can be found in the `AMDGPU Processor Table <https://llvm.org/docs/AMDGPUUsage.html#processors>`_.
82 Alternatively, you can use the ``amdgpu-arch`` tool that comes with Clang to list the GPU architecture on your system:
83
84 .. code-block:: shell
85
86 amdgpu-arch
87
88 You can use ``--offload-arch=native`` to automatically detect the GPU architectures on your system:
89
90 .. code-block:: shell
91
92 clang++ --offload-arch=native -xhip sample.cpp -o sample
93
94
95 Path Setting for Dependencies
96 =============================
97
98 Compiling a HIP program depends on the HIP runtime and device library. The paths to the HIP runtime and device libraries
99 can be specified either using compiler options or environment variables. The paths can also be set through the ROCm path
100 if they follow the ROCm installation directory structure.
101
102 Order of Precedence for HIP Path
103 --------------------------------
104
105 1. ``--hip-path`` compiler option
106 2. ``HIP_PATH`` environment variable *(use with caution)*
107 3. ``--rocm-path`` compiler option
108 4. ``ROCM_PATH`` environment variable *(use with caution)*
109 5. Default automatic detection (relative to Clang or at the default ROCm installation location)
110
111 Order of Precedence for Device Library Path
112 -------------------------------------------
113
114 1. ``--hip-device-lib-path`` compiler option
115 2. ``HIP_DEVICE_LIB_PATH`` environment variable *(use with caution)*
116 3. ``--rocm-path`` compiler option
117 4. ``ROCM_PATH`` environment variable *(use with caution)*
118 5. Default automatic detection (relative to Clang or at the default ROCm installation location)
119
120 .. list-table::
121 :header-rows: 1
122
123 * - Compiler Option
124 - Environment Variable
125 - Description
126 - Default Value
127 * - ``--rocm-path=<path>``
128 - ``ROCM_PATH``
129 - Specifies the ROCm installation path.
130 - Automatic detection
131 * - ``--hip-path=<path>``
132 - ``HIP_PATH``
133 - Specifies the HIP runtime installation path.
134 - Determined by ROCm directory structure
135 * - ``--hip-device-lib-path=<path>``
136 - ``HIP_DEVICE_LIB_PATH``
137 - Specifies the HIP device library installation path.
138 - Determined by ROCm directory structure
139
140 .. note::
141
142 We recommend using the compiler options as the primary method for specifying these paths. While the environment variables ``ROCM_PATH``, ``HIP_PATH``, and ``HIP_DEVICE_LIB_PATH`` are supported, their use can lead to implicit dependencies that might cause issues in the long run. Use them with caution.
143
144
145 Predefined Macros
146 =================
147
148 .. list-table::
149 :header-rows: 1
150
151 * - Macro
152 - Description
153 * - ``__CLANG_RDC__``
154 - Defined when Clang is compiling code in Relocatable Device Code (RDC) mode. RDC, enabled with the ``-fgpu-rdc`` compiler option, is necessary for linking device codes across translation units.
155 * - ``__HIP__``
156 - Defined when compiling with HIP language support, indicating that the code targets the HIP environment.
157 * - ``__HIPCC__``
158 - Alias to ``__HIP__``.
159 * - ``__HIP_DEVICE_COMPILE__``
160 - Defined during device code compilation in Clang's separate compilation process for the host and each offloading GPU architecture.
161 * - ``__HIP_MEMORY_SCOPE_SINGLETHREAD``
162 - Represents single-thread memory scope in HIP (value is 1).
163 * - ``__HIP_MEMORY_SCOPE_WAVEFRONT``
164 - Represents wavefront memory scope in HIP (value is 2).
165 * - ``__HIP_MEMORY_SCOPE_WORKGROUP``
166 - Represents workgroup memory scope in HIP (value is 3).
167 * - ``__HIP_MEMORY_SCOPE_CLUSTER``
168 - Represents cluster memory scope in HIP (value is 6).
169 * - ``__HIP_MEMORY_SCOPE_AGENT``
170 - Represents agent memory scope in HIP (value is 4).
171 * - ``__HIP_MEMORY_SCOPE_SYSTEM``
172 - Represents system-wide memory scope in HIP (value is 5).
173 * - ``__HIP_NO_IMAGE_SUPPORT__``
174 - Defined with a value of 1 when the target device lacks support for HIP image functions.
175 * - ``__HIP_NO_IMAGE_SUPPORT``
176 - Alias to ``__HIP_NO_IMAGE_SUPPORT__``. Deprecated.
177 * - ``__HIP_API_PER_THREAD_DEFAULT_STREAM__``
178 - Defined when the GPU default stream is set to per-thread mode.
179 * - ``HIP_API_PER_THREAD_DEFAULT_STREAM``
180 - Alias to ``__HIP_API_PER_THREAD_DEFAULT_STREAM__``. Deprecated.
181
182 Note that some architecture specific AMDGPU macros will have default values when
183 used from the HIP host compilation.
184
185 Compilation Modes
186 =================
187
188 Each HIP source file contains intertwined device and host code. Depending on the chosen compilation mode by the compiler options ``-fno-gpu-rdc`` and ``-fgpu-rdc``, these portions of code are compiled differently.
189
190 Device Code Compilation
191 -----------------------
192
193 **``-fno-gpu-rdc`` Mode (default)**:
194
195 - Compiles to a self-contained, fully linked offloading device binary for each offloading device architecture.
196 - Device code within a Translation Unit (TU) cannot call functions located in another TU.
197
198 **``-fgpu-rdc`` Mode**:
199
200 - Compiles to a bitcode for each GPU architecture.
201 - For each offloading device architecture, the bitcode from different TUs are linked together to create a single offloading device binary.
202 - Device code in one TU can call functions located in another TU.
203
204 Host Code Compilation
205 ---------------------
206
207 **Both Modes**:
208
209 - Compiles to a relocatable object for each TU.
210 - These relocatable objects are then linked together.
211 - Host code within a TU can call host functions and launch kernels from another TU.
212
213 HIP Fat Binary Registration and Unregistration
214 ==============================================
215
216 When compiling HIP for AMD GPUs, Clang embeds device code into HIP "fat
217 binaries" and generates host-side helper functions that register these
218 fat binaries with the HIP runtime at program start and unregister them at
219 program exit. In non-RDC mode (``-fno-gpu-rdc``), each compilation unit
220 typically produces its own HIP fat binary: a container that holds, for every
221 enabled GPU architecture, a fully linked offloading device image (for example,
222 a GPU code object) that can be loaded directly by the HIP runtime. In RDC mode
223 (``-fgpu-rdc``), each compilation unit contributes device code in a relocatable
224 form (for example, GPU object files or LLVM IR). A later device-link step links
225 those relocatable inputs into fully linked device images per GPU architecture
226 and then packages those images into a HIP fat binary container.
227
228 Registering a HIP fat binary allows the runtime to discover the kernels and
229 device variables defined in that container and to associate host-side addresses
230 and symbols with the corresponding GPU-side entities. For example, when a
231 host-side kernel launch stub is called, the HIP runtime uses information
232 established during registration (and the fat binary handle it returned) to
233 identify which GPU kernel symbol to launch from which device image.
234
235 At the LLVM IR level, Clang/LLVM typically create an internal module
236 constructor (for example ``__hip_module_ctor`` or a ``.hip.fatbin_reg``
237 function) and add it to ``@llvm.global_ctors``. This constructor is called by
238 the C runtime before ``main`` and it:
239
240 * calls ``__hipRegisterFatBinary`` with a pointer to an internal wrapper
241 object that describes the HIP fat binary;
242 * stores the returned handle in an internal global variable;
243 * calls an internal helper such as ``__hip_register_globals`` to register
244 kernels, device variables and other metadata associated with the fat binary;
245 * registers a corresponding module destructor with ``atexit`` so it will run
246 during program termination and use the stored handle to unregister the fat
247 binary from the HIP runtime.
248
249 The module destructor (for example ``__hip_module_dtor`` or a
250 ``.hip.fatbin_unreg`` function) loads the stored handle, checks that it is
251 non-null, calls ``__hipUnregisterFatBinary`` to unregister the fat binary from
252 the HIP runtime, and then clears the handle. This ensures that the HIP runtime
253 sees each fat binary registered exactly once and that it is unregistered once
254 at exit, even when multiple translation units contribute HIP kernels to the
255 same host program.
256
257 These registration/unregistration helpers are implementation details of Clang's
258 HIP code generation; user code should not call ``__hipRegisterFatBinary`` or
259 ``__hipUnregisterFatBinary`` directly.
260
261 Implications for HIP Application Developers
262 -------------------------------------------
263
264 From the point of view of HIP application code, Clang and the HIP runtime
265 provide the following guarantees:
266
267 * Kernels and device variables defined in HIP code will be registered with the
268 HIP runtime before ``main`` begins execution.
269 * Fat binaries will be unregistered via an ``atexit``-registered module
270 destructor after ``main`` returns (or after ``exit`` is called).
271
272 Beyond these points, the detailed ordering of fat binary registration and
273 unregistration relative to user-defined global constructors, destructors and
274 other ``atexit`` handlers is not specified and should not be relied upon.
275 Applications should avoid depending on HIP kernels or device variables being
276 usable from global constructors or destructors, and instead perform HIP
277 initialization and teardown that touches device state in ``main`` (or in
278 functions called from ``main``).
279
280 Implications for HIP Runtime Developers
281 ---------------------------------------
282
283 HIP runtime implementations that are linked with Clang-generated host code
284 must handle registration and unregistration in the presence of uncertain
285 global ctor/dtor ordering:
286
287 * ``__hipRegisterFatBinary`` must accept a pointer to the compiler-generated
288 wrapper object and return an opaque handle that remains valid for as long as
289 the fat binary may be used.
290 * ``__hipUnregisterFatBinary`` must accept the handle previously returned by
291 ``__hipRegisterFatBinary`` and perform any necessary cleanup. It may be
292 called late in process teardown, after other parts of the runtime have
293 started shutting down, so it should be robust in the presence of partially
294 torn-down state.
295 * Runtimes should use appropriate synchronization and guards so that fat
296 binary registration does not observe uninitialized resources and
297 unregistration does not release resources that are still required by other
298 runtime components. In particular, registration and unregistration routines
299 should be written to be safe under repeated calls and in the presence of
300 concurrent or overlapping initialization/teardown logic.
301
302 Syntax Difference with CUDA
303 ===========================
304
305 Clang's front end, used for both CUDA and HIP programming models, shares the same parsing and semantic analysis mechanisms. This includes the resolution of overloads concerning device and host functions. While there exists a comprehensive documentation on the syntax differences between Clang and NVCC for CUDA at `Dialect Differences Between Clang and NVCC <https://llvm.org/docs/CompileCudaWithLLVM.html#dialect-differences-between-clang-and-nvcc>`_, it is important to note that these differences also apply to HIP code compilation.
306
307 Predefined Macros for Differentiation
308 -------------------------------------
309
310 To facilitate differentiation between HIP and CUDA code, as well as between device and host compilations within HIP, Clang defines specific macros:
311
312 - ``__HIP__`` : This macro is defined only when compiling HIP code. It can be used to conditionally compile code specific to HIP, enabling developers to write portable code that can be compiled for both CUDA and HIP.
313
314 - ``__HIP_DEVICE_COMPILE__`` : Defined exclusively during HIP device compilation, this macro allows for conditional compilation of device-specific code. It provides a mechanism to segregate device and host code, ensuring that each can be optimized for their respective execution environments.
315
316 Function Pointers Support
317 =========================
318
319 Function pointers' support varies with the usage mode in Clang with HIP. The following table provides an overview of the support status across different use-cases and modes.
320
321 .. list-table:: Function Pointers Support Overview
322 :widths: 25 25 25
323 :header-rows: 1
324
325 * - Use Case
326 - ``-fno-gpu-rdc`` Mode (default)
327 - ``-fgpu-rdc`` Mode
328 * - Defined and used in the same TU
329 - Supported
330 - Supported
331 * - Defined in one TU and used in another TU
332 - Not Supported
333 - Supported
334
335 In the ``-fno-gpu-rdc`` mode, the compiler calculates the resource usage of kernels based only on functions present within the same TU. This mode does not support the use of function pointers defined in a different TU due to the possibility of incorrect resource usage calculations, leading to undefined behavior.
336
337 On the other hand, the ``-fgpu-rdc`` mode allows the definition and use of function pointers across different TUs, as resource usage calculations can accommodate functions from disparate TUs.
338
339 Virtual Function Support
340 ========================
341
342 In Clang with HIP, support for calling virtual functions of an object in device or host code is contingent on where the object is constructed.
343
344 - **Constructed in Device Code**: Virtual functions of an object can be called in device code on a specific offloading device if the object is constructed in device code on an offloading device with the same architecture.
345 - **Constructed in Host Code**: Virtual functions of an object can be called in host code if the object is constructed in host code.
346
347 In other scenarios, calling virtual functions is not allowed.
348
349 Explanation
350 -----------
351
352 An object constructed on the device side contains a pointer to the virtual function table on the device side, which is not accessible in host code, and vice versa. Thus, trying to invoke virtual functions from a context different from where the object was constructed will be disallowed because the appropriate virtual table cannot be accessed. The virtual function tables for offloading devices with different architectures are different, therefore trying to invoke virtual functions from an offloading device with a different architecture than where the object is constructed is also disallowed.
353
354 Example Usage
355 -------------
356
357 .. code-block:: c++
358
359 class Base {
360 public:
361 __device__ virtual void virtualFunction() {
362 // Base virtual function implementation
363 }
364 };
365
366 class Derived : public Base {
367 public:
368 __device__ void virtualFunction() override {
369 // Derived virtual function implementation
370 }
371 };
372
373 __global__ void kernel() {
374 Derived obj;
375 Base* basePtr = &obj;
376 basePtr->virtualFunction(); // Allowed since obj is constructed in device code
377 }
378
379 Alias Attribute Support
380 =======================
381
382 Clang supports alias attributes in HIP code, allowing creation of alternative names for functions and variables.
383 - Aliases work with ``__host__``, ``__device__``, and ``__host__ __device__`` functions and variables.
384 - The alias attribute uses the syntax ``__attribute__((alias("target_name")))``. Both weak and strong aliases are supported.
385 - Outside of ``extern "C"``, the alias target must use the mangled name of the aliasee
386 - The alias is only emitted if the aliasee is emitted on the same side (ie __host__ or __device__), otherwise it is ignored.
387
388 Example Usage
389 -------------
390
391 .. code-block:: c++
392
393 extern "C" {
394 // Host function alias
395 int __HostFunc(void) { return 0; }
396 int HostFunc(void) __attribute__((weak, alias("__HostFunc")));
397
398 // Device function alias
399 __device__ int __DeviceFunc(void) { return 1; }
400 __device__ int DeviceFunc(void) __attribute__((weak, alias("__DeviceFunc")));
401
402 // Host-device function alias
403 __host__ __device__ int __BothFunc(void) { return 2; }
404 __host__ __device__ int BothFunc(void) __attribute__((alias("__BothFunc")));
405
406 // Variable alias
407 int __host_var = 3;
408 extern int __attribute__((weak, alias("__host_var"))) host_var;
409 }
410 // Mangled / overload alias
411 __host__ __device__ float __Four(float f) { return 2.0f * f; }
412 __host__ __device__ int Four(void) __attribute__((weak, alias("_Z6__Fourv")));
413 __host__ __device__ float Four(float f) __attribute__((weak, alias("_Z6__Fourf")));
414
415 C++17 Class Template Argument Deduction (CTAD) Support
416 ======================================================
417
418 Clang supports C++17 Class Template Argument Deduction (CTAD) in both host and
419 device code for HIP. This allows you to omit template arguments when creating
420 class template instances, letting the compiler deduce them from constructor
421 arguments.
422
423 .. code-block:: c++
424
425 #include <tuple>
426
427 __host__ __device__ void func() {
428 std::tuple<int, int> t = std::tuple(1, 1);
429 }
430
431 In the above example, ``std::tuple(1, 1)`` automatically deduces the type to be
432 ``std::tuple<int, int>``.
433
434 Deduction Guides
435 ----------------
436
437 User-defined deduction guides are also supported. Since deduction guides are not
438 executable code and only participate in type deduction, they semantically behave
439 as ``__host__ __device__``. This ensures they are available for deduction in both
440 host and device contexts, and CTAD continues to respect any constraints on the
441 corresponding constructors in the usual C++ way.
442
443 .. code-block:: c++
444
445 template <typename T>
446 struct MyType {
447 T value;
448 __device__ MyType(T v) : value(v) {}
449 };
450
451 MyType(float) -> MyType<double>;
452
453 __device__ void deviceFunc() {
454 MyType m(1.0f); // Deduces MyType<double>
455 }
456
457 .. note::
458
459 Explicit HIP target attributes such as ``__host__`` or ``__device__``
460 are currently only permitted on deduction guides when both are present
461 (``__host__ __device__``). This usage is deprecated and will be rejected
462 in a future version of Clang; prefer omitting HIP target attributes on
463 deduction guides entirely. Clang treats all deduction guides as if they
464 were ``__host__ __device__``, so ``__host__``-only, ``__device__``-only,
465 or ``__global__`` deduction guides are rejected as ill-formed.
466
467 Host and Device Attributes of Default Destructors
468 ===================================================
469
470 If a default destructor does not have explicit host or device attributes,
471 clang infers these attributes based on the destructors of its data members
472 and base classes. If any conflicts are detected among these destructors,
473 clang diagnoses the issue. Otherwise, clang adds an implicit host or device
474 attribute according to whether the data members's and base classes's
475 destructors can execute on the host or device side.
476
477 For explicit template classes with virtual destructors, which must be emitted,
478 the inference adopts a conservative approach. In this case, implicit host or
479 device attributes from member and base class destructors are ignored. This
480 precaution is necessary because, although a constexpr destructor carries
481 implicit host or device attributes, a constexpr function may call a
482 non-constexpr function, which is by default a host function.
483
484 Users can override the inferred host and device attributes of default
485 destructors by adding explicit host and device attributes to them.
486
487 C++ Standard Parallelism Offload Support: Compiler And Runtime
488 ==============================================================
489
490 Introduction
491 ============
492
493 This section describes the implementation of support for offloading the
494 execution of standard C++ algorithms to accelerators that can be targeted via
495 HIP. Furthermore, it enumerates restrictions on user defined code, as well as
496 the interactions with runtimes.
497
498 Algorithm Offload: What, Why, Where
499 ===================================
500
501 C++17 introduced overloads
502 `for most algorithms in the standard library <https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0024r2.html>`_
503 which allow the user to specify a desired
504 `execution policy <https://en.cppreference.com/w/cpp/algorithm#Execution_policies>`_.
505 The `parallel_unsequenced_policy <https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t>`_
506 maps relatively well to the execution model of AMD GPUs. This, coupled with the
507 the availability and maturity of GPU accelerated algorithm libraries that
508 implement most / all corresponding algorithms in the standard library
509 (e.g. `rocThrust <https://github.com/ROCm/rocm-libraries/tree/develop/projects/rocthrust>`__), makes
510 it feasible to provide seamless accelerator offload for supported algorithms,
511 when an accelerated version exists. Thus, it becomes possible to easily access
512 the computational resources of an AMD accelerator, via a well specified,
513 familiar, algorithmic interface, without having to delve into low-level hardware
514 specific details. Putting it all together:
515
516 - **What**: standard library algorithms, when invoked with the
517 ``parallel_unsequenced_policy``
518 - **Why**: democratise AMDGPU accelerator programming, without loss of user
519 familiarity
520 - **Where**: only AMDGPU accelerators targeted by Clang/LLVM via HIP
521
522 Small Example
523 =============
524
525 Given the following C++ code:
526
527 .. code-block:: C++
528
529 bool has_the_answer(const std::vector<int>& v) {
530 return std::find(std::execution::par_unseq, std::cbegin(v), std::cend(v), 42) != std::cend(v);
531 }
532
533 if Clang is invoked with the ``--hipstdpar --offload-arch=foo`` flags, the call
534 to ``find`` will be offloaded to an accelerator that is part of the ``foo``
535 target family. If either ``foo`` or its runtime environment do not support
536 transparent on-demand paging (such as e.g. that provided in Linux via
537 `HMM <https://docs.kernel.org/mm/hmm.html>`_), it is necessary to also include
538 the ``--hipstdpar-interpose-alloc`` flag. If the accelerator specific algorithm
539 library ``foo`` uses doesn't have an implementation of a particular algorithm,
540 execution seamlessly falls back to the host CPU. It is legal to specify multiple
541 ``--offload-arch``\s. All the flags we introduce, as well as a thorough view of
542 various restrictions an their implementations, will be provided below.
543
544 Implementation - General View
545 =============================
546
547 We built support for Algorithm Offload support atop the pre-existing HIP
548 infrastructure. More specifically, when one requests offload via ``--hipstdpar``,
549 compilation is switched to HIP compilation, as if ``-x hip`` was specified.
550 Similarly, linking is also switched to HIP linking, as if ``--hip-link`` was
551 specified. Note that these are implicit, and one should not assume that any
552 interop with HIP specific language constructs is available e.g. ``__device__``
553 annotations are neither necessary nor guaranteed to work.
554
555 Since there are no language restriction mechanisms in place, it is necessary to
556 relax HIP language specific semantic checks performed by the FE; they would
557 identify otherwise valid, offloadable code, as invalid HIP code. Given that we
558 know that the user intended only for certain algorithms to be offloaded, and
559 encoded this by specifying the ``parallel_unsequenced_policy``, we rely on a
560 pass over IR to clean up any and all code that was not "meant" for offload. If
561 requested, allocation interposition is also handled via a separate pass over IR.
562
563 To interface with the client HIP runtime, and to forward offloaded algorithm
564 invocations to the corresponding accelerator specific library implementation, an
565 implementation detail forwarding header is implicitly included by the driver,
566 when compiling with ``--hipstdpar``. In what follows, we will delve into each
567 component that contributes to implementing Algorithm Offload support.
568
569 Implementation - Driver
570 =======================
571
572 We augment the ``clang`` driver with the following flags:
573
574 - ``--hipstdpar`` enables algorithm offload, which depending on phase, has the
575 following effects:
576
577 - when compiling:
578
579 - ``-x hip`` gets prepended to enable HIP support;
580 - the ``ROCmToolchain`` component checks for the ``hipstdpar_lib.hpp``
581 forwarding header,
582 `rocThrust <https://rocm.docs.amd.com/projects/rocThrust/en/latest/>`_ and
583 `rocPrim <https://rocm.docs.amd.com/projects/rocPRIM/en/latest/>`_ in
584 their canonical locations, which can be overriden via flags found below;
585 if all are found, the forwarding header gets implicitly included,
586 otherwise an error listing the missing component is generated;
587 - the ``LangOpts.HIPStdPar`` member is set.
588
589 - when linking:
590
591 - ``--hip-link`` and ``-frtlib-add-rpath`` gets appended to enable HIP
592 support.
593
594 - ``--hipstdpar-interpose-alloc`` enables the interposition of standard
595 allocation / deallocation functions with accelerator aware equivalents; the
596 ``LangOpts.HIPStdParInterposeAlloc`` member is set;
597 - ``--hipstdpar-path=`` specifies a non-canonical path for the forwarding
598 header; it must point to the folder where the header is located and not to the
599 header itself;
600 - ``--hipstdpar-thrust-path=`` specifies a non-canonical path for
601 `rocThrust <https://rocm.docs.amd.com/projects/rocThrust/en/latest/>`_; it
602 must point to the folder where the library is installed / built under a
603 ``/thrust`` subfolder;
604 - ``--hipstdpar-prim-path=`` specifies a non-canonical path for
605 `rocPrim <https://rocm.docs.amd.com/projects/rocPRIM/en/latest/>`_; it must
606 point to the folder where the library is installed / built under a
607 ``/rocprim`` subfolder;
608
609 The `--offload-arch <https://llvm.org/docs/AMDGPUUsage.html#amdgpu-processors>`_
610 flag can be used to specify the accelerator for which offload code is to be
611 generated.
612
613 Implementation - Front-End
614 ==========================
615
616 When ``LangOpts.HIPStdPar`` is set, we relax some of the HIP language specific
617 ``Sema`` checks to account for the fact that we want to consume pure unannotated
618 C++ code:
619
620 1. ``__device__`` / ``__host__ __device__`` functions (which would originate in
621 the accelerator specific algorithm library) are allowed to call implicitly
622 ``__host__`` functions;
623 2. ``__global__`` functions (which would originate in the accelerator specific
624 algorithm library) are allowed to call implicitly ``__host__`` functions;
625 3. resolving ``__builtin`` availability is deferred, because it is possible that
626 a ``__builtin`` that is unavailable on the target accelerator is not
627 reachable from any offloaded algorithm, and thus will be safely removed in
628 the middle-end;
629 4. ASM parsing / checking is deferred, because it is possible that an ASM block
630 that e.g. uses some constraints that are incompatible with the target
631 accelerator is not reachable from any offloaded algorithm, and thus will be
632 safely removed in the middle-end.
633
634 ``CodeGen`` is similarly relaxed, with implicitly ``__host__`` functions being
635 emitted as well.
636
637 Implementation - Middle-End
638 ===========================
639
640 We add two ``opt`` passes:
641
642 1. ``HipStdParAcceleratorCodeSelectionPass``
643
644 - For all kernels in a ``Module``, compute reachability, where a function
645 ``F`` is reachable from a kernel ``K`` if and only if there exists a direct
646 call-chain rooted in ``F`` that includes ``K``;
647 - Remove all functions that are not reachable from kernels;
648 - This pass is only run when compiling for the accelerator.
649
650 The first pass assumes that the only code that the user intended to offload was
651 that which was directly or transitively invocable as part of an algorithm
652 execution. It also assumes that an accelerator aware algorithm implementation
653 would rely on accelerator specific special functions (kernels), and that these
654 effectively constitute the only roots for accelerator execution graphs. Both of
655 these assumptions are based on observing how widespread accelerators,
656 such as GPUs, work.
657
658 1. ``HipStdParAllocationInterpositionPass``
659
660 - Iterate through all functions in a ``Module``, and replace standard
661 allocation / deallocation functions with accelerator-aware equivalents,
662 based on a pre-established table; the list of functions that can be
663 interposed is available
664 `here <https://github.com/ROCm/roc-stdpar#allocation--deallocation-interposition-status>`__;
665 - This is only run when compiling for the host.
666
667 The second pass is optional.
668
669 Implementation - Forwarding Header
670 ==================================
671
672 The forwarding header implements two pieces of functionality:
673
674 1. It forwards algorithms to a target accelerator, which is done by relying on
675 C++ language rules around overloading:
676
677 - overloads taking an explicit argument of type
678 ``parallel_unsequenced_policy`` are introduced into the ``std`` namespace;
679 - these will get preferentially selected versus the master template;
680 - the body forwards to the equivalent algorithm from the accelerator specific
681 library
682
683 2. It provides allocation / deallocation functions that are equivalent to the
684 standard ones, but obtain memory by invoking
685 `hipMallocManaged <https://rocm.docs.amd.com/projects/HIP/en/latest/.doxygen/docBin/html/group___memory_m.html#gab8cfa0e292193fa37e0cc2e4911fa90a>`_
686 and release it via `hipFree <https://rocm.docs.amd.com/projects/HIP/en/latest/.doxygen/docBin/html/group___memory.html#ga740d08da65cae1441ba32f8fedb863d1>`_.
687
688 Predefined Macros
689 =================
690
691 .. list-table::
692 :header-rows: 1
693
694 * - Macro
695 - Description
696 * - ``__HIPSTDPAR__``
697 - Defined when Clang is compiling code in algorithm offload mode, enabled
698 with the ``--hipstdpar`` compiler option.
699 * - ``__HIPSTDPAR_INTERPOSE_ALLOC__`` / ``__HIPSTDPAR_INTERPOSE_ALLOC_V1__``
700 - Defined only when compiling in algorithm offload mode, when the user
701 enables interposition mode with the ``--hipstdpar-interpose-alloc``
702 compiler option, indicating that all dynamic memory allocation /
703 deallocation functions should be replaced with accelerator aware
704 variants.
705
706 Restrictions
707 ============
708
709 We define two modes in which runtime execution can occur:
710
711 1. **HMM Mode** - this assumes that the
712 `HMM <https://docs.kernel.org/mm/hmm.html>`_ subsystem of the Linux kernel
713 is used to provide transparent on-demand paging i.e. memory obtained from a
714 system / OS allocator such as via a call to ``malloc`` or ``operator new`` is
715 directly accessible to the accelerator and it follows the C++ memory model;
716 2. **Interposition Mode** - this is a fallback mode for cases where transparent
717 on-demand paging is unavailable (e.g. in the Windows OS), which means that
718 memory must be allocated via an accelerator aware mechanism, and system
719 allocated memory is inaccessible for the accelerator.
720
721 The following restrictions imposed on user code apply to both modes:
722
723 1. Pointers to function, and all associated features, such as e.g. dynamic
724 polymorphism, cannot be used (directly or transitively) by the user provided
725 callable passed to an algorithm invocation;
726 2. ``static`` (except for program-wide unique ones) / ``thread`` storage
727 duration variables cannot be used (directly or transitively) in name by the
728 user provided callable;
729 3. User code must be compiled in ``-fgpu-rdc`` mode in order for global /
730 namespace scope variables / program-wide unique ``static`` storage duration
731 variables to be usable in name by the user provided callable;
732 4. Only algorithms that are invoked with the ``parallel_unsequenced_policy`` are
733 candidates for offload;
734 5. Only algorithms that are invoked with iterator arguments that model
735 `random_access_iterator <https://en.cppreference.com/w/cpp/iterator/random_access_iterator>`_
736 are candidates for offload;
737 6. `Exceptions <https://en.cppreference.com/w/cpp/language/exceptions>`_ cannot
738 be used by the user provided callable;
739 7. Dynamic memory allocation (e.g. ``operator new``) cannot be used by the user
740 provided callable;
741 8. Selective offload is not possible i.e. it is not possible to indicate that
742 only some algorithms invoked with the ``parallel_unsequenced_policy`` are to
743 be executed on the accelerator.
744
745 In addition to the above, using **Interposition Mode** imposes the following
746 additional restrictions:
747
748 1. All code that is expected to interoperate has to be recompiled with the
749 ``--hipstdpar-interpose-alloc`` flag i.e. it is not safe to compose libraries
750 that have been independently compiled;
751
752 Current Support
753 ===============
754
755 At the moment, C++ Standard Parallelism Offload is only available for AMD GPUs,
756 when the `ROCm <https://rocm.docs.amd.com/en/latest/>`_ stack is used, on the
757 Linux operating system. Support is synthesised in the following table:
758
759 .. list-table::
760 :header-rows: 1
761
762 * - `Processor <https://llvm.org/docs/AMDGPUUsage.html#amdgpu-processors>`_
763 - HMM Mode
764 - Interposition Mode
765 * - GCN GFX9 (Vega)
766 - YES
767 - YES
768 * - GCN GFX10.1 (RDNA 1)
769 - *NO*
770 - YES
771 * - GCN GFX10.3 (RDNA 2)
772 - *NO*
773 - YES
774 * - GCN GFX11 (RDNA 3)
775 - *NO*
776 - YES
777 * - GCN GFX12 (RDNA 4)
778 - *NO*
779 - YES
780
781 The minimum Linux kernel version for running in HMM mode is 6.4.
782
783 The forwarding header is packaged by
784 `ROCm <https://rocm.docs.amd.com/en/latest/>`_, and is obtainable by installing
785 the `hipstdpar` packege. The list algorithms that can be offloaded is available
786 `here <https://github.com/ROCm/roc-stdpar#algorithm-support-status>`_. More
787 details are available via the dedicated blog
788 `<https://rocm.blogs.amd.com/software-tools-optimization/hipstdpar/README.html>`_.
789
790 HIP Specific Elements
791 ---------------------
792
793 1. There is no defined interop with the
794 `HIP kernel language <https://rocm.docs.amd.com/projects/HIP/en/latest/reference/kernel_language.html>`_;
795 whilst things like using `__device__` annotations might accidentally "work",
796 they are not guaranteed to, and thus cannot be relied upon by user code;
797
798 - A consequence of the above is that both bitcode linking and linking
799 relocatable object files will "work", but it is not guaranteed to remain
800 working or actively tested at the moment; this restriction might be relaxed
801 in the future.
802
803 2. Combining explicit HIP, CUDA or OpenMP Offload compilation with
804 ``--hipstdpar`` based offloading is not allowed or supported in any way.
805 3. There is no way to target different accelerators via a standard algorithm
806 invocation (`this might be addressed in future C++ standards <https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2500r1.html>`_);
807 an unsafe (per the point above) way of achieving this is to spawn new threads
808 and invoke the `hipSetDevice <https://rocm.docs.amd.com/projects/HIP/en/latest/.doxygen/docBin/html/group___device.html#ga43c1e7f15925eeb762195ccb5e063eae>`_
809 interface e.g.:
810
811 .. code-block:: c++
812
813 int accelerator_0 = ...;
814 int accelerator_1 = ...;
815
816 bool multiple_accelerators(const std::vector<int>& u, const std::vector<int>& v) {
817 std::atomic<unsigned int> r{0u};
818
819 thread t0{[&]() {
820 hipSetDevice(accelerator_0);
821
822 r += std::count(std::execution::par_unseq, std::cbegin(u), std::cend(u), 42);
823 }};
824 thread t1{[&]() {
825 hitSetDevice(accelerator_1);
826
827 r += std::count(std::execution::par_unseq, std::cbegin(v), std::cend(v), 314152)
828 }};
829
830 t0.join();
831 t1.join();
832
833 return r;
834 }
835
836 Note that this is a temporary, unsafe workaround for a deficiency in the C++
837 Standard.
838
839 Open Questions / Future Developments
840 ====================================
841
842 1. The restriction on the use of ``static`` / ``thread`` storage duration
843 variables in offloaded algorithms might be lifted;
844 2. The restriction on the use of dynamic memory allocation in offloaded
845 algorithms will be lifted in the future.
846 3. The restriction on the use of pointers to function, and associated features
847 such as dynamic polymorphism might be lifted in the future, when running in
848 **HMM Mode**;
849 4. Offload support might be extended to cases where the ``parallel_policy`` is
850 used for some or all targets.
851
852 SPIR-V Support on HIPAMD ToolChain
853 ==================================
854
855 The HIPAMD ToolChain supports targeting
856 `AMDGCN Flavoured SPIR-V <https://llvm.org/docs/SPIRVUsage.html#target-triples>`_.
857 The support for SPIR-V in the ROCm and HIPAMD ToolChain is under active
858 development.
859
860 Compilation Process
861 -------------------
862
863 When compiling HIP programs with the intent of utilizing SPIR-V, the process
864 diverges from the traditional compilation flow:
865
866 Using ``--offload-arch=amdgcnspirv``
867 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
868
869 - **Target Triple**: The ``--offload-arch=amdgcnspirv`` flag instructs the
870 compiler to use the target triple ``spirv64-amd-amdhsa``. This approach does
871 generates generic AMDGCN SPIR-V which retains architecture specific elements
872 without hardcoding them, thus allowing for optimal target specific code to be
873 generated at run time, when the concrete target is known.
874
875 - **LLVM IR Translation**: The program is compiled to LLVM Intermediate
876 Representation (IR), which is subsequently translated into SPIR-V. In the
877 future, this translation step will be replaced by direct SPIR-V emission via
878 the SPIR-V Back-end.
879
880 - **Clang Offload Bundler**: The resulting SPIR-V is embedded in the Clang
881 offload bundler with the bundle ID ``hip-spirv64-amd-amdhsa--amdgcnspirv``.
882
883 Architecture Specific Macros
884 ----------------------------
885
886 None of the architecture specific :doc:`AMDGPU macros <AMDGPUSupport>` are
887 defined when targeting SPIR-V. An alternative, more flexible mechanism to enable
888 doing per target / per feature code selection will be added in the future.