Compiling CUDA with clang

Introduction

This document describes how to compile CUDA code with clang, and gives somedetails about LLVM and clang’s CUDA implementations.

This document assumes a basic familiarity with CUDA. Information about CUDAprogramming can be found in theCUDA programming guide.

Compiling CUDA Code

Prerequisites

CUDA is supported since llvm 3.9. Clang currently supports CUDA 7.0 through10.1. If clang detects a newer CUDA version, it will issue a warning and willattempt to use detected CUDA SDK it as if it were CUDA-10.1.

Before you build CUDA code, you’ll need to have installed the CUDA SDK. SeeNVIDIA’s CUDA installation guide fordetails. Note that clang maynot support the CUDA toolkit as installed bysome Linux package managers. Clang does attempt to deal with specific details ofCUDA installation on a handful of common Linux distributions, but in general themost reliable way to make it work is to install CUDA in a single directory fromNVIDIA’s .run package and specify its location via –cuda-path=… argument.

CUDA compilation is supported on Linux. Compilation on MacOS and Windows may ormay not work and currently have no maintainers.

Invoking clang

Invoking clang for CUDA compilation works similarly to compiling regular C++.You just need to be aware of a few additional flags.

You can use thisprogram as a toy example. Save it as axpy.cu. (Clang detects that you’recompiling CUDA code by noticing that your filename ends with .cu.Alternatively, you can pass -x cuda.)

To build and run, run the following commands, filling in the parts in anglebrackets as described below:

  1. $ clang++ axpy.cu -o axpy --cuda-gpu-arch=<GPU arch> \
  2. -L<CUDA install path>/<lib64 or lib> \
  3. -lcudart_static -ldl -lrt -pthread
  4. $ ./axpy
  5. y[0] = 2
  6. y[1] = 4
  7. y[2] = 6
  8. y[3] = 8

On MacOS, replace -lcudart_static with -lcudart; otherwise, you may get“CUDA driver version is insufficient for CUDA runtime version” errors when yourun your program.

  • <CUDA install path> – the directory where you installed CUDA SDK.Typically, /usr/local/cuda.

Pass e.g. -L/usr/local/cuda/lib64 if compiling in 64-bit mode; otherwise,pass e.g. -L/usr/local/cuda/lib. (In CUDA, the device code and host codealways have the same pointer widths, so if you’re compiling 64-bit code forthe host, you’re also compiling 64-bit code for the device.) Note that as ofv10.0 CUDA SDK no longer supports compilation of 32-bitapplications.

  • <GPU arch> – the compute capability of your GPU. For example, if youwant to run your program on a GPU with compute capability of 3.5, specify—cuda-gpu-arch=sm_35.

Note: You cannot pass compute_XX as an argument to —cuda-gpu-arch;only sm_XX is currently supported. However, clang always includes PTX inits binaries, so e.g. a binary compiled with —cuda-gpu-arch=sm_30 would beforwards-compatible with e.g. sm_35 GPUs.

You can pass —cuda-gpu-arch multiple times to compile for multiple archs.

The -L and -l flags only need to be passed when linking. When compiling,you may also need to pass —cuda-path=/path/to/cuda if you didn’t installthe CUDA SDK into /usr/local/cuda or /usr/local/cuda-X.Y.

Flags that control numerical code

If you’re using GPUs, you probably care about making numerical code run fast.GPU hardware allows for more control over numerical operations than most CPUs,but this results in more compiler options for you to juggle.

Flags you may wish to tweak include:

  • -ffp-contract={on,off,fast} (defaults to fast on host and device whencompiling CUDA) Controls whether the compiler emits fused multiply-addoperations.

    • off: never emit fma operations, and prevent ptxas from fusing multiplyand add instructions.
    • on: fuse multiplies and adds within a single statement, but neveracross statements (C11 semantics). Prevent ptxas from fusing othermultiplies and adds.
    • fast: fuse multiplies and adds wherever profitable, even acrossstatements. Doesn’t prevent ptxas from fusing additional multiplies andadds.Fused multiply-add instructions can be much faster than the unfusedequivalents, but because the intermediate result in an fma is not rounded,this flag can affect numerical code.
  • -fcuda-flush-denormals-to-zero (default: off) When this is enabled,floating point operations may flush denormal inputs and/or outputs to 0.Operations on denormal numbers are often much slower than the same operationson normal numbers.

  • -fcuda-approx-transcendentals (default: off) When this is enabled, thecompiler may emit calls to faster, approximate versions of transcendentalfunctions, instead of using the slower, fully IEEE-compliant versions. Forexample, this flag allows clang to emit the ptx sin.approx.f32instruction.

