Vectorizers.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. ==========================
  2. Auto-Vectorization in LLVM
  3. ==========================
  4. .. contents::
  5. :local:
  6. NOTE: This document describes the Auto-Vectorization as used for the original
  7. LLVM project, not the DirectX Compiler.
  8. LLVM has two vectorizers: The :ref:`Loop Vectorizer <loop-vectorizer>`,
  9. which operates on Loops, and the :ref:`SLP Vectorizer
  10. <slp-vectorizer>`. These vectorizers
  11. focus on different optimization opportunities and use different techniques.
  12. The SLP vectorizer merges multiple scalars that are found in the code into
  13. vectors while the Loop Vectorizer widens instructions in loops
  14. to operate on multiple consecutive iterations.
  15. Both the Loop Vectorizer and the SLP Vectorizer are enabled by default.
  16. .. _loop-vectorizer:
  17. The Loop Vectorizer
  18. ===================
  19. Usage
  20. -----
  21. The Loop Vectorizer is enabled by default, but it can be disabled
  22. through clang using the command line flag:
  23. .. code-block:: console
  24. $ clang ... -fno-vectorize file.c
  25. Command line flags
  26. ^^^^^^^^^^^^^^^^^^
  27. The loop vectorizer uses a cost model to decide on the optimal vectorization factor
  28. and unroll factor. However, users of the vectorizer can force the vectorizer to use
  29. specific values. Both 'clang' and 'opt' support the flags below.
  30. Users can control the vectorization SIMD width using the command line flag "-force-vector-width".
  31. .. code-block:: console
  32. $ clang -mllvm -force-vector-width=8 ...
  33. $ opt -loop-vectorize -force-vector-width=8 ...
  34. Users can control the unroll factor using the command line flag "-force-vector-unroll"
  35. .. code-block:: console
  36. $ clang -mllvm -force-vector-unroll=2 ...
  37. $ opt -loop-vectorize -force-vector-unroll=2 ...
  38. Pragma loop hint directives
  39. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  40. The ``#pragma clang loop`` directive allows loop vectorization hints to be
  41. specified for the subsequent for, while, do-while, or c++11 range-based for
  42. loop. The directive allows vectorization and interleaving to be enabled or
  43. disabled. Vector width as well as interleave count can also be manually
  44. specified. The following example explicitly enables vectorization and
  45. interleaving:
  46. .. code-block:: c++
  47. #pragma clang loop vectorize(enable) interleave(enable)
  48. while(...) {
  49. ...
  50. }
  51. The following example implicitly enables vectorization and interleaving by
  52. specifying a vector width and interleaving count:
  53. .. code-block:: c++
  54. #pragma clang loop vectorize_width(2) interleave_count(2)
  55. for(...) {
  56. ...
  57. }
  58. See the Clang
  59. `language extensions
  60. <http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
  61. for details.
  62. Diagnostics
  63. -----------
  64. Many loops cannot be vectorized including loops with complicated control flow,
  65. unvectorizable types, and unvectorizable calls. The loop vectorizer generates
  66. optimization remarks which can be queried using command line options to identify
  67. and diagnose loops that are skipped by the loop-vectorizer.
  68. Optimization remarks are enabled using:
  69. ``-Rpass=loop-vectorize`` identifies loops that were successfully vectorized.
  70. ``-Rpass-missed=loop-vectorize`` identifies loops that failed vectorization and
  71. indicates if vectorization was specified.
  72. ``-Rpass-analysis=loop-vectorize`` identifies the statements that caused
  73. vectorization to fail.
  74. Consider the following loop:
  75. .. code-block:: c++
  76. #pragma clang loop vectorize(enable)
  77. for (int i = 0; i < Length; i++) {
  78. switch(A[i]) {
  79. case 0: A[i] = i*2; break;
  80. case 1: A[i] = i; break;
  81. default: A[i] = 0;
  82. }
  83. }
  84. The command line ``-Rpass-missed=loop-vectorized`` prints the remark:
  85. .. code-block:: console
  86. no_switch.cpp:4:5: remark: loop not vectorized: vectorization is explicitly enabled [-Rpass-missed=loop-vectorize]
  87. And the command line ``-Rpass-analysis=loop-vectorize`` indicates that the
  88. switch statement cannot be vectorized.
  89. .. code-block:: console
  90. no_switch.cpp:4:5: remark: loop not vectorized: loop contains a switch statement [-Rpass-analysis=loop-vectorize]
  91. switch(A[i]) {
  92. ^
  93. To ensure line and column numbers are produced include the command line options
  94. ``-gline-tables-only`` and ``-gcolumn-info``. See the Clang `user manual
  95. <http://clang.llvm.org/docs/UsersManual.html#options-to-emit-optimization-reports>`_
  96. for details
  97. Features
  98. --------
  99. The LLVM Loop Vectorizer has a number of features that allow it to vectorize
  100. complex loops.
  101. Loops with unknown trip count
  102. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  103. The Loop Vectorizer supports loops with an unknown trip count.
  104. In the loop below, the iteration ``start`` and ``finish`` points are unknown,
  105. and the Loop Vectorizer has a mechanism to vectorize loops that do not start
  106. at zero. In this example, 'n' may not be a multiple of the vector width, and
  107. the vectorizer has to execute the last few iterations as scalar code. Keeping
  108. a scalar copy of the loop increases the code size.
  109. .. code-block:: c++
  110. void bar(float *A, float* B, float K, int start, int end) {
  111. for (int i = start; i < end; ++i)
  112. A[i] *= B[i] + K;
  113. }
  114. Runtime Checks of Pointers
  115. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  116. In the example below, if the pointers A and B point to consecutive addresses,
  117. then it is illegal to vectorize the code because some elements of A will be
  118. written before they are read from array B.
  119. Some programmers use the 'restrict' keyword to notify the compiler that the
  120. pointers are disjointed, but in our example, the Loop Vectorizer has no way of
  121. knowing that the pointers A and B are unique. The Loop Vectorizer handles this
  122. loop by placing code that checks, at runtime, if the arrays A and B point to
  123. disjointed memory locations. If arrays A and B overlap, then the scalar version
  124. of the loop is executed.
  125. .. code-block:: c++
  126. void bar(float *A, float* B, float K, int n) {
  127. for (int i = 0; i < n; ++i)
  128. A[i] *= B[i] + K;
  129. }
  130. Reductions
  131. ^^^^^^^^^^
  132. In this example the ``sum`` variable is used by consecutive iterations of
  133. the loop. Normally, this would prevent vectorization, but the vectorizer can
  134. detect that 'sum' is a reduction variable. The variable 'sum' becomes a vector
  135. of integers, and at the end of the loop the elements of the array are added
  136. together to create the correct result. We support a number of different
  137. reduction operations, such as addition, multiplication, XOR, AND and OR.
  138. .. code-block:: c++
  139. int foo(int *A, int *B, int n) {
  140. unsigned sum = 0;
  141. for (int i = 0; i < n; ++i)
  142. sum += A[i] + 5;
  143. return sum;
  144. }
  145. We support floating point reduction operations when `-ffast-math` is used.
  146. Inductions
  147. ^^^^^^^^^^
  148. In this example the value of the induction variable ``i`` is saved into an
  149. array. The Loop Vectorizer knows to vectorize induction variables.
  150. .. code-block:: c++
  151. void bar(float *A, float* B, float K, int n) {
  152. for (int i = 0; i < n; ++i)
  153. A[i] = i;
  154. }
  155. If Conversion
  156. ^^^^^^^^^^^^^
  157. The Loop Vectorizer is able to "flatten" the IF statement in the code and
  158. generate a single stream of instructions. The Loop Vectorizer supports any
  159. control flow in the innermost loop. The innermost loop may contain complex
  160. nesting of IFs, ELSEs and even GOTOs.
  161. .. code-block:: c++
  162. int foo(int *A, int *B, int n) {
  163. unsigned sum = 0;
  164. for (int i = 0; i < n; ++i)
  165. if (A[i] > B[i])
  166. sum += A[i] + 5;
  167. return sum;
  168. }
  169. Pointer Induction Variables
  170. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  171. This example uses the "accumulate" function of the standard c++ library. This
  172. loop uses C++ iterators, which are pointers, and not integer indices.
  173. The Loop Vectorizer detects pointer induction variables and can vectorize
  174. this loop. This feature is important because many C++ programs use iterators.
  175. .. code-block:: c++
  176. int baz(int *A, int n) {
  177. return std::accumulate(A, A + n, 0);
  178. }
  179. Reverse Iterators
  180. ^^^^^^^^^^^^^^^^^
  181. The Loop Vectorizer can vectorize loops that count backwards.
  182. .. code-block:: c++
  183. int foo(int *A, int *B, int n) {
  184. for (int i = n; i > 0; --i)
  185. A[i] +=1;
  186. }
  187. Scatter / Gather
  188. ^^^^^^^^^^^^^^^^
  189. The Loop Vectorizer can vectorize code that becomes a sequence of scalar instructions
  190. that scatter/gathers memory.
  191. .. code-block:: c++
  192. int foo(int * A, int * B, int n) {
  193. for (intptr_t i = 0; i < n; ++i)
  194. A[i] += B[i * 4];
  195. }
  196. In many situations the cost model will inform LLVM that this is not beneficial
  197. and LLVM will only vectorize such code if forced with "-mllvm -force-vector-width=#".
  198. Vectorization of Mixed Types
  199. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  200. The Loop Vectorizer can vectorize programs with mixed types. The Vectorizer
  201. cost model can estimate the cost of the type conversion and decide if
  202. vectorization is profitable.
  203. .. code-block:: c++
  204. int foo(int *A, char *B, int n, int k) {
  205. for (int i = 0; i < n; ++i)
  206. A[i] += 4 * B[i];
  207. }
  208. Global Structures Alias Analysis
  209. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  210. Access to global structures can also be vectorized, with alias analysis being
  211. used to make sure accesses don't alias. Run-time checks can also be added on
  212. pointer access to structure members.
  213. Many variations are supported, but some that rely on undefined behaviour being
  214. ignored (as other compilers do) are still being left un-vectorized.
  215. .. code-block:: c++
  216. struct { int A[100], K, B[100]; } Foo;
  217. int foo() {
  218. for (int i = 0; i < 100; ++i)
  219. Foo.A[i] = Foo.B[i] + 100;
  220. }
  221. Vectorization of function calls
  222. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  223. The Loop Vectorize can vectorize intrinsic math functions.
  224. See the table below for a list of these functions.
  225. +-----+-----+---------+
  226. | pow | exp | exp2 |
  227. +-----+-----+---------+
  228. | sin | cos | sqrt |
  229. +-----+-----+---------+
  230. | log |log2 | log10 |
  231. +-----+-----+---------+
  232. |fabs |floor| ceil |
  233. +-----+-----+---------+
  234. |fma |trunc|nearbyint|
  235. +-----+-----+---------+
  236. | | | fmuladd |
  237. +-----+-----+---------+
  238. The loop vectorizer knows about special instructions on the target and will
  239. vectorize a loop containing a function call that maps to the instructions. For
  240. example, the loop below will be vectorized on Intel x86 if the SSE4.1 roundps
  241. instruction is available.
  242. .. code-block:: c++
  243. void foo(float *f) {
  244. for (int i = 0; i != 1024; ++i)
  245. f[i] = floorf(f[i]);
  246. }
  247. Partial unrolling during vectorization
  248. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  249. Modern processors feature multiple execution units, and only programs that contain a
  250. high degree of parallelism can fully utilize the entire width of the machine.
  251. The Loop Vectorizer increases the instruction level parallelism (ILP) by
  252. performing partial-unrolling of loops.
  253. In the example below the entire array is accumulated into the variable 'sum'.
  254. This is inefficient because only a single execution port can be used by the processor.
  255. By unrolling the code the Loop Vectorizer allows two or more execution ports
  256. to be used simultaneously.
  257. .. code-block:: c++
  258. int foo(int *A, int *B, int n) {
  259. unsigned sum = 0;
  260. for (int i = 0; i < n; ++i)
  261. sum += A[i];
  262. return sum;
  263. }
  264. The Loop Vectorizer uses a cost model to decide when it is profitable to unroll loops.
  265. The decision to unroll the loop depends on the register pressure and the generated code size.
  266. .. _slp-vectorizer:
  267. The SLP Vectorizer
  268. ==================
  269. Details
  270. -------
  271. The goal of SLP vectorization (a.k.a. superword-level parallelism) is
  272. to combine similar independent instructions
  273. into vector instructions. Memory accesses, arithmetic operations, comparison
  274. operations, PHI-nodes, can all be vectorized using this technique.
  275. For example, the following function performs very similar operations on its
  276. inputs (a1, b1) and (a2, b2). The basic-block vectorizer may combine these
  277. into vector operations.
  278. .. code-block:: c++
  279. void foo(int a1, int a2, int b1, int b2, int *A) {
  280. A[0] = a1*(a1 + b1)/b1 + 50*b1/a1;
  281. A[1] = a2*(a2 + b2)/b2 + 50*b2/a2;
  282. }
  283. The SLP-vectorizer processes the code bottom-up, across basic blocks, in search of scalars to combine.
  284. Usage
  285. ------
  286. The SLP Vectorizer is enabled by default, but it can be disabled
  287. through clang using the command line flag:
  288. .. code-block:: console
  289. $ clang -fno-slp-vectorize file.c
  290. LLVM has a second basic block vectorization phase
  291. which is more compile-time intensive (The BB vectorizer). This optimization
  292. can be enabled through clang using the command line flag:
  293. .. code-block:: console
  294. $ clang -fslp-vectorize-aggressive file.c