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 or 7.5 to compile with clang. CUDA 8 support is in the
42 Invoking clang for CUDA compilation works similarly to compiling regular C++.
43 You just need to be aware of a few additional flags.
45 You can use `this <https://gist.github.com/855e277884eb6b388cd2f00d956c2fd4>`_
46 program as a toy example. Save it as ``axpy.cu``. (Clang detects that you're
47 compiling CUDA code by noticing that your filename ends with ``.cu``.
48 Alternatively, you can pass ``-x cuda``.)
50 To build and run, run the following commands, filling in the parts in angle
51 brackets as described below:
53 .. code-block:: console
55 $ clang++ axpy.cu -o axpy --cuda-gpu-arch=<GPU arch> \
56 -L<CUDA install path>/<lib64 or lib> \
57 -lcudart_static -ldl -lrt -pthread
64 * ``<CUDA install path>`` -- the directory where you installed CUDA SDK.
65 Typically, ``/usr/local/cuda``.
67 Pass e.g. ``-L/usr/local/cuda/lib64`` if compiling in 64-bit mode; otherwise,
68 pass e.g. ``-L/usr/local/cuda/lib``. (In CUDA, the device code and host code
69 always have the same pointer widths, so if you're compiling 64-bit code for
70 the host, you're also compiling 64-bit code for the device.)
72 * ``<GPU arch>`` -- the `compute capability
73 <https://developer.nvidia.com/cuda-gpus>`_ of your GPU. For example, if you
74 want to run your program on a GPU with compute capability of 3.5, specify
75 ``--cuda-gpu-arch=sm_35``.
77 Note: You cannot pass ``compute_XX`` as an argument to ``--cuda-gpu-arch``;
78 only ``sm_XX`` is currently supported. However, clang always includes PTX in
79 its binaries, so e.g. a binary compiled with ``--cuda-gpu-arch=sm_30`` would be
80 forwards-compatible with e.g. ``sm_35`` GPUs.
82 You can pass ``--cuda-gpu-arch`` multiple times to compile for multiple archs.
84 The `-L` and `-l` flags only need to be passed when linking. When compiling,
85 you may also need to pass ``--cuda-path=/path/to/cuda`` if you didn't install
86 the CUDA SDK into ``/usr/local/cuda``, ``/usr/local/cuda-7.0``, or
87 ``/usr/local/cuda-7.5``.
89 Flags that control numerical code
90 ---------------------------------
92 If you're using GPUs, you probably care about making numerical code run fast.
93 GPU hardware allows for more control over numerical operations than most CPUs,
94 but this results in more compiler options for you to juggle.
96 Flags you may wish to tweak include:
98 * ``-ffp-contract={on,off,fast}`` (defaults to ``fast`` on host and device when
99 compiling CUDA) Controls whether the compiler emits fused multiply-add
102 * ``off``: never emit fma operations, and prevent ptxas from fusing multiply
103 and add instructions.
104 * ``on``: fuse multiplies and adds within a single statement, but never
105 across statements (C11 semantics). Prevent ptxas from fusing other
107 * ``fast``: fuse multiplies and adds wherever profitable, even across
108 statements. Doesn't prevent ptxas from fusing additional multiplies and
111 Fused multiply-add instructions can be much faster than the unfused
112 equivalents, but because the intermediate result in an fma is not rounded,
113 this flag can affect numerical code.
115 * ``-fcuda-flush-denormals-to-zero`` (default: off) When this is enabled,
116 floating point operations may flush `denormal
117 <https://en.wikipedia.org/wiki/Denormal_number>`_ inputs and/or outputs to 0.
118 Operations on denormal numbers are often much slower than the same operations
121 * ``-fcuda-approx-transcendentals`` (default: off) When this is enabled, the
122 compiler may emit calls to faster, approximate versions of transcendental
123 functions, instead of using the slower, fully IEEE-compliant versions. For
124 example, this flag allows clang to emit the ptx ``sin.approx.f32``
127 This is implied by ``-ffast-math``.
129 Detecting clang vs NVCC from code
130 =================================
132 Although clang's CUDA implementation is largely compatible with NVCC's, you may
133 still want to detect when you're compiling CUDA code specifically with clang.
135 This is tricky, because NVCC may invoke clang as part of its own compilation
136 process! For example, NVCC uses the host compiler's preprocessor when
137 compiling for device code, and that host compiler may in fact be clang.
139 When clang is actually compiling CUDA code -- rather than being used as a
140 subtool of NVCC's -- it defines the ``__CUDA__`` macro. ``__CUDA_ARCH__`` is
141 defined only in device mode (but will be defined if NVCC is using clang as a
142 preprocessor). So you can use the following incantations to detect clang CUDA
143 compilation, in host and device modes:
147 #if defined(__clang__) && defined(__CUDA__) && !defined(__CUDA_ARCH__)
148 // clang compiling CUDA code, host mode.
151 #if defined(__clang__) && defined(__CUDA__) && defined(__CUDA_ARCH__)
152 // clang compiling CUDA code, device mode.
155 Both clang and nvcc define ``__CUDACC__`` during CUDA compilation. You can
156 detect NVCC specifically by looking for ``__NVCC__``.
161 CPU and GPU have different design philosophies and architectures. For example, a
162 typical CPU has branch prediction, out-of-order execution, and is superscalar,
163 whereas a typical GPU has none of these. Due to such differences, an
164 optimization pipeline well-tuned for CPUs may be not suitable for GPUs.
166 LLVM performs several general and CUDA-specific optimizations for GPUs. The
167 list below shows some of the more important optimizations for GPUs. Most of
168 them have been upstreamed to ``lib/Transforms/Scalar`` and
169 ``lib/Target/NVPTX``. A few of them have not been upstreamed due to lack of a
170 customizable target-independent optimization pipeline.
172 * **Straight-line scalar optimizations**. These optimizations reduce redundancy
173 in straight-line code. Details can be found in the `design document for
174 straight-line scalar optimizations <https://goo.gl/4Rb9As>`_.
176 * **Inferring memory spaces**. `This optimization
177 <https://github.com/llvm-mirror/llvm/blob/master/lib/Target/NVPTX/NVPTXInferAddressSpaces.cpp>`_
178 infers the memory space of an address so that the backend can emit faster
179 special loads and stores from it.
181 * **Aggressive loop unrooling and function inlining**. Loop unrolling and
182 function inlining need to be more aggressive for GPUs than for CPUs because
183 control flow transfer in GPU is more expensive. They also promote other
184 optimizations such as constant propagation and SROA which sometimes speed up
185 code by over 10x. An empirical inline threshold for GPUs is 1100. This
186 configuration has yet to be upstreamed with a target-specific optimization
187 pipeline. LLVM also provides `loop unrolling pragmas
188 <http://clang.llvm.org/docs/AttributeReference.html#pragma-unroll-pragma-nounroll>`_
189 and ``__attribute__((always_inline))`` for programmers to force unrolling and
192 * **Aggressive speculative execution**. `This transformation
193 <http://llvm.org/docs/doxygen/html/SpeculativeExecution_8cpp_source.html>`_ is
194 mainly for promoting straight-line scalar optimizations which are most
195 effective on code along dominator paths.
197 * **Memory-space alias analysis**. `This alias analysis
198 <http://reviews.llvm.org/D12414>`_ infers that two pointers in different
199 special memory spaces do not alias. It has yet to be integrated to the new
200 alias analysis infrastructure; the new infrastructure does not run
201 target-specific alias analysis.
203 * **Bypassing 64-bit divides**. `An existing optimization
204 <http://llvm.org/docs/doxygen/html/BypassSlowDivision_8cpp_source.html>`_
205 enabled in the NVPTX backend. 64-bit integer divides are much slower than
206 32-bit ones on NVIDIA GPUs due to lack of a divide unit. Many of the 64-bit
207 divides in our benchmarks have a divisor and dividend which fit in 32-bits at
208 runtime. This optimization provides a fast path for this common case.
213 | `gpucc: An Open-Source GPGPU Compiler <http://dl.acm.org/citation.cfm?id=2854041>`_
214 | Jingyue Wu, Artem Belevich, Eli Bendersky, Mark Heffernan, Chris Leary, Jacques Pienaar, Bjarke Roune, Rob Springer, Xuetian Weng, Robert Hundt
215 | *Proceedings of the 2016 International Symposium on Code Generation and Optimization (CGO 2016)*
216 | `Slides for the CGO talk <http://wujingyue.com/docs/gpucc-talk.pdf>`_
221 `CGO 2016 gpucc tutorial <http://wujingyue.com/docs/gpucc-tutorial.pdf>`_
226 To obtain help on LLVM in general and its CUDA support, see `the LLVM
227 community <http://llvm.org/docs/#mailing-lists>`_.