This is implied by -ffast-math.

Standard library support

In clang and nvcc, most of the C++ standard library is not supported on thedevice side.

<math.h> and <cmath>

In clang, math.h and cmath are available and passtestsadapted from libc++’s test suite.

In nvcc math.h and cmath are mostly available. Versions of ::foofin namespace std (e.g. std::sinf) are not available, and where the standardcalls for overloads that take integral arguments, these are usually notavailable.

  1. #include <math.h>
  2. #include <cmath.h>
  3.  
  4. // clang is OK with everything in this function.
  5. __device__ void test() {
  6. std::sin(0.); // nvcc - ok
  7. std::sin(0); // nvcc - error, because no std::sin(int) override is available.
  8. sin(0); // nvcc - same as above.
  9.  
  10. sinf(0.); // nvcc - ok
  11. std::sinf(0.); // nvcc - no such function
  12. }

<std::complex>

nvcc does not officially support std::complex. It’s an error to usestd::complex in device code, but it often works in hostdevice code due to nvcc’s interpretation of the “wrong-side rule” (seebelow). However, we have heard from implementers that it’s possible to getinto situations where nvcc will omit a call to an std::complex function,especially when compiling without optimizations.

As of 2016-11-16, clang supports std::complex without these caveats. It istested with libstdc++ 4.8.5 and newer, but is known to work only with libc++newer than 2016-11-16.

<algorithm>

In C++14, many useful functions from <algorithm> (notably, std::min andstd::max) become constexpr. You can therefore use these in device code,when compiling with clang.

Detecting clang vs NVCC from code

Although clang’s CUDA implementation is largely compatible with NVCC’s, you maystill want to detect when you’re compiling CUDA code specifically with clang.

This is tricky, because NVCC may invoke clang as part of its own compilationprocess! For example, NVCC uses the host compiler’s preprocessor whencompiling for device code, and that host compiler may in fact be clang.

When clang is actually compiling CUDA code – rather than being used as asubtool of NVCC’s – it defines the CUDA macro. CUDA_ARCH isdefined only in device mode (but will be defined if NVCC is using clang as apreprocessor). So you can use the following incantations to detect clang CUDAcompilation, in host and device modes:

  1. #if defined(__clang__) && defined(__CUDA__) && !defined(__CUDA_ARCH__)
  2. // clang compiling CUDA code, host mode.
  3. #endif
  4.  
  5. #if defined(__clang__) && defined(__CUDA__) && defined(__CUDA_ARCH__)
  6. // clang compiling CUDA code, device mode.
  7. #endif

Both clang and nvcc define CUDACC during CUDA compilation. You candetect NVCC specifically by looking for NVCC.

Dialect Differences Between clang and nvcc

There is no formal CUDA spec, and clang and nvcc speak slightly differentdialects of the language. Below, we describe some of the differences.

This section is painful; hopefully you can skip this section and live your lifeblissfully unaware.

Compilation Models

Most of the differences between clang and nvcc stem from the differentcompilation models used by clang and nvcc. nvcc uses split compilation,which works roughly as follows:

  • Run a preprocessor over the input .cu file to split it into two sourcefiles: H, containing source code for the host, and D, containingsource code for the device.
  • For each GPU architecture arch that we’re compiling for, do:
    • Compile D using nvcc proper. The result of this is a ptx file forP_arch.
    • Optionally, invoke ptxas, the PTX assembler, to generate a file,S_arch, containing GPU machine code (SASS) for arch.
  • Invoke fatbin to combine all P_arch and S_arch files into asingle “fat binary” file, F.
  • Compile H using an external host compiler (gcc, clang, or whatever youlike). F is packaged up into a header file which is force-included intoH; nvcc generates code that calls into this header to e.g. launchkernels.

clang uses merged parsing. This is similar to split compilation, except allof the host and device code is present and must be semantically-correct in bothcompilation steps.

  • For each GPU architecture arch that we’re compiling for, do:

    • Compile the input .cu file for device, using clang. host codeis parsed and must be semantically correct, even though we’re notgenerating code for the host at this time.

      The output of this step is a ptx file Parch.

    • Invoke ptxas to generate a SASS file, Sarch. Note that, unlikenvcc, clang always generates SASS code.

  • Invoke fatbin to combine all P_arch and S_arch files into asingle fat binary file, F.

  • Compile H using clang. __device code is parsed and must besemantically correct, even though we’re not generating code for the deviceat this time.

    F is passed to this compilation, and clang includes it in a special ELFsection, where it can be found by tools like cuobjdump.

