1 =========================
2 Compiling CUDA with clang
3 =========================
11 This document describes how to compile CUDA code with clang, and gives some
12 details about LLVM and clang's CUDA implementations.
14 This document assumes a basic familiarity with CUDA. Information about CUDA
15 programming can be found in the
16 `CUDA programming guide
17 <http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html>`_.
25 CUDA is supported in llvm 3.9, but it's still in active development, so we
26 recommend you `compile clang/LLVM from HEAD
27 <http://llvm.org/docs/GettingStarted.html>`_.
29 Before you build CUDA code, you'll need to have installed the appropriate
30 driver for your nvidia GPU and the CUDA SDK. See `NVIDIA's CUDA installation
31 guide <https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html>`_
32 for details. Note that clang `does not support
33 <https://llvm.org/bugs/show_bug.cgi?id=26966>`_ the CUDA toolkit as installed
34 by many Linux package managers; you probably need to install nvidia's package.
36 You will need CUDA 7.0, 7.5, or 8.0 to compile with clang.
41 Invoking clang for CUDA compilation works similarly to compiling regular C++.
42 You just need to be aware of a few additional flags.
44 You can use `this <https://gist.github.com/855e277884eb6b388cd2f00d956c2fd4>`_
45 program as a toy example. Save it as ``axpy.cu``. (Clang detects that you're
46 compiling CUDA code by noticing that your filename ends with ``.cu``.
47 Alternatively, you can pass ``-x cuda``.)
49 To build and run, run the following commands, filling in the parts in angle
50 brackets as described below:
52 .. code-block:: console
54 $ clang++ axpy.cu -o axpy --cuda-gpu-arch=<GPU arch> \
55 -L<CUDA install path>/<lib64 or lib> \
56 -lcudart_static -ldl -lrt -pthread
63 * ``<CUDA install path>`` -- the directory where you installed CUDA SDK.
64 Typically, ``/usr/local/cuda``.
66 Pass e.g. ``-L/usr/local/cuda/lib64`` if compiling in 64-bit mode; otherwise,
67 pass e.g. ``-L/usr/local/cuda/lib``. (In CUDA, the device code and host code
68 always have the same pointer widths, so if you're compiling 64-bit code for
69 the host, you're also compiling 64-bit code for the device.)
71 * ``<GPU arch>`` -- the `compute capability
72 <https://developer.nvidia.com/cuda-gpus>`_ of your GPU. For example, if you
73 want to run your program on a GPU with compute capability of 3.5, specify
74 ``--cuda-gpu-arch=sm_35``.
76 Note: You cannot pass ``compute_XX`` as an argument to ``--cuda-gpu-arch``;
77 only ``sm_XX`` is currently supported. However, clang always includes PTX in
78 its binaries, so e.g. a binary compiled with ``--cuda-gpu-arch=sm_30`` would be
79 forwards-compatible with e.g. ``sm_35`` GPUs.
81 You can pass ``--cuda-gpu-arch`` multiple times to compile for multiple archs.
83 The `-L` and `-l` flags only need to be passed when linking. When compiling,
84 you may also need to pass ``--cuda-path=/path/to/cuda`` if you didn't install
85 the CUDA SDK into ``/usr/local/cuda``, ``/usr/local/cuda-7.0``, or
86 ``/usr/local/cuda-7.5``.
88 Flags that control numerical code
89 ---------------------------------
91 If you're using GPUs, you probably care about making numerical code run fast.
92 GPU hardware allows for more control over numerical operations than most CPUs,
93 but this results in more compiler options for you to juggle.
95 Flags you may wish to tweak include:
97 * ``-ffp-contract={on,off,fast}`` (defaults to ``fast`` on host and device when
98 compiling CUDA) Controls whether the compiler emits fused multiply-add
101 * ``off``: never emit fma operations, and prevent ptxas from fusing multiply
102 and add instructions.
103 * ``on``: fuse multiplies and adds within a single statement, but never
104 across statements (C11 semantics). Prevent ptxas from fusing other
106 * ``fast``: fuse multiplies and adds wherever profitable, even across
107 statements. Doesn't prevent ptxas from fusing additional multiplies and
110 Fused multiply-add instructions can be much faster than the unfused
111 equivalents, but because the intermediate result in an fma is not rounded,
112 this flag can affect numerical code.
114 * ``-fcuda-flush-denormals-to-zero`` (default: off) When this is enabled,
115 floating point operations may flush `denormal
116 <https://en.wikipedia.org/wiki/Denormal_number>`_ inputs and/or outputs to 0.
117 Operations on denormal numbers are often much slower than the same operations
120 * ``-fcuda-approx-transcendentals`` (default: off) When this is enabled, the
121 compiler may emit calls to faster, approximate versions of transcendental
122 functions, instead of using the slower, fully IEEE-compliant versions. For
123 example, this flag allows clang to emit the ptx ``sin.approx.f32``
126 This is implied by ``-ffast-math``.
128 Standard library support
129 ========================
131 In clang and nvcc, most of the C++ standard library is not supported on the
134 ``<math.h>`` and ``<cmath>``
135 ----------------------------
137 In clang, ``math.h`` and ``cmath`` are available and `pass
138 <https://github.com/llvm-mirror/test-suite/blob/master/External/CUDA/math_h.cu>`_
140 <https://github.com/llvm-mirror/test-suite/blob/master/External/CUDA/cmath.cu>`_
141 adapted from libc++'s test suite.
143 In nvcc ``math.h`` and ``cmath`` are mostly available. Versions of ``::foof``
144 in namespace std (e.g. ``std::sinf``) are not available, and where the standard
145 calls for overloads that take integral arguments, these are usually not
153 // clang is OK with everything in this function.
154 __device__ void test() {
155 std::sin(0.); // nvcc - ok
156 std::sin(0); // nvcc - error, because no std::sin(int) override is available.
157 sin(0); // nvcc - same as above.
159 sinf(0.); // nvcc - ok
160 std::sinf(0.); // nvcc - no such function
166 nvcc does not officially support ``std::complex``. It's an error to use
167 ``std::complex`` in ``__device__`` code, but it often works in ``__host__
168 __device__`` code due to nvcc's interpretation of the "wrong-side rule" (see
169 below). However, we have heard from implementers that it's possible to get
170 into situations where nvcc will omit a call to an ``std::complex`` function,
171 especially when compiling without optimizations.
173 As of 2016-11-16, clang supports ``std::complex`` without these caveats. It is
174 tested with libstdc++ 4.8.5 and newer, but is known to work only with libc++
175 newer than 2016-11-16.
180 In C++14, many useful functions from ``<algorithm>`` (notably, ``std::min`` and
181 ``std::max``) become constexpr. You can therefore use these in device code,
182 when compiling with clang.
184 Detecting clang vs NVCC from code
185 =================================
187 Although clang's CUDA implementation is largely compatible with NVCC's, you may
188 still want to detect when you're compiling CUDA code specifically with clang.
190 This is tricky, because NVCC may invoke clang as part of its own compilation
191 process! For example, NVCC uses the host compiler's preprocessor when
192 compiling for device code, and that host compiler may in fact be clang.
194 When clang is actually compiling CUDA code -- rather than being used as a
195 subtool of NVCC's -- it defines the ``__CUDA__`` macro. ``__CUDA_ARCH__`` is
196 defined only in device mode (but will be defined if NVCC is using clang as a
197 preprocessor). So you can use the following incantations to detect clang CUDA
198 compilation, in host and device modes:
202 #if defined(__clang__) && defined(__CUDA__) && !defined(__CUDA_ARCH__)
203 // clang compiling CUDA code, host mode.
206 #if defined(__clang__) && defined(__CUDA__) && defined(__CUDA_ARCH__)
207 // clang compiling CUDA code, device mode.
210 Both clang and nvcc define ``__CUDACC__`` during CUDA compilation. You can
211 detect NVCC specifically by looking for ``__NVCC__``.
213 Dialect Differences Between clang and nvcc
214 ==========================================
216 There is no formal CUDA spec, and clang and nvcc speak slightly different
217 dialects of the language. Below, we describe some of the differences.
219 This section is painful; hopefully you can skip this section and live your life
225 Most of the differences between clang and nvcc stem from the different
226 compilation models used by clang and nvcc. nvcc uses *split compilation*,
227 which works roughly as follows:
229 * Run a preprocessor over the input ``.cu`` file to split it into two source
230 files: ``H``, containing source code for the host, and ``D``, containing
231 source code for the device.
233 * For each GPU architecture ``arch`` that we're compiling for, do:
235 * Compile ``D`` using nvcc proper. The result of this is a ``ptx`` file for
238 * Optionally, invoke ``ptxas``, the PTX assembler, to generate a file,
239 ``S_arch``, containing GPU machine code (SASS) for ``arch``.
241 * Invoke ``fatbin`` to combine all ``P_arch`` and ``S_arch`` files into a
242 single "fat binary" file, ``F``.
244 * Compile ``H`` using an external host compiler (gcc, clang, or whatever you
245 like). ``F`` is packaged up into a header file which is force-included into
246 ``H``; nvcc generates code that calls into this header to e.g. launch
249 clang uses *merged parsing*. This is similar to split compilation, except all
250 of the host and device code is present and must be semantically-correct in both
253 * For each GPU architecture ``arch`` that we're compiling for, do:
255 * Compile the input ``.cu`` file for device, using clang. ``__host__`` code
256 is parsed and must be semantically correct, even though we're not
257 generating code for the host at this time.
259 The output of this step is a ``ptx`` file ``P_arch``.
261 * Invoke ``ptxas`` to generate a SASS file, ``S_arch``. Note that, unlike
262 nvcc, clang always generates SASS code.
264 * Invoke ``fatbin`` to combine all ``P_arch`` and ``S_arch`` files into a
265 single fat binary file, ``F``.
267 * Compile ``H`` using clang. ``__device__`` code is parsed and must be
268 semantically correct, even though we're not generating code for the device
271 ``F`` is passed to this compilation, and clang includes it in a special ELF
272 section, where it can be found by tools like ``cuobjdump``.
274 (You may ask at this point, why does clang need to parse the input file
275 multiple times? Why not parse it just once, and then use the AST to generate
276 code for the host and each device architecture?
278 Unfortunately this can't work because we have to define different macros during
279 host compilation and during device compilation for each GPU architecture.)
281 clang's approach allows it to be highly robust to C++ edge cases, as it doesn't
282 need to decide at an early stage which declarations to keep and which to throw
283 away. But it has some consequences you should be aware of.
285 Overloading Based on ``__host__`` and ``__device__`` Attributes
286 ---------------------------------------------------------------
288 Let "H", "D", and "HD" stand for "``__host__`` functions", "``__device__``
289 functions", and "``__host__ __device__`` functions", respectively. Functions
290 with no attributes behave the same as H.
292 nvcc does not allow you to create H and D functions with the same signature:
296 // nvcc: error - function "foo" has already been defined
297 __host__ void foo() {}
298 __device__ void foo() {}
300 However, nvcc allows you to "overload" H and D functions with different
306 __host__ void foo(int) {}
307 __device__ void foo() {}
309 In clang, the ``__host__`` and ``__device__`` attributes are part of a
310 function's signature, and so it's legal to have H and D functions with
311 (otherwise) the same signature:
316 __host__ void foo() {}
317 __device__ void foo() {}
319 HD functions cannot be overloaded by H or D functions with the same signature:
323 // nvcc: error - function "foo" has already been defined
324 // clang: error - redefinition of 'foo'
325 __host__ __device__ void foo() {}
326 __device__ void foo() {}
330 __host__ __device__ void bar(int) {}
331 __device__ void bar() {}
333 When resolving an overloaded function, clang considers the host/device
334 attributes of the caller and callee. These are used as a tiebreaker during
335 overload resolution. See `IdentifyCUDAPreference
336 <http://clang.llvm.org/doxygen/SemaCUDA_8cpp.html>`_ for the full set of rules,
337 but at a high level they are:
339 * D functions prefer to call other Ds. HDs are given lower priority.
341 * Similarly, H functions prefer to call other Hs, or ``__global__`` functions
342 (with equal priority). HDs are given lower priority.
344 * HD functions prefer to call other HDs.
346 When compiling for device, HDs will call Ds with lower priority than HD, and
347 will call Hs with still lower priority. If it's forced to call an H, the
348 program is malformed if we emit code for this HD function. We call this the
349 "wrong-side rule", see example below.
351 The rules are symmetrical when compiling for host.
358 __device__ void foo();
361 __host__ __device__ void bar();
363 __host__ void test_host() {
364 foo(); // calls H overload
365 bar(); // calls H overload
368 __device__ void test_device() {
369 foo(); // calls D overload
370 bar(); // calls HD overload
373 __host__ __device__ void test_hd() {
374 foo(); // calls H overload when compiling for host, otherwise D overload
375 bar(); // always calls HD overload
378 Wrong-side rule example:
382 __host__ void host_only();
384 // We don't codegen inline functions unless they're referenced by a
385 // non-inline function. inline_hd1() is called only from the host side, so
386 // does not generate an error. inline_hd2() is called from the device side,
387 // so it generates an error.
388 inline __host__ __device__ void inline_hd1() { host_only(); } // no error
389 inline __host__ __device__ void inline_hd2() { host_only(); } // error
391 __host__ void host_fn() { inline_hd1(); }
392 __device__ void device_fn() { inline_hd2(); }
394 // This function is not inline, so it's always codegen'ed on both the host
395 // and the device. Therefore, it generates an error.
396 __host__ __device__ void not_inline_hd() { host_only(); }
398 For the purposes of the wrong-side rule, templated functions also behave like
399 ``inline`` functions: They aren't codegen'ed unless they're instantiated
400 (usually as part of the process of invoking them).
402 clang's behavior with respect to the wrong-side rule matches nvcc's, except
403 nvcc only emits a warning for ``not_inline_hd``; device code is allowed to call
404 ``not_inline_hd``. In its generated code, nvcc may omit ``not_inline_hd``'s
405 call to ``host_only`` entirely, or it may try to generate code for
406 ``host_only`` on the device. What you get seems to depend on whether or not
407 the compiler chooses to inline ``host_only``.
409 Member functions, including constructors, may be overloaded using H and D
410 attributes. However, destructors cannot be overloaded.
412 Using a Different Class on Host/Device
413 --------------------------------------
415 Occasionally you may want to have a class with different host/device versions.
417 If all of the class's members are the same on the host and device, you can just
418 provide overloads for the class's member functions.
420 However, if you want your class to have different members on host/device, you
421 won't be able to provide working H and D overloads in both classes. In this
422 case, clang is likely to be unhappy with you.
428 __device__ void foo() { /* use device_only */ }
433 __host__ void foo() { /* use host_only */ }
437 __device__ void test() {
439 // clang generates an error here, because during host compilation, we
440 // have ifdef'ed away the __device__ overload of S::foo(). The __device__
441 // overload must be present *even during host compilation*.
446 We posit that you don't really want to have classes with different members on H
447 and D. For example, if you were to pass one of these as a parameter to a
448 kernel, it would have a different layout on H and D, so would not work
451 To make code like this compatible with clang, we recommend you separate it out
452 into two classes. If you need to write code that works on both host and
453 device, consider writing an overloaded wrapper function that returns different
454 types on host and device.
458 struct HostS { ... };
459 struct DeviceS { ... };
461 __host__ HostS MakeStruct() { return HostS(); }
462 __device__ DeviceS MakeStruct() { return DeviceS(); }
464 // Now host and device code can call MakeStruct().
466 Unfortunately, this idiom isn't compatible with nvcc, because it doesn't allow
467 you to overload based on the H/D attributes. Here's an idiom that works with
472 struct HostS { ... };
473 struct DeviceS { ... };
476 #ifndef __CUDA_ARCH__
477 __host__ HostS MakeStruct() { return HostS(); }
479 __device__ DeviceS MakeStruct() { return DeviceS(); }
482 __host__ HostS MakeStruct() { return HostS(); }
483 __device__ DeviceS MakeStruct() { return DeviceS(); }
486 // Now host and device code can call MakeStruct().
488 Hopefully you don't have to do this sort of thing often.
493 Modern CPUs and GPUs are architecturally quite different, so code that's fast
494 on a CPU isn't necessarily fast on a GPU. We've made a number of changes to
495 LLVM to make it generate good GPU code. Among these changes are:
497 * `Straight-line scalar optimizations <https://goo.gl/4Rb9As>`_ -- These
498 reduce redundancy within straight-line code.
500 * `Aggressive speculative execution
501 <http://llvm.org/docs/doxygen/html/SpeculativeExecution_8cpp_source.html>`_
502 -- This is mainly for promoting straight-line scalar optimizations, which are
503 most effective on code along dominator paths.
505 * `Memory space inference
506 <http://llvm.org/doxygen/NVPTXInferAddressSpaces_8cpp_source.html>`_ --
507 In PTX, we can operate on pointers that are in a paricular "address space"
508 (global, shared, constant, or local), or we can operate on pointers in the
509 "generic" address space, which can point to anything. Operations in a
510 non-generic address space are faster, but pointers in CUDA are not explicitly
511 annotated with their address space, so it's up to LLVM to infer it where
514 * `Bypassing 64-bit divides
515 <http://llvm.org/docs/doxygen/html/BypassSlowDivision_8cpp_source.html>`_ --
516 This was an existing optimization that we enabled for the PTX backend.
518 64-bit integer divides are much slower than 32-bit ones on NVIDIA GPUs.
519 Many of the 64-bit divides in our benchmarks have a divisor and dividend
520 which fit in 32-bits at runtime. This optimization provides a fast path for
523 * Aggressive loop unrooling and function inlining -- Loop unrolling and
524 function inlining need to be more aggressive for GPUs than for CPUs because
525 control flow transfer in GPU is more expensive. More aggressive unrolling and
526 inlining also promote other optimizations, such as constant propagation and
527 SROA, which sometimes speed up code by over 10x.
529 (Programmers can force unrolling and inline using clang's `loop unrolling pragmas
530 <http://clang.llvm.org/docs/AttributeReference.html#pragma-unroll-pragma-nounroll>`_
531 and ``__attribute__((always_inline))``.)
536 The team at Google published a paper in CGO 2016 detailing the optimizations
537 they'd made to clang/LLVM. Note that "gpucc" is no longer a meaningful name:
538 The relevant tools are now just vanilla clang/LLVM.
540 | `gpucc: An Open-Source GPGPU Compiler <http://dl.acm.org/citation.cfm?id=2854041>`_
541 | Jingyue Wu, Artem Belevich, Eli Bendersky, Mark Heffernan, Chris Leary, Jacques Pienaar, Bjarke Roune, Rob Springer, Xuetian Weng, Robert Hundt
542 | *Proceedings of the 2016 International Symposium on Code Generation and Optimization (CGO 2016)*
544 | `Slides from the CGO talk <http://wujingyue.com/docs/gpucc-talk.pdf>`_
546 | `Tutorial given at CGO <http://wujingyue.com/docs/gpucc-tutorial.pdf>`_
551 To obtain help on LLVM in general and its CUDA support, see `the LLVM
552 community <http://llvm.org/docs/#mailing-lists>`_.