CompileCudaWithLLVM.rst 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. =========================
  2. Compiling CUDA with clang
  3. =========================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. This document describes how to compile CUDA code with clang, and gives some
  9. details about LLVM and clang's CUDA implementations.
  10. This document assumes a basic familiarity with CUDA. Information about CUDA
  11. programming can be found in the
  12. `CUDA programming guide
  13. <http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html>`_.
  14. Compiling CUDA Code
  15. ===================
  16. Prerequisites
  17. -------------
  18. CUDA is supported since llvm 3.9. Current release of clang (7.0.0) supports CUDA
  19. 7.0 through 9.2. If you need support for CUDA 10, you will need to use clang
  20. built from r342924 or newer.
  21. Before you build CUDA code, you'll need to have installed the appropriate driver
  22. for your nvidia GPU and the CUDA SDK. See `NVIDIA's CUDA installation guide
  23. <https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html>`_ for
  24. details. Note that clang `does not support
  25. <https://llvm.org/bugs/show_bug.cgi?id=26966>`_ the CUDA toolkit as installed by
  26. many Linux package managers; you probably need to install CUDA in a single
  27. directory from NVIDIA's package.
  28. CUDA compilation is supported on Linux. Compilation on MacOS and Windows may or
  29. may not work and currently have no maintainers. Compilation with CUDA-9.x is
  30. `currently broken on Windows <https://bugs.llvm.org/show_bug.cgi?id=38811>`_.
  31. Invoking clang
  32. --------------
  33. Invoking clang for CUDA compilation works similarly to compiling regular C++.
  34. You just need to be aware of a few additional flags.
  35. You can use `this <https://gist.github.com/855e277884eb6b388cd2f00d956c2fd4>`_
  36. program as a toy example. Save it as ``axpy.cu``. (Clang detects that you're
  37. compiling CUDA code by noticing that your filename ends with ``.cu``.
  38. Alternatively, you can pass ``-x cuda``.)
  39. To build and run, run the following commands, filling in the parts in angle
  40. brackets as described below:
  41. .. code-block:: console
  42. $ clang++ axpy.cu -o axpy --cuda-gpu-arch=<GPU arch> \
  43. -L<CUDA install path>/<lib64 or lib> \
  44. -lcudart_static -ldl -lrt -pthread
  45. $ ./axpy
  46. y[0] = 2
  47. y[1] = 4
  48. y[2] = 6
  49. y[3] = 8
  50. On MacOS, replace `-lcudart_static` with `-lcudart`; otherwise, you may get
  51. "CUDA driver version is insufficient for CUDA runtime version" errors when you
  52. run your program.
  53. * ``<CUDA install path>`` -- the directory where you installed CUDA SDK.
  54. Typically, ``/usr/local/cuda``.
  55. Pass e.g. ``-L/usr/local/cuda/lib64`` if compiling in 64-bit mode; otherwise,
  56. pass e.g. ``-L/usr/local/cuda/lib``. (In CUDA, the device code and host code
  57. always have the same pointer widths, so if you're compiling 64-bit code for
  58. the host, you're also compiling 64-bit code for the device.) Note that as of
  59. v10.0 CUDA SDK `no longer supports compilation of 32-bit
  60. applications <https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#deprecated-features>`_.
  61. * ``<GPU arch>`` -- the `compute capability
  62. <https://developer.nvidia.com/cuda-gpus>`_ of your GPU. For example, if you
  63. want to run your program on a GPU with compute capability of 3.5, specify
  64. ``--cuda-gpu-arch=sm_35``.
  65. Note: You cannot pass ``compute_XX`` as an argument to ``--cuda-gpu-arch``;
  66. only ``sm_XX`` is currently supported. However, clang always includes PTX in
  67. its binaries, so e.g. a binary compiled with ``--cuda-gpu-arch=sm_30`` would be
  68. forwards-compatible with e.g. ``sm_35`` GPUs.
  69. You can pass ``--cuda-gpu-arch`` multiple times to compile for multiple archs.
  70. The `-L` and `-l` flags only need to be passed when linking. When compiling,
  71. you may also need to pass ``--cuda-path=/path/to/cuda`` if you didn't install
  72. the CUDA SDK into ``/usr/local/cuda`` or ``/usr/local/cuda-X.Y``.
  73. Flags that control numerical code
  74. ---------------------------------
  75. If you're using GPUs, you probably care about making numerical code run fast.
  76. GPU hardware allows for more control over numerical operations than most CPUs,
  77. but this results in more compiler options for you to juggle.
  78. Flags you may wish to tweak include:
  79. * ``-ffp-contract={on,off,fast}`` (defaults to ``fast`` on host and device when
  80. compiling CUDA) Controls whether the compiler emits fused multiply-add
  81. operations.
  82. * ``off``: never emit fma operations, and prevent ptxas from fusing multiply
  83. and add instructions.
  84. * ``on``: fuse multiplies and adds within a single statement, but never
  85. across statements (C11 semantics). Prevent ptxas from fusing other
  86. multiplies and adds.
  87. * ``fast``: fuse multiplies and adds wherever profitable, even across
  88. statements. Doesn't prevent ptxas from fusing additional multiplies and
  89. adds.
  90. Fused multiply-add instructions can be much faster than the unfused
  91. equivalents, but because the intermediate result in an fma is not rounded,
  92. this flag can affect numerical code.
  93. * ``-fcuda-flush-denormals-to-zero`` (default: off) When this is enabled,
  94. floating point operations may flush `denormal
  95. <https://en.wikipedia.org/wiki/Denormal_number>`_ inputs and/or outputs to 0.
  96. Operations on denormal numbers are often much slower than the same operations
  97. on normal numbers.
  98. * ``-fcuda-approx-transcendentals`` (default: off) When this is enabled, the
  99. compiler may emit calls to faster, approximate versions of transcendental
  100. functions, instead of using the slower, fully IEEE-compliant versions. For
  101. example, this flag allows clang to emit the ptx ``sin.approx.f32``
  102. instruction.
  103. This is implied by ``-ffast-math``.
  104. Standard library support
  105. ========================
  106. In clang and nvcc, most of the C++ standard library is not supported on the
  107. device side.
  108. ``<math.h>`` and ``<cmath>``
  109. ----------------------------
  110. In clang, ``math.h`` and ``cmath`` are available and `pass
  111. <https://github.com/llvm/llvm-test-suite/blob/master/External/CUDA/math_h.cu>`_
  112. `tests
  113. <https://github.com/llvm/llvm-test-suite/blob/master/External/CUDA/cmath.cu>`_
  114. adapted from libc++'s test suite.
  115. In nvcc ``math.h`` and ``cmath`` are mostly available. Versions of ``::foof``
  116. in namespace std (e.g. ``std::sinf``) are not available, and where the standard
  117. calls for overloads that take integral arguments, these are usually not
  118. available.
  119. .. code-block:: c++
  120. #include <math.h>
  121. #include <cmath.h>
  122. // clang is OK with everything in this function.
  123. __device__ void test() {
  124. std::sin(0.); // nvcc - ok
  125. std::sin(0); // nvcc - error, because no std::sin(int) override is available.
  126. sin(0); // nvcc - same as above.
  127. sinf(0.); // nvcc - ok
  128. std::sinf(0.); // nvcc - no such function
  129. }
  130. ``<std::complex>``
  131. ------------------
  132. nvcc does not officially support ``std::complex``. It's an error to use
  133. ``std::complex`` in ``__device__`` code, but it often works in ``__host__
  134. __device__`` code due to nvcc's interpretation of the "wrong-side rule" (see
  135. below). However, we have heard from implementers that it's possible to get
  136. into situations where nvcc will omit a call to an ``std::complex`` function,
  137. especially when compiling without optimizations.
  138. As of 2016-11-16, clang supports ``std::complex`` without these caveats. It is
  139. tested with libstdc++ 4.8.5 and newer, but is known to work only with libc++
  140. newer than 2016-11-16.
  141. ``<algorithm>``
  142. ---------------
  143. In C++14, many useful functions from ``<algorithm>`` (notably, ``std::min`` and
  144. ``std::max``) become constexpr. You can therefore use these in device code,
  145. when compiling with clang.
  146. Detecting clang vs NVCC from code
  147. =================================
  148. Although clang's CUDA implementation is largely compatible with NVCC's, you may
  149. still want to detect when you're compiling CUDA code specifically with clang.
  150. This is tricky, because NVCC may invoke clang as part of its own compilation
  151. process! For example, NVCC uses the host compiler's preprocessor when
  152. compiling for device code, and that host compiler may in fact be clang.
  153. When clang is actually compiling CUDA code -- rather than being used as a
  154. subtool of NVCC's -- it defines the ``__CUDA__`` macro. ``__CUDA_ARCH__`` is
  155. defined only in device mode (but will be defined if NVCC is using clang as a
  156. preprocessor). So you can use the following incantations to detect clang CUDA
  157. compilation, in host and device modes:
  158. .. code-block:: c++
  159. #if defined(__clang__) && defined(__CUDA__) && !defined(__CUDA_ARCH__)
  160. // clang compiling CUDA code, host mode.
  161. #endif
  162. #if defined(__clang__) && defined(__CUDA__) && defined(__CUDA_ARCH__)
  163. // clang compiling CUDA code, device mode.
  164. #endif
  165. Both clang and nvcc define ``__CUDACC__`` during CUDA compilation. You can
  166. detect NVCC specifically by looking for ``__NVCC__``.
  167. Dialect Differences Between clang and nvcc
  168. ==========================================
  169. There is no formal CUDA spec, and clang and nvcc speak slightly different
  170. dialects of the language. Below, we describe some of the differences.
  171. This section is painful; hopefully you can skip this section and live your life
  172. blissfully unaware.
  173. Compilation Models
  174. ------------------
  175. Most of the differences between clang and nvcc stem from the different
  176. compilation models used by clang and nvcc. nvcc uses *split compilation*,
  177. which works roughly as follows:
  178. * Run a preprocessor over the input ``.cu`` file to split it into two source
  179. files: ``H``, containing source code for the host, and ``D``, containing
  180. source code for the device.
  181. * For each GPU architecture ``arch`` that we're compiling for, do:
  182. * Compile ``D`` using nvcc proper. The result of this is a ``ptx`` file for
  183. ``P_arch``.
  184. * Optionally, invoke ``ptxas``, the PTX assembler, to generate a file,
  185. ``S_arch``, containing GPU machine code (SASS) for ``arch``.
  186. * Invoke ``fatbin`` to combine all ``P_arch`` and ``S_arch`` files into a
  187. single "fat binary" file, ``F``.
  188. * Compile ``H`` using an external host compiler (gcc, clang, or whatever you
  189. like). ``F`` is packaged up into a header file which is force-included into
  190. ``H``; nvcc generates code that calls into this header to e.g. launch
  191. kernels.
  192. clang uses *merged parsing*. This is similar to split compilation, except all
  193. of the host and device code is present and must be semantically-correct in both
  194. compilation steps.
  195. * For each GPU architecture ``arch`` that we're compiling for, do:
  196. * Compile the input ``.cu`` file for device, using clang. ``__host__`` code
  197. is parsed and must be semantically correct, even though we're not
  198. generating code for the host at this time.
  199. The output of this step is a ``ptx`` file ``P_arch``.
  200. * Invoke ``ptxas`` to generate a SASS file, ``S_arch``. Note that, unlike
  201. nvcc, clang always generates SASS code.
  202. * Invoke ``fatbin`` to combine all ``P_arch`` and ``S_arch`` files into a
  203. single fat binary file, ``F``.
  204. * Compile ``H`` using clang. ``__device__`` code is parsed and must be
  205. semantically correct, even though we're not generating code for the device
  206. at this time.
  207. ``F`` is passed to this compilation, and clang includes it in a special ELF
  208. section, where it can be found by tools like ``cuobjdump``.
  209. (You may ask at this point, why does clang need to parse the input file
  210. multiple times? Why not parse it just once, and then use the AST to generate
  211. code for the host and each device architecture?
  212. Unfortunately this can't work because we have to define different macros during
  213. host compilation and during device compilation for each GPU architecture.)
  214. clang's approach allows it to be highly robust to C++ edge cases, as it doesn't
  215. need to decide at an early stage which declarations to keep and which to throw
  216. away. But it has some consequences you should be aware of.
  217. Overloading Based on ``__host__`` and ``__device__`` Attributes
  218. ---------------------------------------------------------------
  219. Let "H", "D", and "HD" stand for "``__host__`` functions", "``__device__``
  220. functions", and "``__host__ __device__`` functions", respectively. Functions
  221. with no attributes behave the same as H.
  222. nvcc does not allow you to create H and D functions with the same signature:
  223. .. code-block:: c++
  224. // nvcc: error - function "foo" has already been defined
  225. __host__ void foo() {}
  226. __device__ void foo() {}
  227. However, nvcc allows you to "overload" H and D functions with different
  228. signatures:
  229. .. code-block:: c++
  230. // nvcc: no error
  231. __host__ void foo(int) {}
  232. __device__ void foo() {}
  233. In clang, the ``__host__`` and ``__device__`` attributes are part of a
  234. function's signature, and so it's legal to have H and D functions with
  235. (otherwise) the same signature:
  236. .. code-block:: c++
  237. // clang: no error
  238. __host__ void foo() {}
  239. __device__ void foo() {}
  240. HD functions cannot be overloaded by H or D functions with the same signature:
  241. .. code-block:: c++
  242. // nvcc: error - function "foo" has already been defined
  243. // clang: error - redefinition of 'foo'
  244. __host__ __device__ void foo() {}
  245. __device__ void foo() {}
  246. // nvcc: no error
  247. // clang: no error
  248. __host__ __device__ void bar(int) {}
  249. __device__ void bar() {}
  250. When resolving an overloaded function, clang considers the host/device
  251. attributes of the caller and callee. These are used as a tiebreaker during
  252. overload resolution. See `IdentifyCUDAPreference
  253. <http://clang.llvm.org/doxygen/SemaCUDA_8cpp.html>`_ for the full set of rules,
  254. but at a high level they are:
  255. * D functions prefer to call other Ds. HDs are given lower priority.
  256. * Similarly, H functions prefer to call other Hs, or ``__global__`` functions
  257. (with equal priority). HDs are given lower priority.
  258. * HD functions prefer to call other HDs.
  259. When compiling for device, HDs will call Ds with lower priority than HD, and
  260. will call Hs with still lower priority. If it's forced to call an H, the
  261. program is malformed if we emit code for this HD function. We call this the
  262. "wrong-side rule", see example below.
  263. The rules are symmetrical when compiling for host.
  264. Some examples:
  265. .. code-block:: c++
  266. __host__ void foo();
  267. __device__ void foo();
  268. __host__ void bar();
  269. __host__ __device__ void bar();
  270. __host__ void test_host() {
  271. foo(); // calls H overload
  272. bar(); // calls H overload
  273. }
  274. __device__ void test_device() {
  275. foo(); // calls D overload
  276. bar(); // calls HD overload
  277. }
  278. __host__ __device__ void test_hd() {
  279. foo(); // calls H overload when compiling for host, otherwise D overload
  280. bar(); // always calls HD overload
  281. }
  282. Wrong-side rule example:
  283. .. code-block:: c++
  284. __host__ void host_only();
  285. // We don't codegen inline functions unless they're referenced by a
  286. // non-inline function. inline_hd1() is called only from the host side, so
  287. // does not generate an error. inline_hd2() is called from the device side,
  288. // so it generates an error.
  289. inline __host__ __device__ void inline_hd1() { host_only(); } // no error
  290. inline __host__ __device__ void inline_hd2() { host_only(); } // error
  291. __host__ void host_fn() { inline_hd1(); }
  292. __device__ void device_fn() { inline_hd2(); }
  293. // This function is not inline, so it's always codegen'ed on both the host
  294. // and the device. Therefore, it generates an error.
  295. __host__ __device__ void not_inline_hd() { host_only(); }
  296. For the purposes of the wrong-side rule, templated functions also behave like
  297. ``inline`` functions: They aren't codegen'ed unless they're instantiated
  298. (usually as part of the process of invoking them).
  299. clang's behavior with respect to the wrong-side rule matches nvcc's, except
  300. nvcc only emits a warning for ``not_inline_hd``; device code is allowed to call
  301. ``not_inline_hd``. In its generated code, nvcc may omit ``not_inline_hd``'s
  302. call to ``host_only`` entirely, or it may try to generate code for
  303. ``host_only`` on the device. What you get seems to depend on whether or not
  304. the compiler chooses to inline ``host_only``.
  305. Member functions, including constructors, may be overloaded using H and D
  306. attributes. However, destructors cannot be overloaded.
  307. Using a Different Class on Host/Device
  308. --------------------------------------
  309. Occasionally you may want to have a class with different host/device versions.
  310. If all of the class's members are the same on the host and device, you can just
  311. provide overloads for the class's member functions.
  312. However, if you want your class to have different members on host/device, you
  313. won't be able to provide working H and D overloads in both classes. In this
  314. case, clang is likely to be unhappy with you.
  315. .. code-block:: c++
  316. #ifdef __CUDA_ARCH__
  317. struct S {
  318. __device__ void foo() { /* use device_only */ }
  319. int device_only;
  320. };
  321. #else
  322. struct S {
  323. __host__ void foo() { /* use host_only */ }
  324. double host_only;
  325. };
  326. __device__ void test() {
  327. S s;
  328. // clang generates an error here, because during host compilation, we
  329. // have ifdef'ed away the __device__ overload of S::foo(). The __device__
  330. // overload must be present *even during host compilation*.
  331. S.foo();
  332. }
  333. #endif
  334. We posit that you don't really want to have classes with different members on H
  335. and D. For example, if you were to pass one of these as a parameter to a
  336. kernel, it would have a different layout on H and D, so would not work
  337. properly.
  338. To make code like this compatible with clang, we recommend you separate it out
  339. into two classes. If you need to write code that works on both host and
  340. device, consider writing an overloaded wrapper function that returns different
  341. types on host and device.
  342. .. code-block:: c++
  343. struct HostS { ... };
  344. struct DeviceS { ... };
  345. __host__ HostS MakeStruct() { return HostS(); }
  346. __device__ DeviceS MakeStruct() { return DeviceS(); }
  347. // Now host and device code can call MakeStruct().
  348. Unfortunately, this idiom isn't compatible with nvcc, because it doesn't allow
  349. you to overload based on the H/D attributes. Here's an idiom that works with
  350. both clang and nvcc:
  351. .. code-block:: c++
  352. struct HostS { ... };
  353. struct DeviceS { ... };
  354. #ifdef __NVCC__
  355. #ifndef __CUDA_ARCH__
  356. __host__ HostS MakeStruct() { return HostS(); }
  357. #else
  358. __device__ DeviceS MakeStruct() { return DeviceS(); }
  359. #endif
  360. #else
  361. __host__ HostS MakeStruct() { return HostS(); }
  362. __device__ DeviceS MakeStruct() { return DeviceS(); }
  363. #endif
  364. // Now host and device code can call MakeStruct().
  365. Hopefully you don't have to do this sort of thing often.
  366. Optimizations
  367. =============
  368. Modern CPUs and GPUs are architecturally quite different, so code that's fast
  369. on a CPU isn't necessarily fast on a GPU. We've made a number of changes to
  370. LLVM to make it generate good GPU code. Among these changes are:
  371. * `Straight-line scalar optimizations <https://goo.gl/4Rb9As>`_ -- These
  372. reduce redundancy within straight-line code.
  373. * `Aggressive speculative execution
  374. <http://llvm.org/docs/doxygen/html/SpeculativeExecution_8cpp_source.html>`_
  375. -- This is mainly for promoting straight-line scalar optimizations, which are
  376. most effective on code along dominator paths.
  377. * `Memory space inference
  378. <http://llvm.org/doxygen/NVPTXInferAddressSpaces_8cpp_source.html>`_ --
  379. In PTX, we can operate on pointers that are in a paricular "address space"
  380. (global, shared, constant, or local), or we can operate on pointers in the
  381. "generic" address space, which can point to anything. Operations in a
  382. non-generic address space are faster, but pointers in CUDA are not explicitly
  383. annotated with their address space, so it's up to LLVM to infer it where
  384. possible.
  385. * `Bypassing 64-bit divides
  386. <http://llvm.org/docs/doxygen/html/BypassSlowDivision_8cpp_source.html>`_ --
  387. This was an existing optimization that we enabled for the PTX backend.
  388. 64-bit integer divides are much slower than 32-bit ones on NVIDIA GPUs.
  389. Many of the 64-bit divides in our benchmarks have a divisor and dividend
  390. which fit in 32-bits at runtime. This optimization provides a fast path for
  391. this common case.
  392. * Aggressive loop unrooling and function inlining -- Loop unrolling and
  393. function inlining need to be more aggressive for GPUs than for CPUs because
  394. control flow transfer in GPU is more expensive. More aggressive unrolling and
  395. inlining also promote other optimizations, such as constant propagation and
  396. SROA, which sometimes speed up code by over 10x.
  397. (Programmers can force unrolling and inline using clang's `loop unrolling pragmas
  398. <http://clang.llvm.org/docs/AttributeReference.html#pragma-unroll-pragma-nounroll>`_
  399. and ``__attribute__((always_inline))``.)
  400. Publication
  401. ===========
  402. The team at Google published a paper in CGO 2016 detailing the optimizations
  403. they'd made to clang/LLVM. Note that "gpucc" is no longer a meaningful name:
  404. The relevant tools are now just vanilla clang/LLVM.
  405. | `gpucc: An Open-Source GPGPU Compiler <http://dl.acm.org/citation.cfm?id=2854041>`_
  406. | Jingyue Wu, Artem Belevich, Eli Bendersky, Mark Heffernan, Chris Leary, Jacques Pienaar, Bjarke Roune, Rob Springer, Xuetian Weng, Robert Hundt
  407. | *Proceedings of the 2016 International Symposium on Code Generation and Optimization (CGO 2016)*
  408. |
  409. | `Slides from the CGO talk <http://wujingyue.github.io/docs/gpucc-talk.pdf>`_
  410. |
  411. | `Tutorial given at CGO <http://wujingyue.github.io/docs/gpucc-tutorial.pdf>`_
  412. Obtaining Help
  413. ==============
  414. To obtain help on LLVM in general and its CUDA support, see `the LLVM
  415. community <http://llvm.org/docs/#mailing-lists>`_.