(You may ask at this point, why does clang need to parse the input filemultiple times? Why not parse it just once, and then use the AST to generatecode for the host and each device architecture?

Unfortunately this can’t work because we have to define different macros duringhost compilation and during device compilation for each GPU architecture.)

clang’s approach allows it to be highly robust to C++ edge cases, as it doesn’tneed to decide at an early stage which declarations to keep and which to throwaway. But it has some consequences you should be aware of.

Overloading Based on host and device Attributes

Let “H”, “D”, and “HD” stand for “host functions”, “devicefunctions”, and “host device functions”, respectively. Functionswith no attributes behave the same as H.

nvcc does not allow you to create H and D functions with the same signature:

  1. // nvcc: error - function "foo" has already been defined
  2. __host__ void foo() {}
  3. __device__ void foo() {}

However, nvcc allows you to “overload” H and D functions with differentsignatures:

  1. // nvcc: no error
  2. __host__ void foo(int) {}
  3. __device__ void foo() {}

In clang, the host and device attributes are part of afunction’s signature, and so it’s legal to have H and D functions with(otherwise) the same signature:

  1. // clang: no error
  2. __host__ void foo() {}
  3. __device__ void foo() {}

HD functions cannot be overloaded by H or D functions with the same signature:

  1. // nvcc: error - function "foo" has already been defined
  2. // clang: error - redefinition of 'foo'
  3. __host__ __device__ void foo() {}
  4. __device__ void foo() {}
  5.  
  6. // nvcc: no error
  7. // clang: no error
  8. __host__ __device__ void bar(int) {}
  9. __device__ void bar() {}

When resolving an overloaded function, clang considers the host/deviceattributes of the caller and callee. These are used as a tiebreaker duringoverload resolution. See IdentifyCUDAPreference for the full set of rules,but at a high level they are:

  • D functions prefer to call other Ds. HDs are given lower priority.

  • Similarly, H functions prefer to call other Hs, or global functions(with equal priority). HDs are given lower priority.

  • HD functions prefer to call other HDs.

    When compiling for device, HDs will call Ds with lower priority than HD, andwill call Hs with still lower priority. If it’s forced to call an H, theprogram is malformed if we emit code for this HD function. We call this the“wrong-side rule”, see example below.

    The rules are symmetrical when compiling for host.

Some examples:

  1. __host__ void foo();
  2. __device__ void foo();
  3.  
  4. __host__ void bar();
  5. __host__ __device__ void bar();
  6.  
  7. __host__ void test_host() {
  8. foo(); // calls H overload
  9. bar(); // calls H overload
  10. }
  11.  
  12. __device__ void test_device() {
  13. foo(); // calls D overload
  14. bar(); // calls HD overload
  15. }
  16.  
  17. __host__ __device__ void test_hd() {
  18. foo(); // calls H overload when compiling for host, otherwise D overload
  19. bar(); // always calls HD overload
  20. }

Wrong-side rule example:

  1. __host__ void host_only();
  2.  
  3. // We don't codegen inline functions unless they're referenced by a
  4. // non-inline function. inline_hd1() is called only from the host side, so
  5. // does not generate an error. inline_hd2() is called from the device side,
  6. // so it generates an error.
  7. inline __host__ __device__ void inline_hd1() { host_only(); } // no error
  8. inline __host__ __device__ void inline_hd2() { host_only(); } // error
  9.  
  10. __host__ void host_fn() { inline_hd1(); }
  11. __device__ void device_fn() { inline_hd2(); }
  12.  
  13. // This function is not inline, so it's always codegen'ed on both the host
  14. // and the device. Therefore, it generates an error.
  15. __host__ __device__ void not_inline_hd() { host_only(); }

For the purposes of the wrong-side rule, templated functions also behave likeinline functions: They aren’t codegen’ed unless they’re instantiated(usually as part of the process of invoking them).

clang’s behavior with respect to the wrong-side rule matches nvcc’s, exceptnvcc only emits a warning for not_inline_hd; device code is allowed to callnot_inline_hd. In its generated code, nvcc may omit not_inline_hd’scall to host_only entirely, or it may try to generate code forhost_only on the device. What you get seems to depend on whether or notthe compiler chooses to inline host_only.

Member functions, including constructors, may be overloaded using H and Dattributes. However, destructors cannot be overloaded.

Using a Different Class on Host/Device

