blob: b75177545c10f3761e84f38ef88234c2fd7a9c5e [file] [log] [blame]
Sean Silva709c44d2012-12-12 23:44:55 +00001=========================
2Clang Language Extensions
3=========================
4
5.. contents::
6 :local:
Sean Silva13d43fe2013-01-02 21:09:58 +00007 :depth: 1
Sean Silva709c44d2012-12-12 23:44:55 +00008
Sean Silvaf380e0e2013-01-02 21:03:11 +00009.. toctree::
10 :hidden:
11
12 ObjectiveCLiterals
13 BlockLanguageSpec
Michael Gottesman6fd58462013-01-07 22:24:45 +000014 Block-ABI-Apple
DeLesley Hutchinsc51e08c2014-02-18 19:42:01 +000015 AutomaticReferenceCounting
Sean Silvaf380e0e2013-01-02 21:03:11 +000016
Sean Silva709c44d2012-12-12 23:44:55 +000017Introduction
18============
19
20This document describes the language extensions provided by Clang. In addition
21to the language extensions listed here, Clang aims to support a broad range of
22GCC extensions. Please see the `GCC manual
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +000023<https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on
Sean Silva709c44d2012-12-12 23:44:55 +000024these extensions.
25
26.. _langext-feature_check:
27
28Feature Checking Macros
29=======================
30
31Language extensions can be very useful, but only if you know you can depend on
32them. In order to allow fine-grain features checks, we support three builtin
33function-like macros. This allows you to directly test for a feature in your
34code without having to resort to something like autoconf or fragile "compiler
35version checks".
36
37``__has_builtin``
38-----------------
39
40This function-like macro takes a single identifier argument that is the name of
Richard Smithdac3ea42019-08-14 02:30:11 +000041a builtin function, a builtin pseudo-function (taking one or more type
42arguments), or a builtin template.
43It evaluates to 1 if the builtin is supported or 0 if not.
Sean Silva709c44d2012-12-12 23:44:55 +000044It can be used like this:
45
46.. code-block:: c++
47
48 #ifndef __has_builtin // Optional of course.
49 #define __has_builtin(x) 0 // Compatibility with non-clang compilers.
50 #endif
51
52 ...
53 #if __has_builtin(__builtin_trap)
54 __builtin_trap();
55 #else
56 abort();
57 #endif
58 ...
59
Richard Smithdac3ea42019-08-14 02:30:11 +000060.. note::
61
62 Prior to Clang 10, ``__has_builtin`` could not be used to detect most builtin
63 pseudo-functions.
64
65 ``__has_builtin`` should not be used to detect support for a builtin macro;
66 use ``#ifdef`` instead.
67
Sean Silva709c44d2012-12-12 23:44:55 +000068.. _langext-__has_feature-__has_extension:
69
70``__has_feature`` and ``__has_extension``
71-----------------------------------------
72
73These function-like macros take a single identifier argument that is the name
74of a feature. ``__has_feature`` evaluates to 1 if the feature is both
75supported by Clang and standardized in the current language standard or 0 if
76not (but see :ref:`below <langext-has-feature-back-compat>`), while
77``__has_extension`` evaluates to 1 if the feature is supported by Clang in the
78current language (either as a language extension or a standard language
79feature) or 0 if not. They can be used like this:
80
81.. code-block:: c++
82
83 #ifndef __has_feature // Optional of course.
84 #define __has_feature(x) 0 // Compatibility with non-clang compilers.
85 #endif
86 #ifndef __has_extension
87 #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
88 #endif
89
90 ...
91 #if __has_feature(cxx_rvalue_references)
92 // This code will only be compiled with the -std=c++11 and -std=gnu++11
93 // options, because rvalue references are only standardized in C++11.
94 #endif
95
96 #if __has_extension(cxx_rvalue_references)
97 // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98
98 // and -std=gnu++98 options, because rvalue references are supported as a
99 // language extension in C++98.
100 #endif
101
102.. _langext-has-feature-back-compat:
103
Alp Toker958027b2014-07-14 19:42:55 +0000104For backward compatibility, ``__has_feature`` can also be used to test
Sean Silva709c44d2012-12-12 23:44:55 +0000105for support for non-standardized features, i.e. features not prefixed ``c_``,
106``cxx_`` or ``objc_``.
107
108Another use of ``__has_feature`` is to check for compiler features not related
Sean Silva173d2522013-01-02 13:07:47 +0000109to the language standard, such as e.g. :doc:`AddressSanitizer
110<AddressSanitizer>`.
Sean Silva709c44d2012-12-12 23:44:55 +0000111
112If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent
113to ``__has_feature``.
114
115The feature tag is described along with the language feature below.
116
117The feature name or extension name can also be specified with a preceding and
118following ``__`` (double underscore) to avoid interference from a macro with
119the same name. For instance, ``__cxx_rvalue_references__`` can be used instead
120of ``cxx_rvalue_references``.
121
Aaron Ballmana0344c52014-11-14 13:44:02 +0000122``__has_cpp_attribute``
Aaron Ballman631bd7b2014-11-14 14:01:55 +0000123-----------------------
Aaron Ballmana0344c52014-11-14 13:44:02 +0000124
Aaron Ballman62015572018-11-20 15:23:07 +0000125This function-like macro is available in C++2a by default, and is provided as an
126extension in earlier language standards. It takes a single argument that is the
127name of a double-square-bracket-style attribute. The argument can either be a
128single identifier or a scoped identifier. If the attribute is supported, a
129nonzero value is returned. If the attribute is a standards-based attribute, this
130macro returns a nonzero value based on the year and month in which the attribute
131was voted into the working draft. See `WG21 SD-6
132<https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_
133for the list of values returned for standards-based attributes. If the attribute
134is not supported by the current compliation target, this macro evaluates to 0.
135It can be used like this:
Aaron Ballmana0344c52014-11-14 13:44:02 +0000136
137.. code-block:: c++
138
Aaron Ballman62015572018-11-20 15:23:07 +0000139 #ifndef __has_cpp_attribute // For backwards compatibility
140 #define __has_cpp_attribute(x) 0
Aaron Ballmana0344c52014-11-14 13:44:02 +0000141 #endif
142
143 ...
144 #if __has_cpp_attribute(clang::fallthrough)
145 #define FALLTHROUGH [[clang::fallthrough]]
146 #else
147 #define FALLTHROUGH
148 #endif
149 ...
150
Aaron Ballman62015572018-11-20 15:23:07 +0000151The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
152the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
153of these namespaces can be specified with a preceding and following ``__``
154(double underscore) to avoid interference from a macro with the same name. For
155instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
Aaron Ballmana0344c52014-11-14 13:44:02 +0000156
Aaron Ballman48f5f4d2017-12-07 21:37:49 +0000157``__has_c_attribute``
158---------------------
159
160This function-like macro takes a single argument that is the name of an
161attribute exposed with the double square-bracket syntax in C mode. The argument
162can either be a single identifier or a scoped identifier. If the attribute is
163supported, a nonzero value is returned. If the attribute is not supported by the
164current compilation target, this macro evaluates to 0. It can be used like this:
165
166.. code-block:: c
167
168 #ifndef __has_c_attribute // Optional of course.
169 #define __has_c_attribute(x) 0 // Compatibility with non-clang compilers.
170 #endif
171
172 ...
173 #if __has_c_attribute(fallthrough)
174 #define FALLTHROUGH [[fallthrough]]
175 #else
176 #define FALLTHROUGH
177 #endif
178 ...
179
Aaron Ballman62015572018-11-20 15:23:07 +0000180The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
181the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
182of these namespaces can be specified with a preceding and following ``__``
183(double underscore) to avoid interference from a macro with the same name. For
184instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
Aaron Ballman48f5f4d2017-12-07 21:37:49 +0000185
Sean Silva709c44d2012-12-12 23:44:55 +0000186``__has_attribute``
187-------------------
188
189This function-like macro takes a single identifier argument that is the name of
Aaron Ballman4bfaeba2014-12-05 17:11:49 +0000190a GNU-style attribute. It evaluates to 1 if the attribute is supported by the
191current compilation target, or 0 if not. It can be used like this:
Sean Silva709c44d2012-12-12 23:44:55 +0000192
193.. code-block:: c++
194
195 #ifndef __has_attribute // Optional of course.
196 #define __has_attribute(x) 0 // Compatibility with non-clang compilers.
197 #endif
198
199 ...
200 #if __has_attribute(always_inline)
201 #define ALWAYS_INLINE __attribute__((always_inline))
202 #else
203 #define ALWAYS_INLINE
204 #endif
205 ...
206
207The attribute name can also be specified with a preceding and following ``__``
208(double underscore) to avoid interference from a macro with the same name. For
209instance, ``__always_inline__`` can be used instead of ``always_inline``.
210
Aaron Ballman3c0f9b42014-12-05 15:05:29 +0000211
212``__has_declspec_attribute``
213----------------------------
214
215This function-like macro takes a single identifier argument that is the name of
216an attribute implemented as a Microsoft-style ``__declspec`` attribute. It
217evaluates to 1 if the attribute is supported by the current compilation target,
218or 0 if not. It can be used like this:
219
220.. code-block:: c++
221
222 #ifndef __has_declspec_attribute // Optional of course.
223 #define __has_declspec_attribute(x) 0 // Compatibility with non-clang compilers.
224 #endif
225
226 ...
227 #if __has_declspec_attribute(dllexport)
228 #define DLLEXPORT __declspec(dllexport)
229 #else
230 #define DLLEXPORT
231 #endif
232 ...
233
234The attribute name can also be specified with a preceding and following ``__``
235(double underscore) to avoid interference from a macro with the same name. For
236instance, ``__dllexport__`` can be used instead of ``dllexport``.
237
Yunzhong Gaoa8c45c92014-04-12 02:25:32 +0000238``__is_identifier``
239-------------------
240
241This function-like macro takes a single identifier argument that might be either
242a reserved word or a regular identifier. It evaluates to 1 if the argument is just
243a regular identifier and not a reserved word, in the sense that it can then be
244used as the name of a user-defined function or variable. Otherwise it evaluates
245to 0. It can be used like this:
246
247.. code-block:: c++
248
249 ...
250 #ifdef __is_identifier // Compatibility with non-clang compilers.
251 #if __is_identifier(__wchar_t)
252 typedef wchar_t __wchar_t;
253 #endif
254 #endif
255
256 __wchar_t WideCharacter;
257 ...
Aaron Ballmana4bb4b92014-01-09 23:11:13 +0000258
Sean Silva709c44d2012-12-12 23:44:55 +0000259Include File Checking Macros
260============================
261
262Not all developments systems have the same include files. The
263:ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
264you to check for the existence of an include file before doing a possibly
Dmitri Gribenko764ea242013-01-17 17:04:54 +0000265failing ``#include`` directive. Include file checking macros must be used
266as expressions in ``#if`` or ``#elif`` preprocessing directives.
Sean Silva709c44d2012-12-12 23:44:55 +0000267
268.. _langext-__has_include:
269
270``__has_include``
271-----------------
272
273This function-like macro takes a single file name string argument that is the
274name of an include file. It evaluates to 1 if the file can be found using the
275include paths, or 0 otherwise:
276
277.. code-block:: c++
278
279 // Note the two possible file name string formats.
280 #if __has_include("myinclude.h") && __has_include(<stdint.h>)
281 # include "myinclude.h"
282 #endif
283
Richard Smithccfc9ff2013-07-11 00:27:05 +0000284To test for this feature, use ``#if defined(__has_include)``:
285
286.. code-block:: c++
287
Sean Silva709c44d2012-12-12 23:44:55 +0000288 // To avoid problem with non-clang compilers not having this macro.
Richard Smithccfc9ff2013-07-11 00:27:05 +0000289 #if defined(__has_include)
290 #if __has_include("myinclude.h")
Sean Silva709c44d2012-12-12 23:44:55 +0000291 # include "myinclude.h"
292 #endif
Richard Smithccfc9ff2013-07-11 00:27:05 +0000293 #endif
Sean Silva709c44d2012-12-12 23:44:55 +0000294
295.. _langext-__has_include_next:
296
297``__has_include_next``
298----------------------
299
300This function-like macro takes a single file name string argument that is the
301name of an include file. It is like ``__has_include`` except that it looks for
302the second instance of the given file found in the include paths. It evaluates
303to 1 if the second instance of the file can be found using the include paths,
304or 0 otherwise:
305
306.. code-block:: c++
307
308 // Note the two possible file name string formats.
309 #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
310 # include_next "myinclude.h"
311 #endif
312
313 // To avoid problem with non-clang compilers not having this macro.
Richard Smithccfc9ff2013-07-11 00:27:05 +0000314 #if defined(__has_include_next)
315 #if __has_include_next("myinclude.h")
Sean Silva709c44d2012-12-12 23:44:55 +0000316 # include_next "myinclude.h"
317 #endif
Richard Smithccfc9ff2013-07-11 00:27:05 +0000318 #endif
Sean Silva709c44d2012-12-12 23:44:55 +0000319
320Note that ``__has_include_next``, like the GNU extension ``#include_next``
321directive, is intended for use in headers only, and will issue a warning if
322used in the top-level compilation file. A warning will also be issued if an
323absolute path is used in the file argument.
324
325``__has_warning``
326-----------------
327
328This function-like macro takes a string literal that represents a command line
329option for a warning and returns true if that is a valid warning option.
330
331.. code-block:: c++
332
333 #if __has_warning("-Wformat")
334 ...
335 #endif
336
Sylvestre Ledru56799832019-07-15 17:47:22 +0000337.. _languageextensions-builtin-macros:
338
Sean Silva709c44d2012-12-12 23:44:55 +0000339Builtin Macros
340==============
341
342``__BASE_FILE__``
343 Defined to a string that contains the name of the main input file passed to
344 Clang.
Sylvestre Ledru0adbe772019-07-09 08:50:17 +0000345
Kristina Brooks56520632019-05-17 06:46:12 +0000346``__FILE_NAME__``
347 Clang-specific extension that functions similar to ``__FILE__`` but only
348 renders the last path component (the filename) instead of an invocation
Sylvestre Ledru0adbe772019-07-09 08:50:17 +0000349 dependent full path to that file.
Sean Silva709c44d2012-12-12 23:44:55 +0000350
351``__COUNTER__``
352 Defined to an integer value that starts at zero and is incremented each time
353 the ``__COUNTER__`` macro is expanded.
354
355``__INCLUDE_LEVEL__``
356 Defined to an integral value that is the include depth of the file currently
357 being translated. For the main file, this value is zero.
358
359``__TIMESTAMP__``
360 Defined to the date and time of the last modification of the current source
361 file.
362
363``__clang__``
364 Defined when compiling with Clang
365
366``__clang_major__``
367 Defined to the major marketing version number of Clang (e.g., the 2 in
368 2.0.1). Note that marketing version numbers should not be used to check for
369 language features, as different vendors use different numbering schemes.
370 Instead, use the :ref:`langext-feature_check`.
371
372``__clang_minor__``
373 Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note
374 that marketing version numbers should not be used to check for language
375 features, as different vendors use different numbering schemes. Instead, use
376 the :ref:`langext-feature_check`.
377
378``__clang_patchlevel__``
379 Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
380
381``__clang_version__``
382 Defined to a string that captures the Clang marketing version, including the
383 Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
384
385.. _langext-vectors:
386
387Vectors and Extended Vectors
388============================
389
390Supports the GCC, OpenCL, AltiVec and NEON vector extensions.
391
Aaron Ballman18796da2019-08-22 18:57:46 +0000392OpenCL vector types are created using the ``ext_vector_type`` attribute. It
393supports the ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example
Sean Silva709c44d2012-12-12 23:44:55 +0000394is:
395
396.. code-block:: c++
397
398 typedef float float4 __attribute__((ext_vector_type(4)));
399 typedef float float2 __attribute__((ext_vector_type(2)));
400
401 float4 foo(float2 a, float2 b) {
402 float4 c;
403 c.xz = a;
404 c.yw = b;
405 return c;
406 }
407
Aaron Ballman18796da2019-08-22 18:57:46 +0000408Query for this feature with ``__has_attribute(ext_vector_type)``.
Sean Silva709c44d2012-12-12 23:44:55 +0000409
Eric Christopher758aad72017-03-21 22:06:18 +0000410Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax
Sean Silva709c44d2012-12-12 23:44:55 +0000411and functions. For example:
412
413.. code-block:: c++
414
415 vector float foo(vector int a) {
416 vector int b;
417 b = vec_add(a, a) + a;
418 return (vector float)b;
419 }
420
421NEON vector types are created using ``neon_vector_type`` and
422``neon_polyvector_type`` attributes. For example:
423
424.. code-block:: c++
425
426 typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
427 typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
428
429 int8x8_t foo(int8x8_t a) {
430 int8x8_t v;
431 v = a;
432 return v;
433 }
434
435Vector Literals
436---------------
437
438Vector literals can be used to create vectors from a set of scalars, or
439vectors. Either parentheses or braces form can be used. In the parentheses
440form the number of literal values specified must be one, i.e. referring to a
441scalar value, or must match the size of the vector type being created. If a
442single scalar literal value is specified, the scalar literal value will be
443replicated to all the components of the vector type. In the brackets form any
444number of literals can be specified. For example:
445
446.. code-block:: c++
447
448 typedef int v4si __attribute__((__vector_size__(16)));
449 typedef float float4 __attribute__((ext_vector_type(4)));
450 typedef float float2 __attribute__((ext_vector_type(2)));
451
452 v4si vsi = (v4si){1, 2, 3, 4};
453 float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
454 vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1).
455 vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0).
456 vector int vi3 = (vector int)(1, 2); // error
457 vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
458 vector int vi5 = (vector int)(1, 2, 3, 4);
459 float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
460
461Vector Operations
462-----------------
463
464The table below shows the support for each operation by vector extension. A
465dash indicates that an operation is not accepted according to a corresponding
466specification.
467
Anton Yartsev94e46f32014-09-03 17:59:21 +0000468============================== ======= ======= ======= =======
Nick Lewycky00a5d212015-08-10 19:54:11 +0000469 Operator OpenCL AltiVec GCC NEON
Anton Yartsev94e46f32014-09-03 17:59:21 +0000470============================== ======= ======= ======= =======
471[] yes yes yes --
472unary operators +, -- yes yes yes --
473++, -- -- yes yes yes --
474+,--,*,/,% yes yes yes --
475bitwise operators &,|,^,~ yes yes yes --
476>>,<< yes yes yes --
477!, &&, || yes -- -- --
478==, !=, >, <, >=, <= yes yes -- --
479= yes yes yes yes
480:? yes -- -- --
481sizeof yes yes yes yes
482C-style cast yes yes yes no
483reinterpret_cast yes no yes no
484static_cast yes no yes no
485const_cast no no no no
486============================== ======= ======= ======= =======
Sean Silva709c44d2012-12-12 23:44:55 +0000487
Anton Yartsev94e46f32014-09-03 17:59:21 +0000488See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.
Sean Silva709c44d2012-12-12 23:44:55 +0000489
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000490Half-Precision Floating Point
491=============================
492
493Clang supports two half-precision (16-bit) floating point types: ``__fp16`` and
Erich Keane1d1d4382019-01-25 17:27:57 +0000494``_Float16``. These types are supported in all language modes.
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000495
Erich Keane1d1d4382019-01-25 17:27:57 +0000496``__fp16`` is supported on every target, as it is purely a storage format; see below.
497``_Float16`` is currently only supported on the following targets, with further
498targets pending ABI standardization:
Richard Smith87869b32019-08-16 22:08:39 +0000499
500* 32-bit ARM
501* 64-bit ARM (AArch64)
502* SPIR
503
Erich Keane1d1d4382019-01-25 17:27:57 +0000504``_Float16`` will be supported on more targets as they define ABIs for it.
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000505
Erich Keane1d1d4382019-01-25 17:27:57 +0000506``__fp16`` is a storage and interchange format only. This means that values of
507``__fp16`` are immediately promoted to (at least) ``float`` when used in arithmetic
508operations, so that e.g. the result of adding two ``__fp16`` values has type ``float``.
509The behavior of ``__fp16`` is specified by the ARM C Language Extensions (`ACLE <http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053d/IHI0053D_acle_2_1.pdf>`_).
510Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``, not the ARM
511alternative format.
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000512
Erich Keane1d1d4382019-01-25 17:27:57 +0000513``_Float16`` is an extended floating-point type. This means that, just like arithmetic on
514``float`` or ``double``, arithmetic on ``_Float16`` operands is formally performed in the
515``_Float16`` type, so that e.g. the result of adding two ``_Float16`` values has type
516``_Float16``. The behavior of ``_Float16`` is specified by ISO/IEC TS 18661-3:2015
517("Floating-point extensions for C"). As with ``__fp16``, Clang uses the ``binary16``
518format from IEEE 754-2008 for ``_Float16``.
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000519
Erich Keane1d1d4382019-01-25 17:27:57 +0000520``_Float16`` arithmetic will be performed using native half-precision support
521when available on the target (e.g. on ARMv8.2a); otherwise it will be performed
522at a higher precision (currently always ``float``) and then truncated down to
523``_Float16``. Note that C and C++ allow intermediate floating-point operands
524of an expression to be computed with greater precision than is expressible in
525their type, so Clang may avoid intermediate truncations in certain cases; this may
526lead to results that are inconsistent with native arithmetic.
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000527
Erich Keane1d1d4382019-01-25 17:27:57 +0000528It is recommended that portable code use ``_Float16`` instead of ``__fp16``,
529as it has been defined by the C standards committee and has behavior that is
530more familiar to most programmers.
531
532Because ``__fp16`` operands are always immediately promoted to ``float``, the
533common real type of ``__fp16`` and ``_Float16`` for the purposes of the usual
534arithmetic conversions is ``float``.
535
Richard Smith87869b32019-08-16 22:08:39 +0000536A literal can be given ``_Float16`` type using the suffix ``f16``. For example,
537``3.14f16``.
Erich Keane1d1d4382019-01-25 17:27:57 +0000538
539Because default argument promotion only applies to the standard floating-point
540types, ``_Float16`` values are not promoted to ``double`` when passed as variadic
541or untyped arguments. As a consequence, some caution must be taken when using
542certain library facilities with ``_Float16``; for example, there is no ``printf`` format
543specifier for ``_Float16``, and (unlike ``float``) it will not be implicitly promoted to
544``double`` when passed to ``printf``, so the programmer must explicitly cast it to
545``double`` before using it with an ``%f`` or similar specifier.
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000546
Sean Silva709c44d2012-12-12 23:44:55 +0000547Messages on ``deprecated`` and ``unavailable`` Attributes
548=========================================================
549
550An optional string message can be added to the ``deprecated`` and
551``unavailable`` attributes. For example:
552
553.. code-block:: c++
554
555 void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
556
557If the deprecated or unavailable declaration is used, the message will be
558incorporated into the appropriate diagnostic:
559
George Burgess IV61e43272016-06-21 00:16:23 +0000560.. code-block:: none
Sean Silva709c44d2012-12-12 23:44:55 +0000561
562 harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
563 [-Wdeprecated-declarations]
564 explode();
565 ^
566
567Query for this feature with
568``__has_extension(attribute_deprecated_with_message)`` and
569``__has_extension(attribute_unavailable_with_message)``.
570
571Attributes on Enumerators
572=========================
573
574Clang allows attributes to be written on individual enumerators. This allows
575enumerators to be deprecated, made unavailable, etc. The attribute must appear
576after the enumerator name and before any initializer, like so:
577
578.. code-block:: c++
579
580 enum OperationMode {
581 OM_Invalid,
582 OM_Normal,
583 OM_Terrified __attribute__((deprecated)),
584 OM_AbortOnError __attribute__((deprecated)) = 4
585 };
586
587Attributes on the ``enum`` declaration do not apply to individual enumerators.
588
589Query for this feature with ``__has_extension(enumerator_attributes)``.
590
591'User-Specified' System Frameworks
592==================================
593
594Clang provides a mechanism by which frameworks can be built in such a way that
595they will always be treated as being "system frameworks", even if they are not
596present in a system framework directory. This can be useful to system
597framework developers who want to be able to test building other applications
598with development builds of their framework, including the manner in which the
599compiler changes warning behavior for system headers.
600
601Framework developers can opt-in to this mechanism by creating a
602"``.system_framework``" file at the top-level of their framework. That is, the
603framework should have contents like:
604
605.. code-block:: none
606
607 .../TestFramework.framework
608 .../TestFramework.framework/.system_framework
609 .../TestFramework.framework/Headers
610 .../TestFramework.framework/Headers/TestFramework.h
611 ...
612
613Clang will treat the presence of this file as an indicator that the framework
614should be treated as a system framework, regardless of how it was found in the
615framework search path. For consistency, we recommend that such files never be
616included in installed versions of the framework.
617
Sean Silva709c44d2012-12-12 23:44:55 +0000618Checks for Standard Language Features
619=====================================
620
621The ``__has_feature`` macro can be used to query if certain standard language
622features are enabled. The ``__has_extension`` macro can be used to query if
623language features are available as an extension when compiling for a standard
624which does not provide them. The features which can be tested are listed here.
625
Richard Smith38af8562014-11-12 21:16:38 +0000626Since Clang 3.4, the C++ SD-6 feature test macros are also supported.
627These are macros with names of the form ``__cpp_<feature_name>``, and are
628intended to be a portable way to query the supported features of the compiler.
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +0000629See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for
Richard Smith38af8562014-11-12 21:16:38 +0000630information on the version of SD-6 supported by each Clang release, and the
631macros provided by that revision of the recommendations.
632
Sean Silva709c44d2012-12-12 23:44:55 +0000633C++98
634-----
635
636The features listed below are part of the C++98 standard. These features are
637enabled by default when compiling C++ code.
638
639C++ exceptions
640^^^^^^^^^^^^^^
641
642Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
643enabled. For example, compiling code with ``-fno-exceptions`` disables C++
644exceptions.
645
646C++ RTTI
647^^^^^^^^
648
649Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For
650example, compiling code with ``-fno-rtti`` disables the use of RTTI.
651
652C++11
653-----
654
655The features listed below are part of the C++11 standard. As a result, all
656these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
657when compiling C++ code.
658
659C++11 SFINAE includes access control
660^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
661
662Use ``__has_feature(cxx_access_control_sfinae)`` or
663``__has_extension(cxx_access_control_sfinae)`` to determine whether
664access-control errors (e.g., calling a private constructor) are considered to
665be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
666<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
667
668C++11 alias templates
669^^^^^^^^^^^^^^^^^^^^^
670
671Use ``__has_feature(cxx_alias_templates)`` or
672``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
673alias declarations and alias templates is enabled.
674
675C++11 alignment specifiers
676^^^^^^^^^^^^^^^^^^^^^^^^^^
677
678Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
679determine if support for alignment specifiers using ``alignas`` is enabled.
680
Nico Weber736a9932014-12-03 01:25:49 +0000681Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to
682determine if support for the ``alignof`` keyword is enabled.
683
Sean Silva709c44d2012-12-12 23:44:55 +0000684C++11 attributes
685^^^^^^^^^^^^^^^^
686
687Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
688determine if support for attribute parsing with C++11's square bracket notation
689is enabled.
690
691C++11 generalized constant expressions
692^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
693
694Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
695constant expressions (e.g., ``constexpr``) is enabled.
696
697C++11 ``decltype()``
698^^^^^^^^^^^^^^^^^^^^
699
700Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
701determine if support for the ``decltype()`` specifier is enabled. C++11's
702``decltype`` does not require type-completeness of a function call expression.
703Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
704``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
705support for this feature is enabled.
706
707C++11 default template arguments in function templates
708^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
709
710Use ``__has_feature(cxx_default_function_template_args)`` or
711``__has_extension(cxx_default_function_template_args)`` to determine if support
712for default template arguments in function templates is enabled.
713
714C++11 ``default``\ ed functions
715^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
716
717Use ``__has_feature(cxx_defaulted_functions)`` or
718``__has_extension(cxx_defaulted_functions)`` to determine if support for
719defaulted function definitions (with ``= default``) is enabled.
720
721C++11 delegating constructors
722^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
723
724Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
725delegating constructors is enabled.
726
727C++11 ``deleted`` functions
728^^^^^^^^^^^^^^^^^^^^^^^^^^^
729
730Use ``__has_feature(cxx_deleted_functions)`` or
731``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
732function definitions (with ``= delete``) is enabled.
733
734C++11 explicit conversion functions
735^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
736
737Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
738``explicit`` conversion functions is enabled.
739
740C++11 generalized initializers
741^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
742
743Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
744generalized initializers (using braced lists and ``std::initializer_list``) is
745enabled.
746
747C++11 implicit move constructors/assignment operators
748^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
749
750Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
751generate move constructors and move assignment operators where needed.
752
753C++11 inheriting constructors
754^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
755
756Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
Richard Smith25b555a2013-04-19 17:00:31 +0000757inheriting constructors is enabled.
Sean Silva709c44d2012-12-12 23:44:55 +0000758
759C++11 inline namespaces
760^^^^^^^^^^^^^^^^^^^^^^^
761
762Use ``__has_feature(cxx_inline_namespaces)`` or
763``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
764namespaces is enabled.
765
766C++11 lambdas
767^^^^^^^^^^^^^
768
769Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
770determine if support for lambdas is enabled.
771
772C++11 local and unnamed types as template arguments
773^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
774
775Use ``__has_feature(cxx_local_type_template_args)`` or
776``__has_extension(cxx_local_type_template_args)`` to determine if support for
777local and unnamed types as template arguments is enabled.
778
779C++11 noexcept
780^^^^^^^^^^^^^^
781
782Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
783determine if support for noexcept exception specifications is enabled.
784
785C++11 in-class non-static data member initialization
786^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
787
788Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
789initialization of non-static data members is enabled.
790
791C++11 ``nullptr``
792^^^^^^^^^^^^^^^^^
793
794Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
795determine if support for ``nullptr`` is enabled.
796
797C++11 ``override control``
798^^^^^^^^^^^^^^^^^^^^^^^^^^
799
800Use ``__has_feature(cxx_override_control)`` or
801``__has_extension(cxx_override_control)`` to determine if support for the
802override control keywords is enabled.
803
804C++11 reference-qualified functions
805^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
806
807Use ``__has_feature(cxx_reference_qualified_functions)`` or
808``__has_extension(cxx_reference_qualified_functions)`` to determine if support
809for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
810applied to ``*this``) is enabled.
811
812C++11 range-based ``for`` loop
813^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
814
815Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
816determine if support for the range-based for loop is enabled.
817
818C++11 raw string literals
819^^^^^^^^^^^^^^^^^^^^^^^^^
820
821Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
822string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
823
824C++11 rvalue references
825^^^^^^^^^^^^^^^^^^^^^^^
826
827Use ``__has_feature(cxx_rvalue_references)`` or
828``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
829references is enabled.
830
831C++11 ``static_assert()``
832^^^^^^^^^^^^^^^^^^^^^^^^^
833
834Use ``__has_feature(cxx_static_assert)`` or
835``__has_extension(cxx_static_assert)`` to determine if support for compile-time
836assertions using ``static_assert`` is enabled.
837
Richard Smith25b555a2013-04-19 17:00:31 +0000838C++11 ``thread_local``
839^^^^^^^^^^^^^^^^^^^^^^
840
841Use ``__has_feature(cxx_thread_local)`` to determine if support for
842``thread_local`` variables is enabled.
843
Sean Silva709c44d2012-12-12 23:44:55 +0000844C++11 type inference
845^^^^^^^^^^^^^^^^^^^^
846
847Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
848determine C++11 type inference is supported using the ``auto`` specifier. If
849this is disabled, ``auto`` will instead be a storage class specifier, as in C
850or C++98.
851
852C++11 strongly typed enumerations
853^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
854
855Use ``__has_feature(cxx_strong_enums)`` or
856``__has_extension(cxx_strong_enums)`` to determine if support for strongly
857typed, scoped enumerations is enabled.
858
859C++11 trailing return type
860^^^^^^^^^^^^^^^^^^^^^^^^^^
861
862Use ``__has_feature(cxx_trailing_return)`` or
863``__has_extension(cxx_trailing_return)`` to determine if support for the
864alternate function declaration syntax with trailing return type is enabled.
865
866C++11 Unicode string literals
867^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
868
869Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
870string literals is enabled.
871
872C++11 unrestricted unions
873^^^^^^^^^^^^^^^^^^^^^^^^^
874
875Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
876unrestricted unions is enabled.
877
878C++11 user-defined literals
879^^^^^^^^^^^^^^^^^^^^^^^^^^^
880
881Use ``__has_feature(cxx_user_literals)`` to determine if support for
882user-defined literals is enabled.
883
884C++11 variadic templates
885^^^^^^^^^^^^^^^^^^^^^^^^
886
887Use ``__has_feature(cxx_variadic_templates)`` or
888``__has_extension(cxx_variadic_templates)`` to determine if support for
889variadic templates is enabled.
890
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000891C++14
Richard Smith0a715422013-05-07 19:32:56 +0000892-----
893
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000894The features listed below are part of the C++14 standard. As a result, all
895these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option
896when compiling C++ code.
Richard Smith0a715422013-05-07 19:32:56 +0000897
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000898C++14 binary literals
Richard Smith0a715422013-05-07 19:32:56 +0000899^^^^^^^^^^^^^^^^^^^^^
900
901Use ``__has_feature(cxx_binary_literals)`` or
902``__has_extension(cxx_binary_literals)`` to determine whether
903binary literals (for instance, ``0b10010``) are recognized. Clang supports this
904feature as an extension in all language modes.
905
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000906C++14 contextual conversions
Richard Smith0a715422013-05-07 19:32:56 +0000907^^^^^^^^^^^^^^^^^^^^^^^^^^^^
908
909Use ``__has_feature(cxx_contextual_conversions)`` or
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000910``__has_extension(cxx_contextual_conversions)`` to determine if the C++14 rules
Richard Smith0a715422013-05-07 19:32:56 +0000911are used when performing an implicit conversion for an array bound in a
912*new-expression*, the operand of a *delete-expression*, an integral constant
Richard Smithc0f7b812013-07-24 17:41:31 +0000913expression, or a condition in a ``switch`` statement.
Richard Smith0a715422013-05-07 19:32:56 +0000914
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000915C++14 decltype(auto)
Richard Smith0a715422013-05-07 19:32:56 +0000916^^^^^^^^^^^^^^^^^^^^
917
918Use ``__has_feature(cxx_decltype_auto)`` or
919``__has_extension(cxx_decltype_auto)`` to determine if support
920for the ``decltype(auto)`` placeholder type is enabled.
921
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000922C++14 default initializers for aggregates
Richard Smith0a715422013-05-07 19:32:56 +0000923^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
924
925Use ``__has_feature(cxx_aggregate_nsdmi)`` or
926``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
927for default initializers in aggregate members is enabled.
928
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000929C++14 digit separators
Richard Smith38af8562014-11-12 21:16:38 +0000930^^^^^^^^^^^^^^^^^^^^^^
931
932Use ``__cpp_digit_separators`` to determine if support for digit separators
933using single quotes (for instance, ``10'000``) is enabled. At this time, there
934is no corresponding ``__has_feature`` name
935
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000936C++14 generalized lambda capture
Richard Smith0a715422013-05-07 19:32:56 +0000937^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
938
Richard Smith6d540142014-05-09 21:08:59 +0000939Use ``__has_feature(cxx_init_captures)`` or
940``__has_extension(cxx_init_captures)`` to determine if support for
Richard Smith4fb09722013-07-24 17:51:13 +0000941lambda captures with explicit initializers is enabled
Richard Smith0a715422013-05-07 19:32:56 +0000942(for instance, ``[n(0)] { return ++n; }``).
Richard Smith0a715422013-05-07 19:32:56 +0000943
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000944C++14 generic lambdas
Richard Smith0a715422013-05-07 19:32:56 +0000945^^^^^^^^^^^^^^^^^^^^^
946
Richard Smith6d540142014-05-09 21:08:59 +0000947Use ``__has_feature(cxx_generic_lambdas)`` or
948``__has_extension(cxx_generic_lambdas)`` to determine if support for generic
Richard Smith0a715422013-05-07 19:32:56 +0000949(polymorphic) lambdas is enabled
950(for instance, ``[] (auto x) { return x + 1; }``).
Richard Smith0a715422013-05-07 19:32:56 +0000951
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000952C++14 relaxed constexpr
Richard Smith0a715422013-05-07 19:32:56 +0000953^^^^^^^^^^^^^^^^^^^^^^^
954
955Use ``__has_feature(cxx_relaxed_constexpr)`` or
956``__has_extension(cxx_relaxed_constexpr)`` to determine if variable
957declarations, local variable modification, and control flow constructs
958are permitted in ``constexpr`` functions.
Richard Smith0a715422013-05-07 19:32:56 +0000959
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000960C++14 return type deduction
Richard Smith0a715422013-05-07 19:32:56 +0000961^^^^^^^^^^^^^^^^^^^^^^^^^^^
962
963Use ``__has_feature(cxx_return_type_deduction)`` or
964``__has_extension(cxx_return_type_deduction)`` to determine if support
965for return type deduction for functions (using ``auto`` as a return type)
966is enabled.
Richard Smith0a715422013-05-07 19:32:56 +0000967
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000968C++14 runtime-sized arrays
Richard Smith0a715422013-05-07 19:32:56 +0000969^^^^^^^^^^^^^^^^^^^^^^^^^^
970
971Use ``__has_feature(cxx_runtime_array)`` or
972``__has_extension(cxx_runtime_array)`` to determine if support
973for arrays of runtime bound (a restricted form of variable-length arrays)
974is enabled.
975Clang's implementation of this feature is incomplete.
976
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000977C++14 variable templates
Richard Smith0a715422013-05-07 19:32:56 +0000978^^^^^^^^^^^^^^^^^^^^^^^^
979
980Use ``__has_feature(cxx_variable_templates)`` or
981``__has_extension(cxx_variable_templates)`` to determine if support for
982templated variable declarations is enabled.
Richard Smith0a715422013-05-07 19:32:56 +0000983
Sean Silva709c44d2012-12-12 23:44:55 +0000984C11
985---
986
987The features listed below are part of the C11 standard. As a result, all these
988features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
989compiling C code. Additionally, because these features are all
990backward-compatible, they are available as extensions in all language modes.
991
992C11 alignment specifiers
993^^^^^^^^^^^^^^^^^^^^^^^^
994
995Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
996if support for alignment specifiers using ``_Alignas`` is enabled.
997
Nico Weber736a9932014-12-03 01:25:49 +0000998Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine
999if support for the ``_Alignof`` keyword is enabled.
1000
Sean Silva709c44d2012-12-12 23:44:55 +00001001C11 atomic operations
1002^^^^^^^^^^^^^^^^^^^^^
1003
1004Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
1005if support for atomic types using ``_Atomic`` is enabled. Clang also provides
1006:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
Hal Finkel6970ac82014-10-03 04:29:40 +00001007the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use
1008``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header
1009is available.
1010
1011Clang will use the system's ``<stdatomic.h>`` header when one is available, and
1012will otherwise use its own. When using its own, implementations of the atomic
1013operations are provided as macros. In the cases where C11 also requires a real
1014function, this header provides only the declaration of that function (along
1015with a shadowing macro implementation), and you must link to a library which
1016provides a definition of the function if you use it instead of the macro.
Sean Silva709c44d2012-12-12 23:44:55 +00001017
1018C11 generic selections
1019^^^^^^^^^^^^^^^^^^^^^^
1020
1021Use ``__has_feature(c_generic_selections)`` or
1022``__has_extension(c_generic_selections)`` to determine if support for generic
1023selections is enabled.
1024
1025As an extension, the C11 generic selection expression is available in all
1026languages supported by Clang. The syntax is the same as that given in the C11
1027standard.
1028
1029In C, type compatibility is decided according to the rules given in the
1030appropriate standard, but in C++, which lacks the type compatibility rules used
1031in C, types are considered compatible only if they are equivalent.
1032
1033C11 ``_Static_assert()``
1034^^^^^^^^^^^^^^^^^^^^^^^^
1035
1036Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
1037to determine if support for compile-time assertions using ``_Static_assert`` is
1038enabled.
1039
Richard Smith25b555a2013-04-19 17:00:31 +00001040C11 ``_Thread_local``
1041^^^^^^^^^^^^^^^^^^^^^
1042
Ed Schouten401aeba2013-09-14 16:17:20 +00001043Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)``
1044to determine if support for ``_Thread_local`` variables is enabled.
Richard Smith25b555a2013-04-19 17:00:31 +00001045
Ben Langmuir921f2e62015-03-10 14:39:26 +00001046Modules
1047-------
1048
1049Use ``__has_feature(modules)`` to determine if Modules have been enabled.
1050For example, compiling code with ``-fmodules`` enables the use of Modules.
1051
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001052More information could be found `here <https://clang.llvm.org/docs/Modules.html>`_.
Ben Langmuir921f2e62015-03-10 14:39:26 +00001053
Richard Smithdac3ea42019-08-14 02:30:11 +00001054Type Trait Primitives
1055=====================
Alp Toker64197b92014-01-18 21:49:02 +00001056
1057Type trait primitives are special builtin constant expressions that can be used
1058by the standard C++ library to facilitate or simplify the implementation of
1059user-facing type traits in the <type_traits> header.
1060
1061They are not intended to be used directly by user code because they are
1062implementation-defined and subject to change -- as such they're tied closely to
1063the supported set of system headers, currently:
1064
1065* LLVM's own libc++
1066* GNU libstdc++
1067* The Microsoft standard C++ library
Sean Silva709c44d2012-12-12 23:44:55 +00001068
1069Clang supports the `GNU C++ type traits
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00001070<https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
Richard Smithdac3ea42019-08-14 02:30:11 +00001071`Microsoft Visual C++ type traits
1072<https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_,
1073as well as nearly all of the
1074`Embarcadero C++ type traits
1075<http://docwiki.embarcadero.com/RADStudio/Rio/en/Type_Trait_Functions_(C%2B%2B11)_Index>`_.
Alp Toker64197b92014-01-18 21:49:02 +00001076
Richard Smithdac3ea42019-08-14 02:30:11 +00001077The following type trait primitives are supported by Clang. Those traits marked
1078(C++) provide implementations for type traits specified by the C++ standard;
1079``__X(...)`` has the same semantics and constraints as the corresponding
1080``std::X_t<...>`` or ``std::X_v<...>`` type trait.
Alp Toker64197b92014-01-18 21:49:02 +00001081
Richard Smithdac3ea42019-08-14 02:30:11 +00001082* ``__array_rank(type)`` (Embarcadero):
1083 Returns the number of levels of array in the type ``type``:
1084 ``0`` if ``type`` is not an array type, and
1085 ``__array_rank(element) + 1`` if ``type`` is an array of ``element``.
1086* ``__array_extent(type, dim)`` (Embarcadero):
1087 The ``dim``'th array bound in the type ``type``, or ``0`` if
1088 ``dim >= __array_rank(type)``.
1089* ``__has_nothrow_assign`` (GNU, Microsoft, Embarcadero):
1090 Deprecated, use ``__is_nothrow_assignable`` instead.
1091* ``__has_nothrow_move_assign`` (GNU, Microsoft):
1092 Deprecated, use ``__is_nothrow_assignable`` instead.
1093* ``__has_nothrow_copy`` (GNU, Microsoft):
1094 Deprecated, use ``__is_nothrow_constructible`` instead.
1095* ``__has_nothrow_constructor`` (GNU, Microsoft):
1096 Deprecated, use ``__is_nothrow_constructible`` instead.
1097* ``__has_trivial_assign`` (GNU, Microsoft, Embarcadero):
1098 Deprecated, use ``__is_trivially_assignable`` instead.
1099* ``__has_trivial_move_assign`` (GNU, Microsoft):
1100 Deprecated, use ``__is_trivially_assignable`` instead.
1101* ``__has_trivial_copy`` (GNU, Microsoft):
1102 Deprecated, use ``__is_trivially_constructible`` instead.
1103* ``__has_trivial_constructor`` (GNU, Microsoft):
1104 Deprecated, use ``__is_trivially_constructible`` instead.
1105* ``__has_trivial_move_constructor`` (GNU, Microsoft):
1106 Deprecated, use ``__is_trivially_constructible`` instead.
1107* ``__has_trivial_destructor`` (GNU, Microsoft, Embarcadero):
1108 Deprecated, use ``__is_trivially_destructible`` instead.
1109* ``__has_unique_object_representations`` (C++, GNU)
1110* ``__has_virtual_destructor`` (C++, GNU, Microsoft, Embarcadero)
1111* ``__is_abstract`` (C++, GNU, Microsoft, Embarcadero)
1112* ``__is_aggregate`` (C++, GNU, Microsoft)
1113* ``__is_arithmetic`` (C++, Embarcadero)
1114* ``__is_array`` (C++, Embarcadero)
1115* ``__is_assignable`` (C++, MSVC 2015)
1116* ``__is_base_of`` (C++, GNU, Microsoft, Embarcadero)
1117* ``__is_class`` (C++, GNU, Microsoft, Embarcadero)
1118* ``__is_complete_type(type)`` (Embarcadero):
1119 Return ``true`` if ``type`` is a complete type.
1120 Warning: this trait is dangerous because it can return different values at
1121 different points in the same program.
1122* ``__is_compound`` (C++, Embarcadero)
1123* ``__is_const`` (C++, Embarcadero)
1124* ``__is_constructible`` (C++, MSVC 2013)
1125* ``__is_convertible`` (C++, Embarcadero)
1126* ``__is_convertible_to`` (Microsoft):
1127 Synonym for ``__is_convertible``.
1128* ``__is_destructible`` (C++, MSVC 2013):
1129 Only available in ``-fms-extensions`` mode.
1130* ``__is_empty`` (C++, GNU, Microsoft, Embarcadero)
1131* ``__is_enum`` (C++, GNU, Microsoft, Embarcadero)
1132* ``__is_final`` (C++, GNU, Microsoft)
1133* ``__is_floating_point`` (C++, Embarcadero)
1134* ``__is_function`` (C++, Embarcadero)
1135* ``__is_fundamental`` (C++, Embarcadero)
1136* ``__is_integral`` (C++, Embarcadero)
1137* ``__is_interface_class`` (Microsoft):
1138 Returns ``false``, even for types defined with ``__interface``.
1139* ``__is_literal`` (Clang):
1140 Synonym for ``__is_literal_type``.
1141* ``__is_literal_type`` (C++, GNU, Microsoft):
1142 Note, the corresponding standard trait was deprecated in C++17
1143 and removed in C++20.
1144* ``__is_lvalue_reference`` (C++, Embarcadero)
1145* ``__is_member_object_pointer`` (C++, Embarcadero)
1146* ``__is_member_function_pointer`` (C++, Embarcadero)
1147* ``__is_member_pointer`` (C++, Embarcadero)
1148* ``__is_nothrow_assignable`` (C++, MSVC 2013)
1149* ``__is_nothrow_constructible`` (C++, MSVC 2013)
1150* ``__is_nothrow_destructible`` (C++, MSVC 2013)
1151 Only available in ``-fms-extensions`` mode.
1152* ``__is_object`` (C++, Embarcadero)
1153* ``__is_pod`` (C++, GNU, Microsoft, Embarcadero):
1154 Note, the corresponding standard trait was deprecated in C++20.
1155* ``__is_pointer`` (C++, Embarcadero)
1156* ``__is_polymorphic`` (C++, GNU, Microsoft, Embarcadero)
1157* ``__is_reference`` (C++, Embarcadero)
1158* ``__is_rvalue_reference`` (C++, Embarcadero)
1159* ``__is_same`` (C++, Embarcadero)
1160* ``__is_scalar`` (C++, Embarcadero)
1161* ``__is_sealed`` (Microsoft):
1162 Synonym for ``__is_final``.
1163* ``__is_signed`` (C++, Embarcadero):
1164 Note that this currently returns true for enumeration types if the underlying
1165 type is signed, and returns false for floating-point types, in violation of
1166 the requirements for ``std::is_signed``. This behavior is likely to change in
1167 a future version of Clang.
1168* ``__is_standard_layout`` (C++, GNU, Microsoft, Embarcadero)
1169* ``__is_trivial`` (C++, GNU, Microsoft, Embarcadero)
1170* ``__is_trivially_assignable`` (C++, GNU, Microsoft)
1171* ``__is_trivially_constructible`` (C++, GNU, Microsoft)
1172* ``__is_trivially_copyable`` (C++, GNU, Microsoft)
1173* ``__is_trivially_destructible`` (C++, MSVC 2013)
1174* ``__is_union`` (C++, GNU, Microsoft, Embarcadero)
1175* ``__is_unsigned`` (C++, Embarcadero)
1176 Note that this currently returns true for enumeration types if the underlying
1177 type is unsigned, in violation of the requirements for ``std::is_unsigned``.
1178 This behavior is likely to change in a future version of Clang.
1179* ``__is_void`` (C++, Embarcadero)
1180* ``__is_volatile`` (C++, Embarcadero)
1181* ``__reference_binds_to_temporary(T, U)`` (Clang): Determines whether a
1182 reference of type ``T`` bound to an expression of type ``U`` would bind to a
1183 materialized temporary object. If ``T`` is not a reference type the result
1184 is false. Note this trait will also return false when the initialization of
1185 ``T`` from ``U`` is ill-formed.
1186* ``__underlying_type`` (C++, GNU, Microsoft)
1187
1188In addition, the following expression traits are supported:
1189
1190* ``__is_lvalue_expr(e)`` (Embarcadero):
1191 Returns true if ``e`` is an lvalue expression.
1192 Deprecated, use ``__is_lvalue_reference(decltype((e)))`` instead.
1193* ``__is_rvalue_expr(e)`` (Embarcadero):
1194 Returns true if ``e`` is a prvalue expression.
1195 Deprecated, use ``!__is_reference(decltype((e)))`` instead.
1196
1197There are multiple ways to detect support for a type trait ``__X`` in the
1198compiler, depending on the oldest version of Clang you wish to support.
1199
1200* From Clang 10 onwards, ``__has_builtin(__X)`` can be used.
1201* From Clang 6 onwards, ``!__is_identifier(__X)`` can be used.
1202* From Clang 3 onwards, ``__has_feature(X)`` can be used, but only supports
1203 the following traits:
1204
1205 * ``__has_nothrow_assign``
1206 * ``__has_nothrow_copy``
1207 * ``__has_nothrow_constructor``
1208 * ``__has_trivial_assign``
1209 * ``__has_trivial_copy``
1210 * ``__has_trivial_constructor``
1211 * ``__has_trivial_destructor``
1212 * ``__has_virtual_destructor``
1213 * ``__is_abstract``
1214 * ``__is_base_of``
1215 * ``__is_class``
1216 * ``__is_constructible``
1217 * ``__is_convertible_to``
1218 * ``__is_empty``
1219 * ``__is_enum``
1220 * ``__is_final``
1221 * ``__is_literal``
1222 * ``__is_standard_layout``
1223 * ``__is_pod``
1224 * ``__is_polymorphic``
1225 * ``__is_sealed``
1226 * ``__is_trivial``
1227 * ``__is_trivially_assignable``
1228 * ``__is_trivially_constructible``
1229 * ``__is_trivially_copyable``
1230 * ``__is_union``
1231 * ``__underlying_type``
1232
1233A simplistic usage example as might be seen in standard C++ headers follows:
Sean Silva709c44d2012-12-12 23:44:55 +00001234
1235.. code-block:: c++
1236
Richard Smithdac3ea42019-08-14 02:30:11 +00001237 #if __has_builtin(__is_convertible_to)
Sean Silva709c44d2012-12-12 23:44:55 +00001238 template<typename From, typename To>
1239 struct is_convertible_to {
1240 static const bool value = __is_convertible_to(From, To);
1241 };
1242 #else
Alp Toker64197b92014-01-18 21:49:02 +00001243 // Emulate type trait for compatibility with other compilers.
Sean Silva709c44d2012-12-12 23:44:55 +00001244 #endif
1245
Sean Silva709c44d2012-12-12 23:44:55 +00001246Blocks
1247======
1248
1249The syntax and high level language feature description is in
Michael Gottesman6fd58462013-01-07 22:24:45 +00001250:doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
1251the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
Sean Silva709c44d2012-12-12 23:44:55 +00001252
1253Query for this feature with ``__has_extension(blocks)``.
1254
1255Objective-C Features
1256====================
1257
1258Related result types
1259--------------------
1260
1261According to Cocoa conventions, Objective-C methods with certain names
1262("``init``", "``alloc``", etc.) always return objects that are an instance of
1263the receiving class's type. Such methods are said to have a "related result
1264type", meaning that a message send to one of these methods will have the same
1265static type as an instance of the receiver class. For example, given the
1266following classes:
1267
1268.. code-block:: objc
1269
1270 @interface NSObject
1271 + (id)alloc;
1272 - (id)init;
1273 @end
1274
1275 @interface NSArray : NSObject
1276 @end
1277
1278and this common initialization pattern
1279
1280.. code-block:: objc
1281
1282 NSArray *array = [[NSArray alloc] init];
1283
1284the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
1285``alloc`` implicitly has a related result type. Similarly, the type of the
1286expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
1287related result type and its receiver is known to have the type ``NSArray *``.
1288If neither ``alloc`` nor ``init`` had a related result type, the expressions
1289would have had type ``id``, as declared in the method signature.
1290
1291A method with a related result type can be declared by using the type
1292``instancetype`` as its result type. ``instancetype`` is a contextual keyword
1293that is only permitted in the result type of an Objective-C method, e.g.
1294
1295.. code-block:: objc
1296
1297 @interface A
1298 + (instancetype)constructAnA;
1299 @end
1300
1301The related result type can also be inferred for some methods. To determine
1302whether a method has an inferred related result type, the first word in the
1303camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
1304and the method will have a related result type if its return type is compatible
1305with the type of its class and if:
1306
1307* the first word is "``alloc``" or "``new``", and the method is a class method,
1308 or
1309
1310* the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
1311 and the method is an instance method.
1312
1313If a method with a related result type is overridden by a subclass method, the
1314subclass method must also return a type that is compatible with the subclass
1315type. For example:
1316
1317.. code-block:: objc
1318
1319 @interface NSString : NSObject
1320 - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
1321 @end
1322
1323Related result types only affect the type of a message send or property access
1324via the given method. In all other respects, a method with a related result
1325type is treated the same way as method that returns ``id``.
1326
1327Use ``__has_feature(objc_instancetype)`` to determine whether the
1328``instancetype`` contextual keyword is available.
1329
1330Automatic reference counting
1331----------------------------
1332
Sean Silva173d2522013-01-02 13:07:47 +00001333Clang provides support for :doc:`automated reference counting
1334<AutomaticReferenceCounting>` in Objective-C, which eliminates the need
Akira Hatanaka7275da02018-02-28 07:15:55 +00001335for manual ``retain``/``release``/``autorelease`` message sends. There are three
Sean Silva709c44d2012-12-12 23:44:55 +00001336feature macros associated with automatic reference counting:
1337``__has_feature(objc_arc)`` indicates the availability of automated reference
1338counting in general, while ``__has_feature(objc_arc_weak)`` indicates that
1339automated reference counting also includes support for ``__weak`` pointers to
Akira Hatanaka7275da02018-02-28 07:15:55 +00001340Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs
1341are allowed to have fields that are pointers to Objective-C objects managed by
1342automatic reference counting.
Sean Silva709c44d2012-12-12 23:44:55 +00001343
John McCallea9c5802018-07-20 05:40:12 +00001344.. _objc-weak:
1345
1346Weak references
1347---------------
1348
1349Clang supports ARC-style weak and unsafe references in Objective-C even
1350outside of ARC mode. Weak references must be explicitly enabled with
1351the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))``
1352to test whether they are enabled. Unsafe references are enabled
1353unconditionally. ARC-style weak and unsafe references cannot be used
1354when Objective-C garbage collection is enabled.
1355
1356Except as noted below, the language rules for the ``__weak`` and
1357``__unsafe_unretained`` qualifiers (and the ``weak`` and
1358``unsafe_unretained`` property attributes) are just as laid out
1359in the :doc:`ARC specification <AutomaticReferenceCounting>`.
1360In particular, note that some classes do not support forming weak
1361references to their instances, and note that special care must be
1362taken when storing weak references in memory where initialization
1363and deinitialization are outside the responsibility of the compiler
1364(such as in ``malloc``-ed memory).
1365
1366Loading from a ``__weak`` variable always implicitly retains the
1367loaded value. In non-ARC modes, this retain is normally balanced
1368by an implicit autorelease. This autorelease can be suppressed
1369by performing the load in the receiver position of a ``-retain``
1370message send (e.g. ``[weakReference retain]``); note that this performs
1371only a single retain (the retain done when primitively loading from
1372the weak reference).
1373
1374For the most part, ``__unsafe_unretained`` in non-ARC modes is just the
1375default behavior of variables and therefore is not needed. However,
1376it does have an effect on the semantics of block captures: normally,
1377copying a block which captures an Objective-C object or block pointer
1378causes the captured pointer to be retained or copied, respectively,
1379but that behavior is suppressed when the captured variable is qualified
1380with ``__unsafe_unretained``.
1381
1382Note that the ``__weak`` qualifier formerly meant the GC qualifier in
1383all non-ARC modes and was silently ignored outside of GC modes. It now
1384means the ARC-style qualifier in all non-GC modes and is no longer
1385allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``.
1386It is expected that ``-fobjc-weak`` will eventually be enabled by default
1387in all non-GC Objective-C modes.
1388
Sean Silva173d2522013-01-02 13:07:47 +00001389.. _objc-fixed-enum:
1390
Sean Silva709c44d2012-12-12 23:44:55 +00001391Enumerations with a fixed underlying type
1392-----------------------------------------
1393
1394Clang provides support for C++11 enumerations with a fixed underlying type
1395within Objective-C. For example, one can write an enumeration type as:
1396
1397.. code-block:: c++
1398
1399 typedef enum : unsigned char { Red, Green, Blue } Color;
1400
1401This specifies that the underlying type, which is used to store the enumeration
1402value, is ``unsigned char``.
1403
1404Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
1405underlying types is available in Objective-C.
1406
1407Interoperability with C++11 lambdas
1408-----------------------------------
1409
1410Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
1411permitting a lambda to be implicitly converted to a block pointer with the
1412corresponding signature. For example, consider an API such as ``NSArray``'s
1413array-sorting method:
1414
1415.. code-block:: objc
1416
1417 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
1418
1419``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
1420(^)(id, id)``, and parameters of this type are generally provided with block
1421literals as arguments. However, one can also use a C++11 lambda so long as it
1422provides the same signature (in this case, accepting two parameters of type
1423``id`` and returning an ``NSComparisonResult``):
1424
1425.. code-block:: objc
1426
1427 NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
1428 @"String 02"];
1429 const NSStringCompareOptions comparisonOptions
1430 = NSCaseInsensitiveSearch | NSNumericSearch |
1431 NSWidthInsensitiveSearch | NSForcedOrderingSearch;
1432 NSLocale *currentLocale = [NSLocale currentLocale];
1433 NSArray *sorted
1434 = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
1435 NSRange string1Range = NSMakeRange(0, [s1 length]);
1436 return [s1 compare:s2 options:comparisonOptions
1437 range:string1Range locale:currentLocale];
1438 }];
1439 NSLog(@"sorted: %@", sorted);
1440
1441This code relies on an implicit conversion from the type of the lambda
1442expression (an unnamed, local class type called the *closure type*) to the
1443corresponding block pointer type. The conversion itself is expressed by a
1444conversion operator in that closure type that produces a block pointer with the
1445same signature as the lambda itself, e.g.,
1446
1447.. code-block:: objc
1448
1449 operator NSComparisonResult (^)(id, id)() const;
1450
1451This conversion function returns a new block that simply forwards the two
1452parameters to the lambda object (which it captures by copy), then returns the
1453result. The returned block is first copied (with ``Block_copy``) and then
1454autoreleased. As an optimization, if a lambda expression is immediately
1455converted to a block pointer (as in the first example, above), then the block
1456is not copied and autoreleased: rather, it is given the same lifetime as a
1457block literal written at that point in the program, which avoids the overhead
1458of copying a block to the heap in the common case.
1459
1460The conversion from a lambda to a block pointer is only available in
1461Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
1462management (autorelease).
1463
1464Object Literals and Subscripting
1465--------------------------------
1466
Sean Silva173d2522013-01-02 13:07:47 +00001467Clang provides support for :doc:`Object Literals and Subscripting
1468<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
Sean Silva709c44d2012-12-12 23:44:55 +00001469programming patterns, makes programs more concise, and improves the safety of
1470container creation. There are several feature macros associated with object
1471literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
1472availability of array literals; ``__has_feature(objc_dictionary_literals)``
1473tests the availability of dictionary literals;
1474``__has_feature(objc_subscripting)`` tests the availability of object
1475subscripting.
1476
1477Objective-C Autosynthesis of Properties
1478---------------------------------------
1479
1480Clang provides support for autosynthesis of declared properties. Using this
1481feature, clang provides default synthesis of those properties not declared
1482@dynamic and not having user provided backing getter and setter methods.
1483``__has_feature(objc_default_synthesize_properties)`` checks for availability
1484of this feature in version of clang being used.
1485
Jordan Rose32e94892012-12-15 00:37:01 +00001486.. _langext-objc-retain-release:
1487
1488Objective-C retaining behavior attributes
1489-----------------------------------------
1490
1491In Objective-C, functions and methods are generally assumed to follow the
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00001492`Cocoa Memory Management
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00001493<https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
Jordan Rose32e94892012-12-15 00:37:01 +00001494conventions for ownership of object arguments and
1495return values. However, there are exceptions, and so Clang provides attributes
1496to allow these exceptions to be documented. This are used by ARC and the
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001497`static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be
Aaron Ballman840cef32014-02-19 15:45:13 +00001498better described using the ``objc_method_family`` attribute instead.
Jordan Rose32e94892012-12-15 00:37:01 +00001499
1500**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
1501``ns_returns_autoreleased``, ``cf_returns_retained``, and
1502``cf_returns_not_retained`` attributes can be placed on methods and functions
1503that return Objective-C or CoreFoundation objects. They are commonly placed at
1504the end of a function prototype or method declaration:
1505
1506.. code-block:: objc
1507
1508 id foo() __attribute__((ns_returns_retained));
1509
1510 - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
1511
1512The ``*_returns_retained`` attributes specify that the returned object has a +1
1513retain count. The ``*_returns_not_retained`` attributes specify that the return
1514object has a +0 retain count, even if the normal convention for its selector
1515would be +1. ``ns_returns_autoreleased`` specifies that the returned object is
1516+0, but is guaranteed to live at least as long as the next flush of an
1517autorelease pool.
1518
1519**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
1520an parameter declaration; they specify that the argument is expected to have a
1521+1 retain count, which will be balanced in some way by the function or method.
1522The ``ns_consumes_self`` attribute can only be placed on an Objective-C
1523method; it specifies that the method expects its ``self`` parameter to have a
1524+1 retain count, which it will balance in some way.
1525
1526.. code-block:: objc
1527
1528 void foo(__attribute__((ns_consumed)) NSString *string);
1529
1530 - (void) bar __attribute__((ns_consumes_self));
1531 - (void) baz:(id) __attribute__((ns_consumed)) x;
1532
1533Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001534<https://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
Jordan Rose32e94892012-12-15 00:37:01 +00001535
1536Query for these features with ``__has_attribute(ns_consumed)``,
1537``__has_attribute(ns_returns_retained)``, etc.
1538
Nico Weber11cafc82017-07-14 18:40:52 +00001539Objective-C @available
1540----------------------
1541
1542It is possible to use the newest SDK but still build a program that can run on
Nico Weber564004a2017-07-14 18:52:30 +00001543older versions of macOS and iOS by passing ``-mmacosx-version-min=`` /
1544``-miphoneos-version-min=``.
Nico Weber11cafc82017-07-14 18:40:52 +00001545
1546Before LLVM 5.0, when calling a function that exists only in the OS that's
1547newer than the target OS (as determined by the minimum deployment version),
1548programmers had to carefully check if the function exists at runtime, using
1549null checks for weakly-linked C functions, ``+class`` for Objective-C classes,
1550and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for
1551Objective-C methods. If such a check was missed, the program would compile
1552fine, run fine on newer systems, but crash on older systems.
1553
1554As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001555<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together
Nico Weber11cafc82017-07-14 18:40:52 +00001556with the new ``@available()`` keyword to assist with this issue.
1557When a method that's introduced in the OS newer than the target OS is called, a
1558-Wunguarded-availability warning is emitted if that call is not guarded:
1559
1560.. code-block:: objc
1561
1562 void my_fun(NSSomeClass* var) {
1563 // If fancyNewMethod was added in e.g. macOS 10.12, but the code is
1564 // built with -mmacosx-version-min=10.11, then this unconditional call
1565 // will emit a -Wunguarded-availability warning:
1566 [var fancyNewMethod];
1567 }
1568
1569To fix the warning and to avoid the crash on macOS 10.11, wrap it in
1570``if(@available())``:
1571
1572.. code-block:: objc
1573
1574 void my_fun(NSSomeClass* var) {
1575 if (@available(macOS 10.12, *)) {
1576 [var fancyNewMethod];
1577 } else {
1578 // Put fallback behavior for old macOS versions (and for non-mac
1579 // platforms) here.
1580 }
1581 }
1582
1583The ``*`` is required and means that platforms not explicitly listed will take
1584the true branch, and the compiler will emit ``-Wunguarded-availability``
1585warnings for unlisted platforms based on those platform's deployment target.
1586More than one platform can be listed in ``@available()``:
1587
1588.. code-block:: objc
1589
1590 void my_fun(NSSomeClass* var) {
1591 if (@available(macOS 10.12, iOS 10, *)) {
1592 [var fancyNewMethod];
1593 }
1594 }
1595
1596If the caller of ``my_fun()`` already checks that ``my_fun()`` is only called
1597on 10.12, then add an `availability attribute
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001598<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it,
Nico Weber11cafc82017-07-14 18:40:52 +00001599which will also suppress the warning and require that calls to my_fun() are
1600checked:
1601
1602.. code-block:: objc
1603
1604 API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) {
1605 [var fancyNewMethod]; // Now ok.
1606 }
1607
1608``@available()`` is only available in Objective-C code. To use the feature
1609in C and C++ code, use the ``__builtin_available()`` spelling instead.
1610
1611If existing code uses null checks or ``-respondsToSelector:``, it should
1612be changed to use ``@available()`` (or ``__builtin_available``) instead.
1613
1614``-Wunguarded-availability`` is disabled by default, but
1615``-Wunguarded-availability-new``, which only emits this warning for APIs
1616that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and
1617tvOS >= 11, is enabled by default.
1618
1619.. _langext-overloading:
Jordan Rose32e94892012-12-15 00:37:01 +00001620
Ted Kremenek84342d62013-10-15 04:28:42 +00001621Objective-C++ ABI: protocol-qualifier mangling of parameters
1622------------------------------------------------------------
1623
1624Starting with LLVM 3.4, Clang produces a new mangling for parameters whose
1625type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such
1626parameters to be differentiated from those with the regular unqualified ``id``
1627type.
1628
1629This was a non-backward compatible mangling change to the ABI. This change
1630allows proper overloading, and also prevents mangling conflicts with template
1631parameters of protocol-qualified type.
1632
1633Query the presence of this new mangling with
1634``__has_feature(objc_protocol_qualifier_mangling)``.
1635
Anastasia Stulova79f4e472019-07-17 17:21:31 +00001636
1637OpenCL Features
1638===============
1639
1640C++ for OpenCL
1641--------------
1642
1643This functionality is built on top of OpenCL C v2.0 and C++17. Regular C++
1644features can be used in OpenCL kernel code. All functionality from OpenCL C
1645is inherited. This section describes minor differences to OpenCL C and any
1646limitations related to C++ support as well as interactions between OpenCL and
1647C++ features that are not documented elsewhere.
1648
1649Restrictions to C++17
1650^^^^^^^^^^^^^^^^^^^^^
1651
1652The following features are not supported:
1653
1654- Virtual functions
1655- ``dynamic_cast`` operator
1656- Non-placement ``new``/``delete`` operators
1657- Standard C++ libraries. Currently there is no solution for alternative C++
1658 libraries provided. Future release will feature library support.
1659
1660
1661Interplay of OpenCL and C++ features
1662^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1663
1664Address space behavior
1665""""""""""""""""""""""
1666
1667Address spaces are part of the type qualifiers; many rules are just inherited
1668from the qualifier behavior documented in OpenCL C v2.0 s6.5 and Embedded C
1669extension ISO/IEC JTC1 SC22 WG14 N1021 s3.1. Note that since the address space
1670behavior in C++ is not documented formally yet, Clang extends existing concept
1671from C and OpenCL. For example conversion rules are extended from qualification
1672conversion but the compatibility is determined using sets and overlapping from
1673Embedded C (ISO/IEC JTC1 SC22 WG14 N1021 s3.1.3). For OpenCL it means that
1674implicit conversions are allowed from named to ``__generic`` but not vice versa
1675(OpenCL C v2.0 s6.5.5) except for ``__constant`` address space. Most of the
1676rules are built on top of this behavior.
1677
1678**Casts**
1679
1680C style cast will follow OpenCL C v2.0 rules (s6.5.5). All cast operators will
1681permit implicit conversion to ``__generic``. However converting from named
1682address spaces to ``__generic`` can only be done using ``addrspace_cast``. Note
1683that conversions between ``__constant`` and any other is still disallowed.
1684
1685.. _opencl_cpp_addrsp_deduction:
1686
1687**Deduction**
1688
1689Address spaces are not deduced for:
1690
1691- non-pointer/non-reference template parameters or any dependent types except
1692 for template specializations.
1693- non-pointer/non-reference class members except for static data members that are
1694 deduced to ``__global`` address space.
1695- non-pointer/non-reference alias declarations.
1696- ``decltype`` expression.
1697
1698.. code-block:: c++
1699
1700 template <typename T>
1701 void foo() {
1702 T m; // address space of m will be known at template instantiation time.
1703 T * ptr; // ptr points to __generic address space object.
1704 T & ref = ...; // ref references an object in __generic address space.
1705 };
1706
1707 template <int N>
1708 struct S {
1709 int i; // i has no address space
1710 static int ii; // ii is in global address space
1711 int * ptr; // ptr points to __generic address space int.
1712 int & ref = ...; // ref references int in __generic address space.
1713 };
1714
1715 template <int N>
1716 void bar()
1717 {
1718 S<N> s; // s is in __private address space
1719 }
1720
1721TODO: Add example for type alias and decltype!
1722
1723**References**
1724
1725References types can be qualified with an address space.
1726
1727.. code-block:: c++
1728
1729 __private int & ref = ...; // references int in __private address space
1730
1731By default references will refer to ``__generic`` address space objects, except
1732for dependent types that are not template specializations
1733(see :ref:`Deduction <opencl_cpp_addrsp_deduction>`). Address space compatibility
1734checks are performed when references are bound to values. The logic follows the
1735rules from address space pointer conversion (OpenCL v2.0 s6.5.5).
1736
1737**Default address space**
1738
1739All non-static member functions take an implicit object parameter ``this`` that
1740is a pointer type. By default this pointer parameter is in ``__generic`` address
1741space. All concrete objects passed as an argument to ``this`` parameter will be
1742converted to ``__generic`` address space first if the conversion is valid.
1743Therefore programs using objects in ``__constant`` address space won't be compiled
1744unless address space is explicitly specified using address space qualifiers on
1745member functions
1746(see :ref:`Member function qualifier <opencl_cpp_addrspace_method_qual>`) as the
1747conversion between ``__constant`` and ``__generic`` is disallowed. Member function
1748qualifiers can also be used in case conversion to ``__generic`` address space is
1749undesirable (even if it is legal), for example to take advantage of memory bank
1750accesses. Note this not only applies to regular member functions but to
1751constructors and destructors too.
1752
1753.. _opencl_cpp_addrspace_method_qual:
1754
1755**Member function qualifier**
1756
1757Clang allows specifying address space qualifier on member functions to signal that
1758they are to be used with objects constructed in some specific address space. This
1759works just the same as qualifying member functions with ``const`` or any other
1760qualifiers. The overloading resolution will select overload with most specific
1761address space if multiple candidates are provided. If there is no conversion to
1762to an address space among existing overloads compilation will fail with a
1763diagnostic.
1764
1765.. code-block:: c++
1766
1767 struct C {
1768 void foo() __local;
1769 void foo();
1770 };
1771
1772 __kernel void bar() {
1773 __local C c1;
1774 C c2;
1775 __constant C c3;
1776 c1.foo(); // will resolve to the first foo
1777 c2.foo(); // will resolve to the second foo
1778 c3.foo(); // error due to mismatching address spaces - can't convert to
1779 // __local or __generic
1780 }
1781
1782**Implicit special members**
1783
1784All implicit special members (default, copy, or move constructor, copy or move
1785assignment, destructor) will be generated with ``__generic`` address space.
1786
1787.. code-block:: c++
1788
1789 class C {
1790 // Has the following implicit definition
1791 // void C() __generic;
1792 // void C(const __generic C &) __generic;
1793 // void C(__generic C &&) __generic;
1794 // operator= '__generic C &(__generic C &&)'
1795 // operator= '__generic C &(const __generic C &) __generic
1796 }
1797
1798**Builtin operators**
1799
1800All builtin operators are available in the specific address spaces, thus no conversion
1801to ``__generic`` is performed.
1802
1803**Templates**
1804
1805There is no deduction of address spaces in non-pointer/non-reference template parameters
1806and dependent types (see :ref:`Deduction <opencl_cpp_addrsp_deduction>`). The address
1807space of template parameter is deduced during the type deduction if it's not explicitly
1808provided in instantiation.
1809
1810.. code-block:: c++
1811
1812 1 template<typename T>
1813 2 void foo(T* i){
1814 3 T var;
1815 4 }
1816 5
1817 6 __global int g;
1818 7 void bar(){
1819 8 foo(&g); // error: template instantiation failed as function scope variable appears to
1820 9 // be declared in __global address space (see line 3)
1821 10 }
1822
1823It is not legal to specify multiple different address spaces between template definition and
1824instantiation. If multiple different address spaces are specified in template definition and
1825instantiation compilation of such program will fail with a diagnostic.
1826
1827.. code-block:: c++
1828
1829 template <typename T>
1830 void foo() {
1831 __private T var;
1832 }
1833
1834 void bar() {
1835 foo<__global int>(); // error: conflicting address space qualifiers are provided __global
1836 // and __private
1837 }
1838
1839Once template is instantiated regular restrictions for address spaces will apply.
1840
1841.. code-block:: c++
1842
1843 template<typename T>
1844 void foo(){
1845 T var;
1846 }
1847
1848 void bar(){
1849 foo<__global int>(); // error: function scope variable cannot be declared in __global
1850 // address space
1851 }
1852
1853**Temporary materialization**
1854
1855All temporaries are materialized in ``__private`` address space. If a reference with some
1856other address space is bound to them, the conversion will be generated in case it's valid
1857otherwise compilation will fail with a diagnostic.
1858
1859.. code-block:: c++
1860
1861 int bar(const unsigned int &i);
1862
1863 void foo() {
1864 bar(1); // temporary is created in __private address space but converted
1865 // to __generic address space of parameter reference
1866 }
1867
1868 __global const int& f(__global float &ref) {
1869 return ref; // error: address space mismatch between temporary object
1870 // created to hold value converted float->int and return
1871 // value type (can't convert from __private to __global)
1872 }
1873
1874**Initialization of local and constant address space objects**
1875
1876TODO
1877
1878Constructing and destroying global objects
1879^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1880
1881Global objects are constructed before the first kernel using the global
1882objects is executed and destroyed just after the last kernel using the
1883program objects is executed. In OpenCL v2.0 drivers there is no specific
1884API for invoking global constructors. However, an easy workaround would be
1885to enqueue constructor initialization kernel that has a name
1886``@_GLOBAL__sub_I_<compiled file name>``. This kernel is only present if there
1887are any global objects to be initialized in the compiled binary. One way to
1888check this is by passing ``CL_PROGRAM_KERNEL_NAMES`` to ``clGetProgramInfo``
1889(OpenCL v2.0 s5.8.7).
1890
1891Note that if multiple files are compiled and linked into libraries multiple
1892kernels that initialize global objects for multiple modules would have to be
1893invoked.
1894
1895.. code-block:: console
1896
Anastasia Stulova88ed70e2019-07-25 11:04:29 +00001897 clang -cl-std=clc++ test.cl
Anastasia Stulova79f4e472019-07-17 17:21:31 +00001898
1899If there are any global objects to be initialized the final binary will
1900contain ``@_GLOBAL__sub_I_test.cl`` kernel to be enqueued.
1901
1902Global destructors can not be invoked in OpenCL v2.0 drivers. However, all
1903memory used for program scope objects is released on ``clReleaseProgram``.
1904
Sean Silva709c44d2012-12-12 23:44:55 +00001905Initializer lists for complex numbers in C
1906==========================================
1907
1908clang supports an extension which allows the following in C:
1909
1910.. code-block:: c++
1911
1912 #include <math.h>
1913 #include <complex.h>
1914 complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
1915
1916This construct is useful because there is no way to separately initialize the
1917real and imaginary parts of a complex variable in standard C, given that clang
1918does not support ``_Imaginary``. (Clang also supports the ``__real__`` and
1919``__imag__`` extensions from gcc, which help in some cases, but are not usable
1920in static initializers.)
1921
1922Note that this extension does not allow eliding the braces; the meaning of the
1923following two lines is different:
1924
1925.. code-block:: c++
1926
1927 complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
1928 complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
1929
1930This extension also works in C++ mode, as far as that goes, but does not apply
1931to the C++ ``std::complex``. (In C++11, list initialization allows the same
1932syntax to be used with ``std::complex`` with the same meaning.)
1933
1934Builtin Functions
1935=================
1936
1937Clang supports a number of builtin library functions with the same syntax as
1938GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
1939``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
Hal Finkelbcc06082014-09-07 22:58:14 +00001940``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc. In addition to
1941the GCC builtins, Clang supports a number of builtins that GCC does not, which
1942are listed here.
Sean Silva709c44d2012-12-12 23:44:55 +00001943
1944Please note that Clang does not and will not support all of the GCC builtins
1945for vector operations. Instead of using builtins, you should use the functions
1946defined in target-specific header files like ``<xmmintrin.h>``, which define
1947portable wrappers for these. Many of the Clang versions of these functions are
1948implemented directly in terms of :ref:`extended vector support
1949<langext-vectors>` instead of builtins, in order to reduce the number of
1950builtins that we need to implement.
1951
Hal Finkelbcc06082014-09-07 22:58:14 +00001952``__builtin_assume``
1953------------------------------
1954
1955``__builtin_assume`` is used to provide the optimizer with a boolean
1956invariant that is defined to be true.
1957
1958**Syntax**:
1959
1960.. code-block:: c++
1961
1962 __builtin_assume(bool)
1963
1964**Example of Use**:
1965
1966.. code-block:: c++
1967
1968 int foo(int x) {
1969 __builtin_assume(x != 0);
1970
1971 // The optimizer may short-circuit this check using the invariant.
1972 if (x == 0)
1973 return do_something();
1974
1975 return do_something_else();
1976 }
1977
1978**Description**:
1979
1980The boolean argument to this function is defined to be true. The optimizer may
1981analyze the form of the expression provided as the argument and deduce from
1982that information used to optimize the program. If the condition is violated
1983during execution, the behavior is undefined. The argument itself is never
1984evaluated, so any side effects of the expression will be discarded.
1985
1986Query for this feature with ``__has_builtin(__builtin_assume)``.
1987
Sean Silva709c44d2012-12-12 23:44:55 +00001988``__builtin_readcyclecounter``
1989------------------------------
1990
1991``__builtin_readcyclecounter`` is used to access the cycle counter register (or
1992a similar low-latency, high-accuracy clock) on those targets that support it.
1993
1994**Syntax**:
1995
1996.. code-block:: c++
1997
1998 __builtin_readcyclecounter()
1999
2000**Example of Use**:
2001
2002.. code-block:: c++
2003
2004 unsigned long long t0 = __builtin_readcyclecounter();
2005 do_something();
2006 unsigned long long t1 = __builtin_readcyclecounter();
2007 unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
2008
2009**Description**:
2010
2011The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
2012which may be either global or process/thread-specific depending on the target.
2013As the backing counters often overflow quickly (on the order of seconds) this
2014should only be used for timing small intervals. When not supported by the
2015target, the return value is always zero. This builtin takes no arguments and
2016produces an unsigned long long result.
2017
Tim Northoverbfe2e5f72013-05-23 19:14:12 +00002018Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
2019that even if present, its use may depend on run-time privilege or other OS
2020controlled state.
Sean Silva709c44d2012-12-12 23:44:55 +00002021
2022.. _langext-__builtin_shufflevector:
2023
2024``__builtin_shufflevector``
2025---------------------------
2026
2027``__builtin_shufflevector`` is used to express generic vector
2028permutation/shuffle/swizzle operations. This builtin is also very important
2029for the implementation of various target-specific header files like
2030``<xmmintrin.h>``.
2031
2032**Syntax**:
2033
2034.. code-block:: c++
2035
2036 __builtin_shufflevector(vec1, vec2, index1, index2, ...)
2037
2038**Examples**:
2039
2040.. code-block:: c++
2041
Craig Topper50ad5b72013-08-03 17:40:38 +00002042 // identity operation - return 4-element vector v1.
2043 __builtin_shufflevector(v1, v1, 0, 1, 2, 3)
Sean Silva709c44d2012-12-12 23:44:55 +00002044
2045 // "Splat" element 0 of V1 into a 4-element result.
2046 __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
2047
2048 // Reverse 4-element vector V1.
2049 __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
2050
2051 // Concatenate every other element of 4-element vectors V1 and V2.
2052 __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
2053
2054 // Concatenate every other element of 8-element vectors V1 and V2.
2055 __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
2056
Craig Topper50ad5b72013-08-03 17:40:38 +00002057 // Shuffle v1 with some elements being undefined
2058 __builtin_shufflevector(v1, v1, 3, -1, 1, -1)
2059
Sean Silva709c44d2012-12-12 23:44:55 +00002060**Description**:
2061
2062The first two arguments to ``__builtin_shufflevector`` are vectors that have
2063the same element type. The remaining arguments are a list of integers that
2064specify the elements indices of the first two vectors that should be extracted
2065and returned in a new vector. These element indices are numbered sequentially
2066starting with the first vector, continuing into the second vector. Thus, if
2067``vec1`` is a 4-element vector, index 5 would refer to the second element of
Craig Topper50ad5b72013-08-03 17:40:38 +00002068``vec2``. An index of -1 can be used to indicate that the corresponding element
2069in the returned vector is a don't care and can be optimized by the backend.
Sean Silva709c44d2012-12-12 23:44:55 +00002070
2071The result of ``__builtin_shufflevector`` is a vector with the same element
2072type as ``vec1``/``vec2`` but that has an element count equal to the number of
2073indices specified.
2074
2075Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
2076
Anton Yartsev94e46f32014-09-03 17:59:21 +00002077.. _langext-__builtin_convertvector:
2078
Hal Finkelc4d7c822013-09-18 03:29:45 +00002079``__builtin_convertvector``
2080---------------------------
2081
2082``__builtin_convertvector`` is used to express generic vector
2083type-conversion operations. The input vector and the output vector
2084type must have the same number of elements.
2085
2086**Syntax**:
2087
2088.. code-block:: c++
2089
2090 __builtin_convertvector(src_vec, dst_vec_type)
2091
2092**Examples**:
2093
2094.. code-block:: c++
2095
2096 typedef double vector4double __attribute__((__vector_size__(32)));
2097 typedef float vector4float __attribute__((__vector_size__(16)));
2098 typedef short vector4short __attribute__((__vector_size__(8)));
2099 vector4float vf; vector4short vs;
2100
2101 // convert from a vector of 4 floats to a vector of 4 doubles.
2102 __builtin_convertvector(vf, vector4double)
2103 // equivalent to:
2104 (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }
2105
2106 // convert from a vector of 4 shorts to a vector of 4 floats.
2107 __builtin_convertvector(vs, vector4float)
2108 // equivalent to:
Yunzhong Gao637cb90b2014-09-02 19:24:14 +00002109 (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] }
Hal Finkelc4d7c822013-09-18 03:29:45 +00002110
2111**Description**:
2112
2113The first argument to ``__builtin_convertvector`` is a vector, and the second
2114argument is a vector type with the same number of elements as the first
2115argument.
2116
2117The result of ``__builtin_convertvector`` is a vector with the same element
2118type as the second argument, with a value defined in terms of the action of a
2119C-style cast applied to each element of the first argument.
2120
2121Query for this feature with ``__has_builtin(__builtin_convertvector)``.
2122
Matt Arsenault08087c52016-03-23 22:14:43 +00002123``__builtin_bitreverse``
Aaron Ballmanbcf13da2016-03-24 12:34:44 +00002124------------------------
Matt Arsenault08087c52016-03-23 22:14:43 +00002125
2126* ``__builtin_bitreverse8``
2127* ``__builtin_bitreverse16``
2128* ``__builtin_bitreverse32``
2129* ``__builtin_bitreverse64``
2130
2131**Syntax**:
2132
2133.. code-block:: c++
Aaron Ballmanbcf13da2016-03-24 12:34:44 +00002134
Matt Arsenault08087c52016-03-23 22:14:43 +00002135 __builtin_bitreverse32(x)
2136
2137**Examples**:
2138
2139.. code-block:: c++
Aaron Ballmanbcf13da2016-03-24 12:34:44 +00002140
Matt Arsenault08087c52016-03-23 22:14:43 +00002141 uint8_t rev_x = __builtin_bitreverse8(x);
2142 uint16_t rev_x = __builtin_bitreverse16(x);
2143 uint32_t rev_y = __builtin_bitreverse32(y);
2144 uint64_t rev_z = __builtin_bitreverse64(z);
2145
2146**Description**:
2147
2148The '``__builtin_bitreverse``' family of builtins is used to reverse
2149the bitpattern of an integer value; for example ``0b10110110`` becomes
2150``0b01101101``.
2151
Sanjay Patelad823902018-08-19 16:50:30 +00002152``__builtin_rotateleft``
2153------------------------
2154
2155* ``__builtin_rotateleft8``
2156* ``__builtin_rotateleft16``
2157* ``__builtin_rotateleft32``
2158* ``__builtin_rotateleft64``
2159
2160**Syntax**:
2161
2162.. code-block:: c++
2163
2164 __builtin_rotateleft32(x, y)
2165
2166**Examples**:
2167
2168.. code-block:: c++
2169
2170 uint8_t rot_x = __builtin_rotateleft8(x, y);
2171 uint16_t rot_x = __builtin_rotateleft16(x, y);
2172 uint32_t rot_x = __builtin_rotateleft32(x, y);
2173 uint64_t rot_x = __builtin_rotateleft64(x, y);
2174
2175**Description**:
2176
2177The '``__builtin_rotateleft``' family of builtins is used to rotate
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00002178the bits in the first argument by the amount in the second argument.
Sanjay Patelad823902018-08-19 16:50:30 +00002179For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``.
2180The shift value is treated as an unsigned amount modulo the size of
2181the arguments. Both arguments and the result have the bitwidth specified
2182by the name of the builtin.
2183
2184``__builtin_rotateright``
Kristina Brooks233a4982019-04-05 18:26:43 +00002185-------------------------
Sanjay Patelad823902018-08-19 16:50:30 +00002186
2187* ``__builtin_rotateright8``
2188* ``__builtin_rotateright16``
2189* ``__builtin_rotateright32``
2190* ``__builtin_rotateright64``
2191
2192**Syntax**:
2193
2194.. code-block:: c++
2195
2196 __builtin_rotateright32(x, y)
2197
2198**Examples**:
2199
2200.. code-block:: c++
2201
2202 uint8_t rot_x = __builtin_rotateright8(x, y);
2203 uint16_t rot_x = __builtin_rotateright16(x, y);
2204 uint32_t rot_x = __builtin_rotateright32(x, y);
2205 uint64_t rot_x = __builtin_rotateright64(x, y);
2206
2207**Description**:
2208
2209The '``__builtin_rotateright``' family of builtins is used to rotate
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00002210the bits in the first argument by the amount in the second argument.
Sanjay Patelad823902018-08-19 16:50:30 +00002211For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``.
2212The shift value is treated as an unsigned amount modulo the size of
2213the arguments. Both arguments and the result have the bitwidth specified
2214by the name of the builtin.
2215
Sean Silva709c44d2012-12-12 23:44:55 +00002216``__builtin_unreachable``
2217-------------------------
2218
2219``__builtin_unreachable`` is used to indicate that a specific point in the
2220program cannot be reached, even if the compiler might otherwise think it can.
2221This is useful to improve optimization and eliminates certain warnings. For
2222example, without the ``__builtin_unreachable`` in the example below, the
2223compiler assumes that the inline asm can fall through and prints a "function
2224declared '``noreturn``' should not return" warning.
2225
2226**Syntax**:
2227
2228.. code-block:: c++
2229
2230 __builtin_unreachable()
2231
2232**Example of use**:
2233
2234.. code-block:: c++
2235
2236 void myabort(void) __attribute__((noreturn));
2237 void myabort(void) {
2238 asm("int3");
2239 __builtin_unreachable();
2240 }
2241
2242**Description**:
2243
2244The ``__builtin_unreachable()`` builtin has completely undefined behavior.
2245Since it has undefined behavior, it is a statement that it is never reached and
2246the optimizer can take advantage of this to produce better code. This builtin
2247takes no arguments and produces a void result.
2248
2249Query for this feature with ``__has_builtin(__builtin_unreachable)``.
2250
Sanjay Patela24296b2015-09-02 20:01:30 +00002251``__builtin_unpredictable``
2252---------------------------
2253
2254``__builtin_unpredictable`` is used to indicate that a branch condition is
2255unpredictable by hardware mechanisms such as branch prediction logic.
2256
2257**Syntax**:
2258
2259.. code-block:: c++
2260
2261 __builtin_unpredictable(long long)
2262
2263**Example of use**:
2264
2265.. code-block:: c++
2266
2267 if (__builtin_unpredictable(x > 0)) {
2268 foo();
2269 }
2270
2271**Description**:
2272
2273The ``__builtin_unpredictable()`` builtin is expected to be used with control
2274flow conditions such as in ``if`` and ``switch`` statements.
2275
2276Query for this feature with ``__has_builtin(__builtin_unpredictable)``.
2277
Sean Silva709c44d2012-12-12 23:44:55 +00002278``__sync_swap``
2279---------------
2280
2281``__sync_swap`` is used to atomically swap integers or pointers in memory.
2282
2283**Syntax**:
2284
2285.. code-block:: c++
2286
2287 type __sync_swap(type *ptr, type value, ...)
2288
2289**Example of Use**:
2290
2291.. code-block:: c++
2292
2293 int old_value = __sync_swap(&value, new_value);
2294
2295**Description**:
2296
2297The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
2298atomic intrinsics to allow code to atomically swap the current value with the
2299new value. More importantly, it helps developers write more efficient and
2300correct code by avoiding expensive loops around
2301``__sync_bool_compare_and_swap()`` or relying on the platform specific
2302implementation details of ``__sync_lock_test_and_set()``. The
2303``__sync_swap()`` builtin is a full barrier.
2304
Richard Smith6cbd65d2013-07-11 02:27:57 +00002305``__builtin_addressof``
2306-----------------------
2307
2308``__builtin_addressof`` performs the functionality of the built-in ``&``
2309operator, ignoring any ``operator&`` overload. This is useful in constant
2310expressions in C++11, where there is no other way to take the address of an
2311object that overloads ``operator&``.
2312
2313**Example of use**:
2314
2315.. code-block:: c++
2316
2317 template<typename T> constexpr T *addressof(T &value) {
2318 return __builtin_addressof(value);
2319 }
2320
Richard Smith760520b2014-06-03 23:27:44 +00002321``__builtin_operator_new`` and ``__builtin_operator_delete``
2322------------------------------------------------------------
2323
2324``__builtin_operator_new`` allocates memory just like a non-placement non-class
2325*new-expression*. This is exactly like directly calling the normal
2326non-placement ``::operator new``, except that it allows certain optimizations
2327that the C++ standard does not permit for a direct function call to
2328``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and
2329merging allocations).
2330
2331Likewise, ``__builtin_operator_delete`` deallocates memory just like a
2332non-class *delete-expression*, and is exactly like directly calling the normal
2333``::operator delete``, except that it permits optimizations. Only the unsized
2334form of ``__builtin_operator_delete`` is currently available.
2335
2336These builtins are intended for use in the implementation of ``std::allocator``
2337and other similar allocation libraries, and are only available in C++.
2338
Yonghong Song048493f2019-07-09 04:21:50 +00002339``__builtin_preserve_access_index``
2340-----------------------------------
2341
2342``__builtin_preserve_access_index`` specifies a code section where
2343array subscript access and structure/union member access are relocatable
2344under bpf compile-once run-everywhere framework. Debuginfo (typically
2345with ``-g``) is needed, otherwise, the compiler will exit with an error.
2346
2347**Syntax**:
2348
2349.. code-block:: c
2350
2351 const void * __builtin_preserve_access_index(const void * ptr)
2352
2353**Example of Use**:
2354
2355.. code-block:: c
2356
2357 struct t {
2358 int i;
2359 int j;
2360 union {
2361 int a;
2362 int b;
2363 } c[4];
2364 };
2365 struct t *v = ...;
2366 const void *pb =__builtin_preserve_access_index(&v->c[3].b);
2367
Michael Gottesmanc5cc9f12013-01-13 04:35:31 +00002368Multiprecision Arithmetic Builtins
2369----------------------------------
2370
2371Clang provides a set of builtins which expose multiprecision arithmetic in a
2372manner amenable to C. They all have the following form:
2373
2374.. code-block:: c
2375
2376 unsigned x = ..., y = ..., carryin = ..., carryout;
2377 unsigned sum = __builtin_addc(x, y, carryin, &carryout);
2378
2379Thus one can form a multiprecision addition chain in the following manner:
2380
2381.. code-block:: c
2382
2383 unsigned *x, *y, *z, carryin=0, carryout;
2384 z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
2385 carryin = carryout;
2386 z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
2387 carryin = carryout;
2388 z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
2389 carryin = carryout;
2390 z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
2391
2392The complete list of builtins are:
2393
2394.. code-block:: c
2395
Michael Gottesman15343992013-06-18 20:40:40 +00002396 unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
Michael Gottesmanc5cc9f12013-01-13 04:35:31 +00002397 unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
2398 unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
2399 unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
2400 unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
Michael Gottesman15343992013-06-18 20:40:40 +00002401 unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
Michael Gottesmanc5cc9f12013-01-13 04:35:31 +00002402 unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
2403 unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
2404 unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
2405 unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
2406
Michael Gottesman930ecdb2013-06-20 23:28:10 +00002407Checked Arithmetic Builtins
2408---------------------------
2409
2410Clang provides a set of builtins that implement checked arithmetic for security
2411critical applications in a manner that is fast and easily expressable in C. As
2412an example of their usage:
2413
2414.. code-block:: c
2415
2416 errorcode_t security_critical_application(...) {
2417 unsigned x, y, result;
2418 ...
John McCall03107a42015-10-29 20:48:01 +00002419 if (__builtin_mul_overflow(x, y, &result))
Michael Gottesman930ecdb2013-06-20 23:28:10 +00002420 return kErrorCodeHackers;
2421 ...
2422 use_multiply(result);
2423 ...
2424 }
2425
John McCall03107a42015-10-29 20:48:01 +00002426Clang provides the following checked arithmetic builtins:
Michael Gottesman930ecdb2013-06-20 23:28:10 +00002427
2428.. code-block:: c
2429
John McCall03107a42015-10-29 20:48:01 +00002430 bool __builtin_add_overflow (type1 x, type2 y, type3 *sum);
2431 bool __builtin_sub_overflow (type1 x, type2 y, type3 *diff);
2432 bool __builtin_mul_overflow (type1 x, type2 y, type3 *prod);
Michael Gottesman930ecdb2013-06-20 23:28:10 +00002433 bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum);
2434 bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);
2435 bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);
2436 bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff);
2437 bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);
2438 bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);
2439 bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod);
2440 bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);
2441 bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);
2442 bool __builtin_sadd_overflow (int x, int y, int *sum);
2443 bool __builtin_saddl_overflow (long x, long y, long *sum);
2444 bool __builtin_saddll_overflow(long long x, long long y, long long *sum);
2445 bool __builtin_ssub_overflow (int x, int y, int *diff);
2446 bool __builtin_ssubl_overflow (long x, long y, long *diff);
2447 bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);
2448 bool __builtin_smul_overflow (int x, int y, int *prod);
2449 bool __builtin_smull_overflow (long x, long y, long *prod);
2450 bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
2451
John McCall03107a42015-10-29 20:48:01 +00002452Each builtin performs the specified mathematical operation on the
2453first two arguments and stores the result in the third argument. If
2454possible, the result will be equal to mathematically-correct result
2455and the builtin will return 0. Otherwise, the builtin will return
24561 and the result will be equal to the unique value that is equivalent
2457to the mathematically-correct result modulo two raised to the *k*
2458power, where *k* is the number of bits in the result type. The
2459behavior of these builtins is well-defined for all argument values.
2460
2461The first three builtins work generically for operands of any integer type,
2462including boolean types. The operands need not have the same type as each
2463other, or as the result. The other builtins may implicitly promote or
2464convert their operands before performing the operation.
2465
2466Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc.
Michael Gottesman930ecdb2013-06-20 23:28:10 +00002467
Matt Arsenault2d933982016-02-27 09:06:18 +00002468Floating point builtins
2469---------------------------------------
2470
2471``__builtin_canonicalize``
2472--------------------------
2473
2474.. code-block:: c
2475
2476 double __builtin_canonicalize(double);
2477 float __builtin_canonicalizef(float);
2478 long double__builtin_canonicalizel(long double);
2479
2480Returns the platform specific canonical encoding of a floating point
2481number. This canonicalization is useful for implementing certain
2482numeric primitives such as frexp. See `LLVM canonicalize intrinsic
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00002483<https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for
Matt Arsenault2d933982016-02-27 09:06:18 +00002484more information on the semantics.
2485
Richard Smith67d484b2017-01-20 00:57:59 +00002486String builtins
2487---------------
2488
2489Clang provides constant expression evaluation support for builtins forms of
Richard Smith0abb11c2017-01-23 18:17:46 +00002490the following functions from the C standard library ``<string.h>`` header:
Richard Smith67d484b2017-01-20 00:57:59 +00002491
2492* ``memchr``
2493* ``memcmp``
2494* ``strchr``
2495* ``strcmp``
2496* ``strlen``
2497* ``strncmp``
2498* ``wcschr``
2499* ``wcscmp``
2500* ``wcslen``
2501* ``wcsncmp``
2502* ``wmemchr``
2503* ``wmemcmp``
2504
2505In each case, the builtin form has the name of the C library function prefixed
Richard Smith90854c42017-01-20 01:08:15 +00002506by ``__builtin_``. Example:
Richard Smith67d484b2017-01-20 00:57:59 +00002507
2508.. code-block:: c
2509
2510 void *p = __builtin_memchr("foobar", 'b', 5);
2511
2512In addition to the above, one further builtin is provided:
2513
2514.. code-block:: c
2515
2516 char *__builtin_char_memchr(const char *haystack, int needle, size_t size);
2517
2518``__builtin_char_memchr(a, b, c)`` is identical to
2519``(char*)__builtin_memchr(a, b, c)`` except that its use is permitted within
2520constant expressions in C++11 onwards (where a cast from ``void*`` to ``char*``
2521is disallowed in general).
2522
2523Support for constant expression evaluation for the above builtins be detected
2524with ``__has_feature(cxx_constexpr_string_builtins)``.
2525
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00002526Atomic Min/Max builtins with memory ordering
2527--------------------------------------------
2528
2529There are two atomic builtins with min/max in-memory comparison and swap.
2530The syntax and semantics are similar to GCC-compatible __atomic_* builtins.
2531
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00002532* ``__atomic_fetch_min``
2533* ``__atomic_fetch_max``
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00002534
2535The builtins work with signed and unsigned integers and require to specify memory ordering.
2536The return value is the original value that was stored in memory before comparison.
2537
2538Example:
2539
2540.. code-block:: c
2541
2542 unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED);
2543
2544The third argument is one of the memory ordering specifiers ``__ATOMIC_RELAXED``,
2545``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, ``__ATOMIC_RELEASE``,
2546``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics.
2547
2548In terms or aquire-release ordering barriers these two operations are always
2549considered as operations with *load-store* semantics, even when the original value
2550is not actually modified after comparison.
2551
Sean Silva709c44d2012-12-12 23:44:55 +00002552.. _langext-__c11_atomic:
2553
2554__c11_atomic builtins
2555---------------------
2556
2557Clang provides a set of builtins which are intended to be used to implement
2558C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the
2559``_explicit`` form of the corresponding C11 operation, and are named with a
Hal Finkel6970ac82014-10-03 04:29:40 +00002560``__c11_`` prefix. The supported operations, and the differences from
2561the corresponding C11 operations, are:
Sean Silva709c44d2012-12-12 23:44:55 +00002562
2563* ``__c11_atomic_init``
2564* ``__c11_atomic_thread_fence``
2565* ``__c11_atomic_signal_fence``
Hal Finkel6970ac82014-10-03 04:29:40 +00002566* ``__c11_atomic_is_lock_free`` (The argument is the size of the
Dan Liewfe726862014-10-03 12:36:20 +00002567 ``_Atomic(...)`` object, instead of its address)
Sean Silva709c44d2012-12-12 23:44:55 +00002568* ``__c11_atomic_store``
2569* ``__c11_atomic_load``
2570* ``__c11_atomic_exchange``
2571* ``__c11_atomic_compare_exchange_strong``
2572* ``__c11_atomic_compare_exchange_weak``
2573* ``__c11_atomic_fetch_add``
2574* ``__c11_atomic_fetch_sub``
2575* ``__c11_atomic_fetch_and``
2576* ``__c11_atomic_fetch_or``
2577* ``__c11_atomic_fetch_xor``
2578
Hal Finkel6970ac82014-10-03 04:29:40 +00002579The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``,
JF Bastiene6ccacf2014-10-10 16:09:48 +00002580``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are
Hal Finkel6970ac82014-10-03 04:29:40 +00002581provided, with values corresponding to the enumerators of C11's
2582``memory_order`` enumeration.
2583
James Y Knight81167fb2015-08-05 16:57:36 +00002584(Note that Clang additionally provides GCC-compatible ``__atomic_*``
Yaxun Liu39195062017-08-04 18:16:31 +00002585builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.0
2586atomic builtins are an explicit form of the corresponding OpenCL 2.0
2587builtin function, and are named with a ``__opencl_`` prefix. The macros
2588``__OPENCL_MEMORY_SCOPE_WORK_ITEM``, ``__OPENCL_MEMORY_SCOPE_WORK_GROUP``,
2589``__OPENCL_MEMORY_SCOPE_DEVICE``, ``__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES``,
2590and ``__OPENCL_MEMORY_SCOPE_SUB_GROUP`` are provided, with values
2591corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.)
James Y Knight81167fb2015-08-05 16:57:36 +00002592
Tim Northover6aacd492013-07-16 09:47:53 +00002593Low-level ARM exclusive memory builtins
2594---------------------------------------
2595
2596Clang provides overloaded builtins giving direct access to the three key ARM
2597instructions for implementing atomic operations.
2598
2599.. code-block:: c
Sean Silvaa928c242013-09-09 19:50:40 +00002600
Tim Northover6aacd492013-07-16 09:47:53 +00002601 T __builtin_arm_ldrex(const volatile T *addr);
Tim Northover3acd6bd2014-07-02 12:56:02 +00002602 T __builtin_arm_ldaex(const volatile T *addr);
Tim Northover6aacd492013-07-16 09:47:53 +00002603 int __builtin_arm_strex(T val, volatile T *addr);
Tim Northover3acd6bd2014-07-02 12:56:02 +00002604 int __builtin_arm_stlex(T val, volatile T *addr);
Tim Northover6aacd492013-07-16 09:47:53 +00002605 void __builtin_arm_clrex(void);
2606
2607The types ``T`` currently supported are:
Michael Zolotukhinc3f09ff2015-09-10 23:56:10 +00002608
Tim Northover573cbee2014-05-24 12:52:07 +00002609* Integer types with width at most 64 bits (or 128 bits on AArch64).
Tim Northover6aacd492013-07-16 09:47:53 +00002610* Floating-point types
2611* Pointer types.
2612
2613Note that the compiler does not guarantee it will not insert stores which clear
Tim Northover3acd6bd2014-07-02 12:56:02 +00002614the exclusive monitor in between an ``ldrex`` type operation and its paired
2615``strex``. In practice this is only usually a risk when the extra store is on
2616the same cache line as the variable being modified and Clang will only insert
2617stack stores on its own, so it is best not to use these operations on variables
2618with automatic storage duration.
Tim Northover6aacd492013-07-16 09:47:53 +00002619
2620Also, loads and stores may be implicit in code written between the ``ldrex`` and
2621``strex``. Clang will not necessarily mitigate the effects of these either, so
2622care should be exercised.
2623
2624For these reasons the higher level atomic primitives should be preferred where
2625possible.
2626
Michael Zolotukhin59d72b12015-09-11 02:01:15 +00002627Non-temporal load/store builtins
2628--------------------------------
2629
2630Clang provides overloaded builtins allowing generation of non-temporal memory
2631accesses.
2632
2633.. code-block:: c
2634
2635 T __builtin_nontemporal_load(T *addr);
2636 void __builtin_nontemporal_store(T value, T *addr);
2637
2638The types ``T`` currently supported are:
2639
2640* Integer types.
2641* Floating-point types.
2642* Vector types.
2643
2644Note that the compiler does not guarantee that non-temporal loads or stores
2645will be used.
2646
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00002647C++ Coroutines support builtins
2648--------------------------------
2649
2650.. warning::
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00002651 This is a work in progress. Compatibility across Clang/LLVM releases is not
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00002652 guaranteed.
2653
2654Clang provides experimental builtins to support C++ Coroutines as defined by
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00002655https://wg21.link/P0057. The following four are intended to be used by the
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00002656standard library to implement `std::experimental::coroutine_handle` type.
2657
2658**Syntax**:
2659
2660.. code-block:: c
2661
2662 void __builtin_coro_resume(void *addr);
2663 void __builtin_coro_destroy(void *addr);
2664 bool __builtin_coro_done(void *addr);
2665 void *__builtin_coro_promise(void *addr, int alignment, bool from_promise)
2666
2667**Example of use**:
2668
2669.. code-block:: c++
2670
2671 template <> struct coroutine_handle<void> {
2672 void resume() const { __builtin_coro_resume(ptr); }
2673 void destroy() const { __builtin_coro_destroy(ptr); }
2674 bool done() const { return __builtin_coro_done(ptr); }
2675 // ...
2676 protected:
2677 void *ptr;
2678 };
2679
2680 template <typename Promise> struct coroutine_handle : coroutine_handle<> {
2681 // ...
2682 Promise &promise() const {
2683 return *reinterpret_cast<Promise *>(
2684 __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false));
2685 }
2686 static coroutine_handle from_promise(Promise &promise) {
2687 coroutine_handle p;
2688 p.ptr = __builtin_coro_promise(&promise, alignof(Promise),
2689 /*from-promise=*/true);
2690 return p;
2691 }
2692 };
2693
2694
2695Other coroutine builtins are either for internal clang use or for use during
2696development of the coroutine feature. See `Coroutines in LLVM
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00002697<https://llvm.org/docs/Coroutines.html#intrinsics>`_ for
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00002698more information on their semantics. Note that builtins matching the intrinsics
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00002699that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc,
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00002700llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to
2701an appropriate value during the emission.
2702
2703**Syntax**:
2704
2705.. code-block:: c
2706
2707 size_t __builtin_coro_size()
2708 void *__builtin_coro_frame()
2709 void *__builtin_coro_free(void *coro_frame)
2710
2711 void *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts)
2712 bool __builtin_coro_alloc()
2713 void *__builtin_coro_begin(void *memory)
2714 void __builtin_coro_end(void *coro_frame, bool unwind)
2715 char __builtin_coro_suspend(bool final)
2716 bool __builtin_coro_param(void *original, void *copy)
2717
2718Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM
2719automatically will insert one if the first argument to `llvm.coro.suspend` is
2720token `none`. If a user calls `__builin_suspend`, clang will insert `token none`
2721as the first argument to the intrinsic.
2722
Eric Fiselier708afb52019-05-16 21:04:15 +00002723Source location builtins
2724------------------------
2725
2726Clang provides experimental builtins to support C++ standard library implementation
2727of ``std::experimental::source_location`` as specified in http://wg21.link/N4600.
2728With the exception of ``__builtin_COLUMN``, these builtins are also implemented by
2729GCC.
2730
2731**Syntax**:
2732
2733.. code-block:: c
2734
2735 const char *__builtin_FILE();
2736 const char *__builtin_FUNCTION();
2737 unsigned __builtin_LINE();
2738 unsigned __builtin_COLUMN(); // Clang only
2739
2740**Example of use**:
2741
2742.. code-block:: c++
2743
2744 void my_assert(bool pred, int line = __builtin_LINE(), // Captures line of caller
2745 const char* file = __builtin_FILE(),
2746 const char* function = __builtin_FUNCTION()) {
2747 if (pred) return;
2748 printf("%s:%d assertion failed in function %s\n", file, line, function);
2749 std::abort();
2750 }
2751
2752 struct MyAggregateType {
2753 int x;
2754 int line = __builtin_LINE(); // captures line where aggregate initialization occurs
2755 };
2756 static_assert(MyAggregateType{42}.line == __LINE__);
2757
2758 struct MyClassType {
2759 int line = __builtin_LINE(); // captures line of the constructor used during initialization
2760 constexpr MyClassType(int) { assert(line == __LINE__); }
2761 };
2762
2763**Description**:
2764
2765The builtins ``__builtin_LINE``, ``__builtin_FUNCTION``, and ``__builtin_FILE`` return
2766the values, at the "invocation point", for ``__LINE__``, ``__FUNCTION__``, and
2767``__FILE__`` respectively. These builtins are constant expressions.
2768
2769When the builtins appear as part of a default function argument the invocation
2770point is the location of the caller. When the builtins appear as part of a
2771default member initializer, the invocation point is the location of the
2772constructor or aggregate initialization used to create the object. Otherwise
2773the invocation point is the same as the location of the builtin.
2774
2775When the invocation point of ``__builtin_FUNCTION`` is not a function scope the
2776empty string is returned.
2777
Sean Silva709c44d2012-12-12 23:44:55 +00002778Non-standard C++11 Attributes
2779=============================
2780
Richard Smithf6d2d3b2013-02-14 00:13:34 +00002781Clang's non-standard C++11 attributes live in the ``clang`` attribute
2782namespace.
Sean Silva709c44d2012-12-12 23:44:55 +00002783
Aaron Ballman68893db2014-02-19 23:21:40 +00002784Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which
Richard Smithf6d2d3b2013-02-14 00:13:34 +00002785are accepted with the ``__attribute__((foo))`` syntax are also accepted as
2786``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
2787(see the list of `GCC function attributes
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00002788<https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
2789attributes <https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
Richard Smithf6d2d3b2013-02-14 00:13:34 +00002790`GCC type attributes
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00002791<https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
Richard Smithf6d2d3b2013-02-14 00:13:34 +00002792implementation, these attributes must appertain to the *declarator-id* in a
2793declaration, which means they must go either at the start of the declaration or
2794immediately after the name being declared.
2795
2796For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
2797also applies the GNU ``noreturn`` attribute to ``f``.
2798
2799.. code-block:: c++
2800
2801 [[gnu::unused]] int a, f [[gnu::noreturn]] ();
2802
Sean Silva709c44d2012-12-12 23:44:55 +00002803Target-Specific Extensions
2804==========================
2805
2806Clang supports some language features conditionally on some targets.
2807
Yi Kong4de26fb2014-07-23 09:25:02 +00002808ARM/AArch64 Language Extensions
2809-------------------------------
2810
2811Memory Barrier Intrinsics
2812^^^^^^^^^^^^^^^^^^^^^^^^^
2813Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined
2814in the `ARM C Language Extensions Release 2.0
2815<http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053c/IHI0053C_acle_2_0.pdf>`_.
2816Note that these intrinsics are implemented as motion barriers that block
2817reordering of memory accesses and side effect instructions. Other instructions
Sylvestre Ledrube8f3962016-02-14 20:20:58 +00002818like simple arithmetic may be reordered around the intrinsic. If you expect to
Yi Kong4de26fb2014-07-23 09:25:02 +00002819have no reordering at all, use inline assembly instead.
2820
Sean Silva709c44d2012-12-12 23:44:55 +00002821X86/X86-64 Language Extensions
2822------------------------------
2823
2824The X86 backend has these language extensions:
2825
David L Kreitzerd8984102016-05-03 20:20:59 +00002826Memory references to specified segments
2827^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Sean Silva709c44d2012-12-12 23:44:55 +00002828
2829Annotating a pointer with address space #256 causes it to be code generated
David L Kreitzerd8984102016-05-03 20:20:59 +00002830relative to the X86 GS segment register, address space #257 causes it to be
2831relative to the X86 FS segment, and address space #258 causes it to be
2832relative to the X86 SS segment. Note that this is a very very low-level
Sean Silva709c44d2012-12-12 23:44:55 +00002833feature that should only be used if you know what you're doing (for example in
2834an OS kernel).
2835
2836Here is an example:
2837
2838.. code-block:: c++
2839
2840 #define GS_RELATIVE __attribute__((address_space(256)))
2841 int foo(int GS_RELATIVE *P) {
2842 return *P;
2843 }
2844
2845Which compiles to (on X86-32):
2846
2847.. code-block:: gas
2848
2849 _foo:
2850 movl 4(%esp), %eax
2851 movl %gs:(%eax), %eax
2852 ret
2853
JF Bastienfff5dc02019-07-14 18:33:51 +00002854You can also use the GCC compatibility macros ``__seg_fs`` and ``__seg_gs`` for
2855the same purpose. The preprocessor symbols ``__SEG_FS`` and ``__SEG_GS``
2856indicate their support.
2857
Kang Zhange5ac3852019-03-29 09:11:52 +00002858PowerPC Language Extensions
2859------------------------------
2860
2861Set the Floating Point Rounding Mode
David Zarzyckib0888452019-08-21 06:48:11 +00002862^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Kang Zhange5ac3852019-03-29 09:11:52 +00002863PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set
2864the floating point rounding mode. This function will use the least significant
2865two bits of integer argument to set the floating point rounding mode.
2866
2867.. code-block:: c++
2868
2869 double __builtin_setrnd(int mode);
2870
2871The effective values for mode are:
2872
2873 - 0 - round to nearest
2874 - 1 - round to zero
2875 - 2 - round to +infinity
2876 - 3 - round to -infinity
2877
2878Note that the mode argument will modulo 4, so if the integer argument is greater
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00002879than 3, it will only use the least significant two bits of the mode.
Kang Zhange5ac3852019-03-29 09:11:52 +00002880Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``.
2881
Ahsan Saghir3962d6d2019-04-29 23:25:33 +00002882PowerPC cache builtins
2883^^^^^^^^^^^^^^^^^^^^^^
2884
2885The PowerPC architecture specifies instructions implementing cache operations.
2886Clang provides builtins that give direct programmer access to these cache
2887instructions.
2888
2889Currently the following builtins are implemented in clang:
2890
2891``__builtin_dcbf`` copies the contents of a modified block from the data cache
2892to main memory and flushes the copy from the data cache.
2893
2894**Syntax**:
2895
2896.. code-block:: c
2897
2898 void __dcbf(const void* addr); /* Data Cache Block Flush */
2899
2900**Example of Use**:
2901
2902.. code-block:: c
2903
2904 int a = 1;
2905 __builtin_dcbf (&a);
2906
Jordan Rose32e94892012-12-15 00:37:01 +00002907Extensions for Static Analysis
Dmitri Gribenkoace09a22012-12-15 14:25:25 +00002908==============================
Sean Silva709c44d2012-12-12 23:44:55 +00002909
2910Clang supports additional attributes that are useful for documenting program
Jordan Rose32e94892012-12-15 00:37:01 +00002911invariants and rules for static analysis tools, such as the `Clang Static
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00002912Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented
Jordan Rose32e94892012-12-15 00:37:01 +00002913in the analyzer's `list of source-level annotations
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00002914<https://clang-analyzer.llvm.org/annotations.html>`_.
Sean Silva709c44d2012-12-12 23:44:55 +00002915
Sean Silva709c44d2012-12-12 23:44:55 +00002916
Jordan Rose32e94892012-12-15 00:37:01 +00002917Extensions for Dynamic Analysis
Dmitri Gribenkoace09a22012-12-15 14:25:25 +00002918===============================
Sean Silva709c44d2012-12-12 23:44:55 +00002919
Sean Silva709c44d2012-12-12 23:44:55 +00002920Use ``__has_feature(address_sanitizer)`` to check if the code is being built
Dmitri Gribenkoace09a22012-12-15 14:25:25 +00002921with :doc:`AddressSanitizer`.
Sean Silva709c44d2012-12-12 23:44:55 +00002922
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00002923Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
2924with :doc:`ThreadSanitizer`.
2925
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00002926Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
2927with :doc:`MemorySanitizer`.
Dario Domizioli33c17872014-05-28 14:06:38 +00002928
Peter Collingbournec4122c12015-06-15 21:08:13 +00002929Use ``__has_feature(safe_stack)`` to check if the code is being built
2930with :doc:`SafeStack`.
2931
Dario Domizioli33c17872014-05-28 14:06:38 +00002932
2933Extensions for selectively disabling optimization
2934=================================================
2935
2936Clang provides a mechanism for selectively disabling optimizations in functions
2937and methods.
2938
2939To disable optimizations in a single function definition, the GNU-style or C++11
2940non-standard attribute ``optnone`` can be used.
2941
2942.. code-block:: c++
2943
2944 // The following functions will not be optimized.
2945 // GNU-style attribute
2946 __attribute__((optnone)) int foo() {
2947 // ... code
2948 }
2949 // C++11 attribute
2950 [[clang::optnone]] int bar() {
2951 // ... code
2952 }
2953
2954To facilitate disabling optimization for a range of function definitions, a
2955range-based pragma is provided. Its syntax is ``#pragma clang optimize``
2956followed by ``off`` or ``on``.
2957
2958All function definitions in the region between an ``off`` and the following
2959``on`` will be decorated with the ``optnone`` attribute unless doing so would
2960conflict with explicit attributes already present on the function (e.g. the
2961ones that control inlining).
2962
2963.. code-block:: c++
2964
2965 #pragma clang optimize off
2966 // This function will be decorated with optnone.
2967 int foo() {
2968 // ... code
2969 }
2970
2971 // optnone conflicts with always_inline, so bar() will not be decorated.
2972 __attribute__((always_inline)) int bar() {
2973 // ... code
2974 }
2975 #pragma clang optimize on
2976
2977If no ``on`` is found to close an ``off`` region, the end of the region is the
2978end of the compilation unit.
2979
2980Note that a stray ``#pragma clang optimize on`` does not selectively enable
2981additional optimizations when compiling at low optimization levels. This feature
2982can only be used to selectively disable optimizations.
2983
2984The pragma has an effect on functions only at the point of their definition; for
2985function templates, this means that the state of the pragma at the point of an
2986instantiation is not necessarily relevant. Consider the following example:
2987
2988.. code-block:: c++
2989
2990 template<typename T> T twice(T t) {
2991 return 2 * t;
2992 }
2993
2994 #pragma clang optimize off
2995 template<typename T> T thrice(T t) {
2996 return 3 * t;
2997 }
2998
2999 int container(int a, int b) {
3000 return twice(a) + thrice(b);
3001 }
3002 #pragma clang optimize on
3003
3004In this example, the definition of the template function ``twice`` is outside
3005the pragma region, whereas the definition of ``thrice`` is inside the region.
3006The ``container`` function is also in the region and will not be optimized, but
3007it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of
3008these two instantiations, ``twice`` will be optimized (because its definition
3009was outside the region) and ``thrice`` will not be optimized.
Tyler Nowickidb2668a2014-06-18 00:51:32 +00003010
3011Extensions for loop hint optimizations
3012======================================
3013
3014The ``#pragma clang loop`` directive is used to specify hints for optimizing the
3015subsequent for, while, do-while, or c++11 range-based for loop. The directive
Sjoerd Meijera48f58c2019-07-25 07:33:13 +00003016provides options for vectorization, interleaving, predication, unrolling and
Adam Nemet2de463e2016-06-14 12:04:26 +00003017distribution. Loop hints can be specified before any loop and will be ignored if
3018the optimization is not safe to apply.
Eli Bendersky778268d2014-06-19 18:12:44 +00003019
Sjoerd Meijera48f58c2019-07-25 07:33:13 +00003020Vectorization, Interleaving, and Predication
3021--------------------------------------------
Tyler Nowickidb2668a2014-06-18 00:51:32 +00003022
3023A vectorized loop performs multiple iterations of the original loop
3024in parallel using vector instructions. The instruction set of the target
3025processor determines which vector instructions are available and their vector
3026widths. This restricts the types of loops that can be vectorized. The vectorizer
3027automatically determines if the loop is safe and profitable to vectorize. A
3028vector instruction cost model is used to select the vector width.
3029
3030Interleaving multiple loop iterations allows modern processors to further
3031improve instruction-level parallelism (ILP) using advanced hardware features,
3032such as multiple execution units and out-of-order execution. The vectorizer uses
3033a cost model that depends on the register pressure and generated code size to
3034select the interleaving count.
3035
3036Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled
3037by ``interleave(enable)``. This is useful when compiling with ``-Os`` to
3038manually enable vectorization or interleaving.
3039
3040.. code-block:: c++
3041
3042 #pragma clang loop vectorize(enable)
3043 #pragma clang loop interleave(enable)
3044 for(...) {
3045 ...
3046 }
3047
3048The vector width is specified by ``vectorize_width(_value_)`` and the interleave
3049count is specified by ``interleave_count(_value_)``, where
3050_value_ is a positive integer. This is useful for specifying the optimal
3051width/count of the set of target architectures supported by your application.
3052
3053.. code-block:: c++
3054
Tyler Nowickidb2668a2014-06-18 00:51:32 +00003055 #pragma clang loop vectorize_width(2)
3056 #pragma clang loop interleave_count(2)
3057 for(...) {
3058 ...
3059 }
3060
3061Specifying a width/count of 1 disables the optimization, and is equivalent to
3062``vectorize(disable)`` or ``interleave(disable)``.
3063
Sjoerd Meijera48f58c2019-07-25 07:33:13 +00003064Vector predication is enabled by ``vectorize_predicate(enable)``, for example:
3065
3066.. code-block:: c++
3067
3068 #pragma clang loop vectorize(enable)
3069 #pragma clang loop vectorize_predicate(enable)
3070 for(...) {
3071 ...
3072 }
3073
3074This predicates (masks) all instructions in the loop, which allows the scalar
3075remainder loop (the tail) to be folded into the main vectorized loop. This
3076might be more efficient when vector predication is efficiently supported by the
3077target platform.
3078
Eli Bendersky778268d2014-06-19 18:12:44 +00003079Loop Unrolling
3080--------------
3081
3082Unrolling a loop reduces the loop control overhead and exposes more
3083opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling
3084eliminates the loop and replaces it with an enumerated sequence of loop
3085iterations. Full unrolling is only possible if the loop trip count is known at
3086compile time. Partial unrolling replicates the loop body within the loop and
3087reduces the trip count.
3088
Mark Heffernan397a98d2015-08-10 17:29:39 +00003089If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the
Mark Heffernan7ccb5e22015-07-13 18:31:37 +00003090loop if the trip count is known at compile time. If the fully unrolled code size
3091is greater than an internal limit the loop will be partially unrolled up to this
Mark Heffernan397a98d2015-08-10 17:29:39 +00003092limit. If the trip count is not known at compile time the loop will be partially
3093unrolled with a heuristically chosen unroll factor.
3094
3095.. code-block:: c++
3096
3097 #pragma clang loop unroll(enable)
3098 for(...) {
3099 ...
3100 }
3101
3102If ``unroll(full)`` is specified the unroller will attempt to fully unroll the
3103loop if the trip count is known at compile time identically to
3104``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled
3105if the loop count is not known at compile time.
Eli Bendersky778268d2014-06-19 18:12:44 +00003106
3107.. code-block:: c++
3108
Mark Heffernan450c2382014-07-23 17:31:31 +00003109 #pragma clang loop unroll(full)
Eli Bendersky778268d2014-06-19 18:12:44 +00003110 for(...) {
3111 ...
3112 }
3113
3114The unroll count can be specified explicitly with ``unroll_count(_value_)`` where
3115_value_ is a positive integer. If this value is greater than the trip count the
3116loop will be fully unrolled. Otherwise the loop is partially unrolled subject
Mark Heffernan397a98d2015-08-10 17:29:39 +00003117to the same code size limit as with ``unroll(enable)``.
Eli Bendersky778268d2014-06-19 18:12:44 +00003118
3119.. code-block:: c++
3120
3121 #pragma clang loop unroll_count(8)
3122 for(...) {
3123 ...
3124 }
3125
3126Unrolling of a loop can be prevented by specifying ``unroll(disable)``.
3127
Adam Nemet2de463e2016-06-14 12:04:26 +00003128Loop Distribution
3129-----------------
3130
3131Loop Distribution allows splitting a loop into multiple loops. This is
3132beneficial for example when the entire loop cannot be vectorized but some of the
3133resulting loops can.
3134
Adam Nemet0c58eb72016-06-14 19:33:16 +00003135If ``distribute(enable))`` is specified and the loop has memory dependencies
Adam Nemet2de463e2016-06-14 12:04:26 +00003136that inhibit vectorization, the compiler will attempt to isolate the offending
3137operations into a new loop. This optimization is not enabled by default, only
3138loops marked with the pragma are considered.
3139
3140.. code-block:: c++
3141
3142 #pragma clang loop distribute(enable)
3143 for (i = 0; i < N; ++i) {
3144 S1: A[i + 1] = A[i] + B[i];
3145 S2: C[i] = D[i] * E[i];
3146 }
3147
3148This loop will be split into two loops between statements S1 and S2. The
3149second loop containing S2 will be vectorized.
3150
3151Loop Distribution is currently not enabled by default in the optimizer because
3152it can hurt performance in some cases. For example, instruction-level
3153parallelism could be reduced by sequentializing the execution of the
3154statements S1 and S2 above.
3155
3156If Loop Distribution is turned on globally with
3157``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can
3158be used the disable it on a per-loop basis.
3159
Eli Bendersky778268d2014-06-19 18:12:44 +00003160Additional Information
3161----------------------
3162
Tyler Nowickidb2668a2014-06-18 00:51:32 +00003163For convenience multiple loop hints can be specified on a single line.
3164
3165.. code-block:: c++
3166
3167 #pragma clang loop vectorize_width(4) interleave_count(8)
3168 for(...) {
3169 ...
3170 }
3171
3172If an optimization cannot be applied any hints that apply to it will be ignored.
3173For example, the hint ``vectorize_width(4)`` is ignored if the loop is not
3174proven safe to vectorize. To identify and diagnose optimization issues use
3175`-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the
3176user guide for details.
Adam Nemet60d32642017-04-04 21:18:36 +00003177
3178Extensions to specify floating-point flags
3179====================================================
3180
3181The ``#pragma clang fp`` pragma allows floating-point options to be specified
3182for a section of the source code. This pragma can only appear at file scope or
3183at the start of a compound statement (excluding comments). When using within a
3184compound statement, the pragma is active within the scope of the compound
3185statement.
3186
3187Currently, only FP contraction can be controlled with the pragma. ``#pragma
3188clang fp contract`` specifies whether the compiler should contract a multiply
3189and an addition (or subtraction) into a fused FMA operation when supported by
3190the target.
3191
3192The pragma can take three values: ``on``, ``fast`` and ``off``. The ``on``
3193option is identical to using ``#pragma STDC FP_CONTRACT(ON)`` and it allows
3194fusion as specified the language standard. The ``fast`` option allows fusiong
3195in cases when the language standard does not make this possible (e.g. across
3196statements in C)
3197
3198.. code-block:: c++
3199
3200 for(...) {
3201 #pragma clang fp contract(fast)
3202 a = b[i] * c[i];
3203 d[i] += a;
3204 }
3205
3206
Adam Nemete73e00c2017-04-04 22:45:20 +00003207The pragma can also be used with ``off`` which turns FP contraction off for a
Adam Nemet60d32642017-04-04 21:18:36 +00003208section of the code. This can be useful when fast contraction is otherwise
Adam Nemetd7f95112017-04-04 23:46:34 +00003209enabled for the translation unit with the ``-ffp-contract=fast`` flag.
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003210
3211Specifying an attribute for multiple declarations (#pragma clang attribute)
3212===========================================================================
3213
3214The ``#pragma clang attribute`` directive can be used to apply an attribute to
3215multiple declarations. The ``#pragma clang attribute push`` variation of the
Erik Pilkington7d180942018-10-29 17:38:42 +00003216directive pushes a new "scope" of ``#pragma clang attribute`` that attributes
3217can be added to. The ``#pragma clang attribute (...)`` variation adds an
3218attribute to that scope, and the ``#pragma clang attribute pop`` variation pops
3219the scope. You can also use ``#pragma clang attribute push (...)``, which is a
3220shorthand for when you want to add one attribute to a new scope. Multiple push
3221directives can be nested inside each other.
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003222
3223The attributes that are used in the ``#pragma clang attribute`` directives
3224can be written using the GNU-style syntax:
3225
3226.. code-block:: c++
3227
Erik Pilkington7d180942018-10-29 17:38:42 +00003228 #pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function)
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003229
3230 void function(); // The function now has the annotate("custom") attribute
3231
3232 #pragma clang attribute pop
3233
3234The attributes can also be written using the C++11 style syntax:
3235
3236.. code-block:: c++
3237
Erik Pilkington7d180942018-10-29 17:38:42 +00003238 #pragma clang attribute push ([[noreturn]], apply_to = function)
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003239
3240 void function(); // The function now has the [[noreturn]] attribute
3241
3242 #pragma clang attribute pop
3243
3244The ``__declspec`` style syntax is also supported:
3245
3246.. code-block:: c++
3247
Erik Pilkington7d180942018-10-29 17:38:42 +00003248 #pragma clang attribute push (__declspec(dllexport), apply_to = function)
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003249
3250 void function(); // The function now has the __declspec(dllexport) attribute
3251
3252 #pragma clang attribute pop
3253
3254A single push directive accepts only one attribute regardless of the syntax
3255used.
3256
Erik Pilkington0876cae2018-12-20 22:32:04 +00003257Because multiple push directives can be nested, if you're writing a macro that
3258expands to ``_Pragma("clang attribute")`` it's good hygiene (though not
3259required) to add a namespace to your push/pop directives. A pop directive with a
3260namespace will pop the innermost push that has that same namespace. This will
3261ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note
3262that an ``pop`` without a namespace will pop the innermost ``push`` without a
3263namespace. ``push``es with a namespace can only be popped by ``pop`` with the
3264same namespace. For instance:
3265
3266.. code-block:: c++
3267
3268 #define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)")
3269 #define ASSUME_NORETURN_END _Pragma("clang attribute AssumeNoreturn.pop")
3270
3271 #define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)")
3272 #define ASSUME_UNAVAILABLE_END _Pragma("clang attribute Unavailable.pop")
3273
3274
3275 ASSUME_NORETURN_BEGIN
3276 ASSUME_UNAVAILABLE_BEGIN
3277 void function(); // function has [[noreturn]] and __attribute__((unavailable))
3278 ASSUME_NORETURN_END
3279 void other_function(); // function has __attribute__((unavailable))
3280 ASSUME_UNAVAILABLE_END
3281
3282Without the namespaces on the macros, ``other_function`` will be annotated with
3283``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like
3284a contrived example, but its very possible for this kind of situation to appear
Erik Pilkingtonb460f162019-01-07 21:54:00 +00003285in real code if the pragmas are spread out across a large file. You can test if
3286your version of clang supports namespaces on ``#pragma clang attribute`` with
Erik Pilkington6ccc1732019-01-08 18:24:39 +00003287``__has_extension(pragma_clang_attribute_namespaces)``.
Erik Pilkington0876cae2018-12-20 22:32:04 +00003288
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003289Subject Match Rules
3290-------------------
3291
3292The set of declarations that receive a single attribute from the attribute stack
3293depends on the subject match rules that were specified in the pragma. Subject
3294match rules are specified after the attribute. The compiler expects an
3295identifier that corresponds to the subject set specifier. The ``apply_to``
3296specifier is currently the only supported subject set specifier. It allows you
3297to specify match rules that form a subset of the attribute's allowed subject
3298set, i.e. the compiler doesn't require all of the attribute's subjects. For
3299example, an attribute like ``[[nodiscard]]`` whose subject set includes
3300``enum``, ``record`` and ``hasType(functionType)``, requires the presence of at
3301least one of these rules after ``apply_to``:
3302
3303.. code-block:: c++
3304
3305 #pragma clang attribute push([[nodiscard]], apply_to = enum)
3306
3307 enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]]
3308
3309 struct Record1 { }; // The struct will *not* receive [[nodiscard]]
3310
3311 #pragma clang attribute pop
3312
3313 #pragma clang attribute push([[nodiscard]], apply_to = any(record, enum))
3314
3315 enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]]
3316
3317 struct Record2 { }; // The struct *will* receive [[nodiscard]]
3318
3319 #pragma clang attribute pop
3320
3321 // This is an error, since [[nodiscard]] can't be applied to namespaces:
3322 #pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace))
3323
3324 #pragma clang attribute pop
3325
3326Multiple match rules can be specified using the ``any`` match rule, as shown
3327in the example above. The ``any`` rule applies attributes to all declarations
3328that are matched by at least one of the rules in the ``any``. It doesn't nest
3329and can't be used inside the other match rules. Redundant match rules or rules
3330that conflict with one another should not be used inside of ``any``.
3331
3332Clang supports the following match rules:
3333
3334- ``function``: Can be used to apply attributes to functions. This includes C++
3335 member functions, static functions, operators, and constructors/destructors.
3336
3337- ``function(is_member)``: Can be used to apply attributes to C++ member
3338 functions. This includes members like static functions, operators, and
3339 constructors/destructors.
3340
3341- ``hasType(functionType)``: Can be used to apply attributes to functions, C++
3342 member functions, and variables/fields whose type is a function pointer. It
3343 does not apply attributes to Objective-C methods or blocks.
3344
3345- ``type_alias``: Can be used to apply attributes to ``typedef`` declarations
3346 and C++11 type aliases.
3347
3348- ``record``: Can be used to apply attributes to ``struct``, ``class``, and
3349 ``union`` declarations.
3350
3351- ``record(unless(is_union))``: Can be used to apply attributes only to
3352 ``struct`` and ``class`` declarations.
3353
3354- ``enum``: Can be be used to apply attributes to enumeration declarations.
3355
3356- ``enum_constant``: Can be used to apply attributes to enumerators.
3357
3358- ``variable``: Can be used to apply attributes to variables, including
3359 local variables, parameters, global variables, and static member variables.
3360 It does not apply attributes to instance member variables or Objective-C
3361 ivars.
3362
3363- ``variable(is_thread_local)``: Can be used to apply attributes to thread-local
3364 variables only.
3365
3366- ``variable(is_global)``: Can be used to apply attributes to global variables
3367 only.
3368
3369- ``variable(is_parameter)``: Can be used to apply attributes to parameters
3370 only.
3371
3372- ``variable(unless(is_parameter))``: Can be used to apply attributes to all
3373 the variables that are not parameters.
3374
3375- ``field``: Can be used to apply attributes to non-static member variables
3376 in a record. This includes Objective-C ivars.
3377
3378- ``namespace``: Can be used to apply attributes to ``namespace`` declarations.
3379
3380- ``objc_interface``: Can be used to apply attributes to ``@interface``
3381 declarations.
3382
3383- ``objc_protocol``: Can be used to apply attributes to ``@protocol``
3384 declarations.
3385
3386- ``objc_category``: Can be used to apply attributes to category declarations,
3387 including class extensions.
3388
3389- ``objc_method``: Can be used to apply attributes to Objective-C methods,
3390 including instance and class methods. Implicit methods like implicit property
3391 getters and setters do not receive the attribute.
3392
3393- ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C
3394 instance methods.
3395
3396- ``objc_property``: Can be used to apply attributes to ``@property``
3397 declarations.
3398
3399- ``block``: Can be used to apply attributes to block declarations. This does
3400 not include variables/fields of block pointer type.
3401
3402The use of ``unless`` in match rules is currently restricted to a strict set of
3403sub-rules that are used by the supported attributes. That means that even though
3404``variable(unless(is_parameter))`` is a valid match rule,
3405``variable(unless(is_thread_local))`` is not.
3406
3407Supported Attributes
3408--------------------
3409
3410Not all attributes can be used with the ``#pragma clang attribute`` directive.
3411Notably, statement attributes like ``[[fallthrough]]`` or type attributes
3412like ``address_space`` aren't supported by this directive. You can determine
3413whether or not an attribute is supported by the pragma by referring to the
3414:doc:`individual documentation for that attribute <AttributeReference>`.
3415
3416The attributes are applied to all matching declarations individually, even when
3417the attribute is semantically incorrect. The attributes that aren't applied to
3418any declaration are not verified semantically.
Javed Absar2a67c9e2017-06-05 10:11:57 +00003419
3420Specifying section names for global objects (#pragma clang section)
3421===================================================================
3422
3423The ``#pragma clang section`` directive provides a means to assign section-names
3424to global variables, functions and static variables.
3425
3426The section names can be specified as:
3427
3428.. code-block:: c++
3429
3430 #pragma clang section bss="myBSS" data="myData" rodata="myRodata" text="myText"
3431
3432The section names can be reverted back to default name by supplying an empty
3433string to the section kind, for example:
3434
3435.. code-block:: c++
3436
3437 #pragma clang section bss="" data="" text="" rodata=""
3438
3439The ``#pragma clang section`` directive obeys the following rules:
3440
3441* The pragma applies to all global variable, statics and function declarations
3442 from the pragma to the end of the translation unit.
3443
3444* The pragma clang section is enabled automatically, without need of any flags.
3445
3446* This feature is only defined to work sensibly for ELF targets.
3447
3448* If section name is specified through _attribute_((section("myname"))), then
3449 the attribute name gains precedence.
3450
3451* Global variables that are initialized to zero will be placed in the named
3452 bss section, if one is present.
3453
3454* The ``#pragma clang section`` directive does not does try to infer section-kind
3455 from the name. For example, naming a section "``.bss.mySec``" does NOT mean
3456 it will be a bss section name.
3457
3458* The decision about which section-kind applies to each global is taken in the back-end.
3459 Once the section-kind is known, appropriate section name, as specified by the user using
3460 ``#pragma clang section`` directive, is applied to that global.
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00003461
3462Specifying Linker Options on ELF Targets
3463========================================
3464
3465The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets.
3466The second parameter is the library name (without the traditional Unix prefix of
3467``lib``). This allows you to provide an implicit link of dependent libraries.
Erik Pilkington9c3b5882019-01-30 20:34:53 +00003468
3469Evaluating Object Size Dynamically
3470==================================
3471
3472Clang supports the builtin ``__builtin_dynamic_object_size``, the semantics are
3473the same as GCC's ``__builtin_object_size`` (which Clang also supports), but
3474``__builtin_dynamic_object_size`` can evaluate the object's size at runtime.
3475``__builtin_dynamic_object_size`` is meant to be used as a drop-in replacement
3476for ``__builtin_object_size`` in libraries that support it.
3477
3478For instance, here is a program that ``__builtin_dynamic_object_size`` will make
3479safer:
3480
3481.. code-block:: c
3482
3483 void copy_into_buffer(size_t size) {
3484 char* buffer = malloc(size);
3485 strlcpy(buffer, "some string", strlen("some string"));
3486 // Previous line preprocesses to:
3487 // __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buffer, 0))
3488 }
3489
3490Since the size of ``buffer`` can't be known at compile time, Clang will fold
3491``__builtin_object_size(buffer, 0)`` into ``-1``. However, if this was written
3492as ``__builtin_dynamic_object_size(buffer, 0)``, Clang will fold it into
3493``size``, providing some extra runtime safety.