Occasionally you may want to have a class with different host/device versions.

If all of the class’s members are the same on the host and device, you can justprovide overloads for the class’s member functions.

However, if you want your class to have different members on host/device, youwon’t be able to provide working H and D overloads in both classes. In thiscase, clang is likely to be unhappy with you.

  1. #ifdef __CUDA_ARCH__
  2. struct S {
  3. __device__ void foo() { /* use device_only */ }
  4. int device_only;
  5. };
  6. #else
  7. struct S {
  8. __host__ void foo() { /* use host_only */ }
  9. double host_only;
  10. };
  11.  
  12. __device__ void test() {
  13. S s;
  14. // clang generates an error here, because during host compilation, we
  15. // have ifdef'ed away the __device__ overload of S::foo(). The __device__
  16. // overload must be present *even during host compilation*.
  17. S.foo();
  18. }
  19. #endif

We posit that you don’t really want to have classes with different members on Hand D. For example, if you were to pass one of these as a parameter to akernel, it would have a different layout on H and D, so would not workproperly.

To make code like this compatible with clang, we recommend you separate it outinto two classes. If you need to write code that works on both host anddevice, consider writing an overloaded wrapper function that returns differenttypes on host and device.

  1. struct HostS { ... };
  2. struct DeviceS { ... };
  3.  
  4. __host__ HostS MakeStruct() { return HostS(); }
  5. __device__ DeviceS MakeStruct() { return DeviceS(); }
  6.  
  7. // Now host and device code can call MakeStruct().

Unfortunately, this idiom isn’t compatible with nvcc, because it doesn’t allowyou to overload based on the H/D attributes. Here’s an idiom that works withboth clang and nvcc:

  1. struct HostS { ... };
  2. struct DeviceS { ... };
  3.  
  4. #ifdef __NVCC__
  5. #ifndef __CUDA_ARCH__
  6. __host__ HostS MakeStruct() { return HostS(); }
  7. #else
  8. __device__ DeviceS MakeStruct() { return DeviceS(); }
  9. #endif
  10. #else
  11. __host__ HostS MakeStruct() { return HostS(); }
  12. __device__ DeviceS MakeStruct() { return DeviceS(); }
  13. #endif
  14.  
  15. // Now host and device code can call MakeStruct().

Hopefully you don’t have to do this sort of thing often.

Optimizations

Modern CPUs and GPUs are architecturally quite different, so code that’s faston a CPU isn’t necessarily fast on a GPU. We’ve made a number of changes toLLVM to make it generate good GPU code. Among these changes are:

  • Straight-line scalar optimizations – Thesereduce redundancy within straight-line code.

  • Aggressive speculative execution– This is mainly for promoting straight-line scalar optimizations, which aremost effective on code along dominator paths.

  • Memory space inference –In PTX, we can operate on pointers that are in a particular “address space”(global, shared, constant, or local), or we can operate on pointers in the“generic” address space, which can point to anything. Operations in anon-generic address space are faster, but pointers in CUDA are not explicitlyannotated with their address space, so it’s up to LLVM to infer it wherepossible.

  • Bypassing 64-bit divides –This was an existing optimization that we enabled for the PTX backend.

64-bit integer divides are much slower than 32-bit ones on NVIDIA GPUs.Many of the 64-bit divides in our benchmarks have a divisor and dividendwhich fit in 32-bits at runtime. This optimization provides a fast path forthis common case.

  • Aggressive loop unrolling and function inlining – Loop unrolling andfunction inlining need to be more aggressive for GPUs than for CPUs becausecontrol flow transfer in GPU is more expensive. More aggressive unrolling andinlining also promote other optimizations, such as constant propagation andSROA, which sometimes speed up code by over 10x.

(Programmers can force unrolling and inline using clang’s loop unrolling pragmasand attribute((always_inline)).)

Publication

The team at Google published a paper in CGO 2016 detailing the optimizationsthey’d made to clang/LLVM. Note that “gpucc” is no longer a meaningful name:The relevant tools are now just vanilla clang/LLVM.

gpucc: An Open-Source GPGPU Compiler

Jingyue Wu, Artem Belevich, Eli Bendersky, Mark Heffernan, Chris Leary, Jacques Pienaar, Bjarke Roune, Rob Springer, Xuetian Weng, Robert Hundt

Proceedings of the 2016 International Symposium on Code Generation and Optimization (CGO 2016)

Slides from the CGO talk

Tutorial given at CGO

Obtaining Help

To obtain help on LLVM in general and its CUDA support, see the LLVMcommunity.