1========================= 2Clang Language Extensions 3========================= 4 5.. contents:: 6 :local: 7 :depth: 1 8 9.. toctree:: 10 :hidden: 11 12 ObjectiveCLiterals 13 BlockLanguageSpec 14 Block-ABI-Apple 15 AutomaticReferenceCounting 16 MatrixTypes 17 18Introduction 19============ 20 21This document describes the language extensions provided by Clang. In addition 22to the language extensions listed here, Clang aims to support a broad range of 23GCC extensions. Please see the `GCC manual 24<https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on 25these extensions. 26 27.. _langext-feature_check: 28 29Feature Checking Macros 30======================= 31 32Language extensions can be very useful, but only if you know you can depend on 33them. In order to allow fine-grain features checks, we support three builtin 34function-like macros. This allows you to directly test for a feature in your 35code without having to resort to something like autoconf or fragile "compiler 36version checks". 37 38``__has_builtin`` 39----------------- 40 41This function-like macro takes a single identifier argument that is the name of 42a builtin function, a builtin pseudo-function (taking one or more type 43arguments), or a builtin template. 44It evaluates to 1 if the builtin is supported or 0 if not. 45It can be used like this: 46 47.. code-block:: c++ 48 49 #ifndef __has_builtin // Optional of course. 50 #define __has_builtin(x) 0 // Compatibility with non-clang compilers. 51 #endif 52 53 ... 54 #if __has_builtin(__builtin_trap) 55 __builtin_trap(); 56 #else 57 abort(); 58 #endif 59 ... 60 61.. note:: 62 63 Prior to Clang 10, ``__has_builtin`` could not be used to detect most builtin 64 pseudo-functions. 65 66 ``__has_builtin`` should not be used to detect support for a builtin macro; 67 use ``#ifdef`` instead. 68 69.. _langext-__has_feature-__has_extension: 70 71``__has_feature`` and ``__has_extension`` 72----------------------------------------- 73 74These function-like macros take a single identifier argument that is the name 75of a feature. ``__has_feature`` evaluates to 1 if the feature is both 76supported by Clang and standardized in the current language standard or 0 if 77not (but see :ref:`below <langext-has-feature-back-compat>`), while 78``__has_extension`` evaluates to 1 if the feature is supported by Clang in the 79current language (either as a language extension or a standard language 80feature) or 0 if not. They can be used like this: 81 82.. code-block:: c++ 83 84 #ifndef __has_feature // Optional of course. 85 #define __has_feature(x) 0 // Compatibility with non-clang compilers. 86 #endif 87 #ifndef __has_extension 88 #define __has_extension __has_feature // Compatibility with pre-3.0 compilers. 89 #endif 90 91 ... 92 #if __has_feature(cxx_rvalue_references) 93 // This code will only be compiled with the -std=c++11 and -std=gnu++11 94 // options, because rvalue references are only standardized in C++11. 95 #endif 96 97 #if __has_extension(cxx_rvalue_references) 98 // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98 99 // and -std=gnu++98 options, because rvalue references are supported as a 100 // language extension in C++98. 101 #endif 102 103.. _langext-has-feature-back-compat: 104 105For backward compatibility, ``__has_feature`` can also be used to test 106for support for non-standardized features, i.e. features not prefixed ``c_``, 107``cxx_`` or ``objc_``. 108 109Another use of ``__has_feature`` is to check for compiler features not related 110to the language standard, such as e.g. :doc:`AddressSanitizer 111<AddressSanitizer>`. 112 113If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent 114to ``__has_feature``. 115 116The feature tag is described along with the language feature below. 117 118The feature name or extension name can also be specified with a preceding and 119following ``__`` (double underscore) to avoid interference from a macro with 120the same name. For instance, ``__cxx_rvalue_references__`` can be used instead 121of ``cxx_rvalue_references``. 122 123``__has_cpp_attribute`` 124----------------------- 125 126This function-like macro is available in C++20 by default, and is provided as an 127extension in earlier language standards. It takes a single argument that is the 128name of a double-square-bracket-style attribute. The argument can either be a 129single identifier or a scoped identifier. If the attribute is supported, a 130nonzero value is returned. If the attribute is a standards-based attribute, this 131macro returns a nonzero value based on the year and month in which the attribute 132was voted into the working draft. See `WG21 SD-6 133<https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_ 134for the list of values returned for standards-based attributes. If the attribute 135is not supported by the current compilation target, this macro evaluates to 0. 136It can be used like this: 137 138.. code-block:: c++ 139 140 #ifndef __has_cpp_attribute // For backwards compatibility 141 #define __has_cpp_attribute(x) 0 142 #endif 143 144 ... 145 #if __has_cpp_attribute(clang::fallthrough) 146 #define FALLTHROUGH [[clang::fallthrough]] 147 #else 148 #define FALLTHROUGH 149 #endif 150 ... 151 152The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are 153the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either 154of these namespaces can be specified with a preceding and following ``__`` 155(double underscore) to avoid interference from a macro with the same name. For 156instance, ``gnu::__const__`` can be used instead of ``gnu::const``. 157 158``__has_c_attribute`` 159--------------------- 160 161This function-like macro takes a single argument that is the name of an 162attribute exposed with the double square-bracket syntax in C mode. The argument 163can either be a single identifier or a scoped identifier. If the attribute is 164supported, a nonzero value is returned. If the attribute is not supported by the 165current compilation target, this macro evaluates to 0. It can be used like this: 166 167.. code-block:: c 168 169 #ifndef __has_c_attribute // Optional of course. 170 #define __has_c_attribute(x) 0 // Compatibility with non-clang compilers. 171 #endif 172 173 ... 174 #if __has_c_attribute(fallthrough) 175 #define FALLTHROUGH [[fallthrough]] 176 #else 177 #define FALLTHROUGH 178 #endif 179 ... 180 181The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are 182the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either 183of these namespaces can be specified with a preceding and following ``__`` 184(double underscore) to avoid interference from a macro with the same name. For 185instance, ``gnu::__const__`` can be used instead of ``gnu::const``. 186 187``__has_attribute`` 188------------------- 189 190This function-like macro takes a single identifier argument that is the name of 191a GNU-style attribute. It evaluates to 1 if the attribute is supported by the 192current compilation target, or 0 if not. It can be used like this: 193 194.. code-block:: c++ 195 196 #ifndef __has_attribute // Optional of course. 197 #define __has_attribute(x) 0 // Compatibility with non-clang compilers. 198 #endif 199 200 ... 201 #if __has_attribute(always_inline) 202 #define ALWAYS_INLINE __attribute__((always_inline)) 203 #else 204 #define ALWAYS_INLINE 205 #endif 206 ... 207 208The attribute name can also be specified with a preceding and following ``__`` 209(double underscore) to avoid interference from a macro with the same name. For 210instance, ``__always_inline__`` can be used instead of ``always_inline``. 211 212 213``__has_declspec_attribute`` 214---------------------------- 215 216This function-like macro takes a single identifier argument that is the name of 217an attribute implemented as a Microsoft-style ``__declspec`` attribute. It 218evaluates to 1 if the attribute is supported by the current compilation target, 219or 0 if not. It can be used like this: 220 221.. code-block:: c++ 222 223 #ifndef __has_declspec_attribute // Optional of course. 224 #define __has_declspec_attribute(x) 0 // Compatibility with non-clang compilers. 225 #endif 226 227 ... 228 #if __has_declspec_attribute(dllexport) 229 #define DLLEXPORT __declspec(dllexport) 230 #else 231 #define DLLEXPORT 232 #endif 233 ... 234 235The attribute name can also be specified with a preceding and following ``__`` 236(double underscore) to avoid interference from a macro with the same name. For 237instance, ``__dllexport__`` can be used instead of ``dllexport``. 238 239``__is_identifier`` 240------------------- 241 242This function-like macro takes a single identifier argument that might be either 243a reserved word or a regular identifier. It evaluates to 1 if the argument is just 244a regular identifier and not a reserved word, in the sense that it can then be 245used as the name of a user-defined function or variable. Otherwise it evaluates 246to 0. It can be used like this: 247 248.. code-block:: c++ 249 250 ... 251 #ifdef __is_identifier // Compatibility with non-clang compilers. 252 #if __is_identifier(__wchar_t) 253 typedef wchar_t __wchar_t; 254 #endif 255 #endif 256 257 __wchar_t WideCharacter; 258 ... 259 260Include File Checking Macros 261============================ 262 263Not all developments systems have the same include files. The 264:ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow 265you to check for the existence of an include file before doing a possibly 266failing ``#include`` directive. Include file checking macros must be used 267as expressions in ``#if`` or ``#elif`` preprocessing directives. 268 269.. _langext-__has_include: 270 271``__has_include`` 272----------------- 273 274This function-like macro takes a single file name string argument that is the 275name of an include file. It evaluates to 1 if the file can be found using the 276include paths, or 0 otherwise: 277 278.. code-block:: c++ 279 280 // Note the two possible file name string formats. 281 #if __has_include("myinclude.h") && __has_include(<stdint.h>) 282 # include "myinclude.h" 283 #endif 284 285To test for this feature, use ``#if defined(__has_include)``: 286 287.. code-block:: c++ 288 289 // To avoid problem with non-clang compilers not having this macro. 290 #if defined(__has_include) 291 #if __has_include("myinclude.h") 292 # include "myinclude.h" 293 #endif 294 #endif 295 296.. _langext-__has_include_next: 297 298``__has_include_next`` 299---------------------- 300 301This function-like macro takes a single file name string argument that is the 302name of an include file. It is like ``__has_include`` except that it looks for 303the second instance of the given file found in the include paths. It evaluates 304to 1 if the second instance of the file can be found using the include paths, 305or 0 otherwise: 306 307.. code-block:: c++ 308 309 // Note the two possible file name string formats. 310 #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>) 311 # include_next "myinclude.h" 312 #endif 313 314 // To avoid problem with non-clang compilers not having this macro. 315 #if defined(__has_include_next) 316 #if __has_include_next("myinclude.h") 317 # include_next "myinclude.h" 318 #endif 319 #endif 320 321Note that ``__has_include_next``, like the GNU extension ``#include_next`` 322directive, is intended for use in headers only, and will issue a warning if 323used in the top-level compilation file. A warning will also be issued if an 324absolute path is used in the file argument. 325 326``__has_warning`` 327----------------- 328 329This function-like macro takes a string literal that represents a command line 330option for a warning and returns true if that is a valid warning option. 331 332.. code-block:: c++ 333 334 #if __has_warning("-Wformat") 335 ... 336 #endif 337 338.. _languageextensions-builtin-macros: 339 340Builtin Macros 341============== 342 343``__BASE_FILE__`` 344 Defined to a string that contains the name of the main input file passed to 345 Clang. 346 347``__FILE_NAME__`` 348 Clang-specific extension that functions similar to ``__FILE__`` but only 349 renders the last path component (the filename) instead of an invocation 350 dependent full path to that file. 351 352``__COUNTER__`` 353 Defined to an integer value that starts at zero and is incremented each time 354 the ``__COUNTER__`` macro is expanded. 355 356``__INCLUDE_LEVEL__`` 357 Defined to an integral value that is the include depth of the file currently 358 being translated. For the main file, this value is zero. 359 360``__TIMESTAMP__`` 361 Defined to the date and time of the last modification of the current source 362 file. 363 364``__clang__`` 365 Defined when compiling with Clang 366 367``__clang_major__`` 368 Defined to the major marketing version number of Clang (e.g., the 2 in 369 2.0.1). Note that marketing version numbers should not be used to check for 370 language features, as different vendors use different numbering schemes. 371 Instead, use the :ref:`langext-feature_check`. 372 373``__clang_minor__`` 374 Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note 375 that marketing version numbers should not be used to check for language 376 features, as different vendors use different numbering schemes. Instead, use 377 the :ref:`langext-feature_check`. 378 379``__clang_patchlevel__`` 380 Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1). 381 382``__clang_version__`` 383 Defined to a string that captures the Clang marketing version, including the 384 Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``". 385 386``__clang_literal_encoding__`` 387 Defined to a narrow string literal that represents the current encoding of 388 narrow string literals, e.g., ``"hello"``. This macro typically expands to 389 "UTF-8" (but may change in the future if the 390 ``-fexec-charset="Encoding-Name"`` option is implemented.) 391 392``__clang_wide_literal_encoding__`` 393 Defined to a narrow string literal that represents the current encoding of 394 wide string literals, e.g., ``L"hello"``. This macro typically expands to 395 "UTF-16" or "UTF-32" (but may change in the future if the 396 ``-fwide-exec-charset="Encoding-Name"`` option is implemented.) 397 398.. _langext-vectors: 399 400Vectors and Extended Vectors 401============================ 402 403Supports the GCC, OpenCL, AltiVec and NEON vector extensions. 404 405OpenCL vector types are created using the ``ext_vector_type`` attribute. It 406supports the ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example 407is: 408 409.. code-block:: c++ 410 411 typedef float float4 __attribute__((ext_vector_type(4))); 412 typedef float float2 __attribute__((ext_vector_type(2))); 413 414 float4 foo(float2 a, float2 b) { 415 float4 c; 416 c.xz = a; 417 c.yw = b; 418 return c; 419 } 420 421Query for this feature with ``__has_attribute(ext_vector_type)``. 422 423Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax 424and functions. For example: 425 426.. code-block:: c++ 427 428 vector float foo(vector int a) { 429 vector int b; 430 b = vec_add(a, a) + a; 431 return (vector float)b; 432 } 433 434NEON vector types are created using ``neon_vector_type`` and 435``neon_polyvector_type`` attributes. For example: 436 437.. code-block:: c++ 438 439 typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t; 440 typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t; 441 442 int8x8_t foo(int8x8_t a) { 443 int8x8_t v; 444 v = a; 445 return v; 446 } 447 448Vector Literals 449--------------- 450 451Vector literals can be used to create vectors from a set of scalars, or 452vectors. Either parentheses or braces form can be used. In the parentheses 453form the number of literal values specified must be one, i.e. referring to a 454scalar value, or must match the size of the vector type being created. If a 455single scalar literal value is specified, the scalar literal value will be 456replicated to all the components of the vector type. In the brackets form any 457number of literals can be specified. For example: 458 459.. code-block:: c++ 460 461 typedef int v4si __attribute__((__vector_size__(16))); 462 typedef float float4 __attribute__((ext_vector_type(4))); 463 typedef float float2 __attribute__((ext_vector_type(2))); 464 465 v4si vsi = (v4si){1, 2, 3, 4}; 466 float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f); 467 vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1). 468 vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0). 469 vector int vi3 = (vector int)(1, 2); // error 470 vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0). 471 vector int vi5 = (vector int)(1, 2, 3, 4); 472 float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f)); 473 474Vector Operations 475----------------- 476 477The table below shows the support for each operation by vector extension. A 478dash indicates that an operation is not accepted according to a corresponding 479specification. 480 481============================== ======= ======= ============= ======= 482 Operator OpenCL AltiVec GCC NEON 483============================== ======= ======= ============= ======= 484[] yes yes yes -- 485unary operators +, -- yes yes yes -- 486++, -- -- yes yes yes -- 487+,--,*,/,% yes yes yes -- 488bitwise operators &,|,^,~ yes yes yes -- 489>>,<< yes yes yes -- 490!, &&, || yes -- yes -- 491==, !=, >, <, >=, <= yes yes yes -- 492= yes yes yes yes 493?: [#]_ yes -- yes -- 494sizeof yes yes yes yes 495C-style cast yes yes yes no 496reinterpret_cast yes no yes no 497static_cast yes no yes no 498const_cast no no no no 499============================== ======= ======= ============= ======= 500 501See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`. 502 503.. [#] ternary operator(?:) has different behaviors depending on condition 504 operand's vector type. If the condition is a GNU vector (i.e. __vector_size__), 505 it's only available in C++ and uses normal bool conversions (that is, != 0). 506 If it's an extension (OpenCL) vector, it's only available in C and OpenCL C. 507 And it selects base on signedness of the condition operands (OpenCL v1.1 s6.3.9). 508 509Vector Builtins 510--------------- 511 512**Note: The implementation of vector builtins is work-in-progress and incomplete.** 513 514In addition to the operators mentioned above, Clang provides a set of builtins 515to perform additional operations on certain scalar and vector types. 516 517Let ``T`` be one of the following types: 518 519* an integer type (as in C2x 6.2.5p19), but excluding enumerated types and _Bool 520* the standard floating types float or double 521* a half-precision floating point type, if one is supported on the target 522* a vector type. 523 524For scalar types, consider the operation applied to a vector with a single element. 525 526*Elementwise Builtins* 527 528Each builtin returns a vector equivalent to applying the specified operation 529elementwise to the input. 530 531Unless specified otherwise operation(±0) = ±0 and operation(±infinity) = ±infinity 532 533=========================================== ================================================================ ========================================= 534 Name Operation Supported element types 535=========================================== ================================================================ ========================================= 536 T __builtin_elementwise_abs(T x) return the absolute value of a number x; the absolute value of signed integer and floating point types 537 the most negative integer remains the most negative integer 538 T __builtin_elementwise_ceil(T x) return the smallest integral value greater than or equal to x floating point types 539 T __builtin_elementwise_floor(T x) return the largest integral value less than or equal to x floating point types 540 T __builtin_elementwise_roundeven(T x) round x to the nearest integer value in floating point format, floating point types 541 rounding halfway cases to even (that is, to the nearest value 542 that is an even integer), regardless of the current rounding 543 direction. 544 T__builtin_elementwise_trunc(T x) return the integral value nearest to but no larger in floating point types 545 magnitude than x 546 T __builtin_elementwise_max(T x, T y) return x or y, whichever is larger integer and floating point types 547 T __builtin_elementwise_min(T x, T y) return x or y, whichever is smaller integer and floating point types 548 T __builtin_elementwise_add_sat(T x, T y) return the sum of x and y, clamped to the range of integer types 549 representable values for the signed/unsigned integer type. 550 T __builtin_elementwise_sub_sat(T x, T y) return the difference of x and y, clamped to the range of integer types 551 representable values for the signed/unsigned integer type. 552=========================================== ================================================================ ========================================= 553 554 555*Reduction Builtins* 556 557Each builtin returns a scalar equivalent to applying the specified 558operation(x, y) as recursive even-odd pairwise reduction to all vector 559elements. ``operation(x, y)`` is repeatedly applied to each non-overlapping 560even-odd element pair with indices ``i * 2`` and ``i * 2 + 1`` with 561``i in [0, Number of elements / 2)``. If the numbers of elements is not a 562power of 2, the vector is widened with neutral elements for the reduction 563at the end to the next power of 2. 564 565Example: 566 567.. code-block:: c++ 568 569 __builtin_reduce_add([e3, e2, e1, e0]) = __builtin_reduced_add([e3 + e2, e1 + e0]) 570 = (e3 + e2) + (e1 + e0) 571 572 573Let ``VT`` be a vector type and ``ET`` the element type of ``VT``. 574 575======================================= ================================================================ ================================== 576 Name Operation Supported element types 577======================================= ================================================================ ================================== 578 ET __builtin_reduce_max(VT a) return x or y, whichever is larger; If exactly one argument is integer and floating point types 579 a NaN, return the other argument. If both arguments are NaNs, 580 fmax() return a NaN. 581 ET __builtin_reduce_min(VT a) return x or y, whichever is smaller; If exactly one argument integer and floating point types 582 is a NaN, return the other argument. If both arguments are 583 NaNs, fmax() return a NaN. 584 ET __builtin_reduce_add(VT a) \+ integer and floating point types 585 ET __builtin_reduce_and(VT a) & integer types 586 ET __builtin_reduce_or(VT a) \| integer types 587 ET __builtin_reduce_xor(VT a) ^ integer types 588======================================= ================================================================ ================================== 589 590Matrix Types 591============ 592 593Clang provides an extension for matrix types, which is currently being 594implemented. See :ref:`the draft specification <matrixtypes>` for more details. 595 596For example, the code below uses the matrix types extension to multiply two 4x4 597float matrices and add the result to a third 4x4 matrix. 598 599.. code-block:: c++ 600 601 typedef float m4x4_t __attribute__((matrix_type(4, 4))); 602 603 m4x4_t f(m4x4_t a, m4x4_t b, m4x4_t c) { 604 return a + b * c; 605 } 606 607The matrix type extension also supports operations on a matrix and a scalar. 608 609.. code-block:: c++ 610 611 typedef float m4x4_t __attribute__((matrix_type(4, 4))); 612 613 m4x4_t f(m4x4_t a) { 614 return (a + 23) * 12; 615 } 616 617The matrix type extension supports division on a matrix and a scalar but not on a matrix and a matrix. 618 619.. code-block:: c++ 620 621 typedef float m4x4_t __attribute__((matrix_type(4, 4))); 622 623 m4x4_t f(m4x4_t a) { 624 a = a / 3.0; 625 return a; 626 } 627 628The matrix type extension supports compound assignments for addition, subtraction, and multiplication on matrices 629and on a matrix and a scalar, provided their types are consistent. 630 631.. code-block:: c++ 632 633 typedef float m4x4_t __attribute__((matrix_type(4, 4))); 634 635 m4x4_t f(m4x4_t a, m4x4_t b) { 636 a += b; 637 a -= b; 638 a *= b; 639 a += 23; 640 a -= 12; 641 return a; 642 } 643 644The matrix type extension supports explicit casts. Implicit type conversion between matrix types is not allowed. 645 646.. code-block:: c++ 647 648 typedef int ix5x5 __attribute__((matrix_type(5, 5))); 649 typedef float fx5x5 __attribute__((matrix_type(5, 5))); 650 651 fx5x5 f1(ix5x5 i, fx5x5 f) { 652 return (fx5x5) i; 653 } 654 655 656 template <typename X> 657 using matrix_4_4 = X __attribute__((matrix_type(4, 4))); 658 659 void f2() { 660 matrix_5_5<double> d; 661 matrix_5_5<int> i; 662 i = (matrix_5_5<int>)d; 663 i = static_cast<matrix_5_5<int>>(d); 664 } 665 666Half-Precision Floating Point 667============================= 668 669Clang supports three half-precision (16-bit) floating point types: ``__fp16``, 670``_Float16`` and ``__bf16``. These types are supported in all language modes. 671 672``__fp16`` is supported on every target, as it is purely a storage format; see below. 673``_Float16`` is currently only supported on the following targets, with further 674targets pending ABI standardization: 675 676* 32-bit ARM 677* 64-bit ARM (AArch64) 678* AMDGPU 679* SPIR 680* X86 (Only available under feature AVX512-FP16) 681 682``_Float16`` will be supported on more targets as they define ABIs for it. 683 684``__bf16`` is purely a storage format; it is currently only supported on the following targets: 685* 32-bit ARM 686* 64-bit ARM (AArch64) 687 688The ``__bf16`` type is only available when supported in hardware. 689 690``__fp16`` is a storage and interchange format only. This means that values of 691``__fp16`` are immediately promoted to (at least) ``float`` when used in arithmetic 692operations, so that e.g. the result of adding two ``__fp16`` values has type ``float``. 693The 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>`_). 694Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``, not the ARM 695alternative format. 696 697``_Float16`` is an interchange floating-point type. This means that, just like arithmetic on 698``float`` or ``double``, arithmetic on ``_Float16`` operands is formally performed in the 699``_Float16`` type, so that e.g. the result of adding two ``_Float16`` values has type 700``_Float16``. The behavior of ``_Float16`` is specified by ISO/IEC TS 18661-3:2015 701("Floating-point extensions for C"). As with ``__fp16``, Clang uses the ``binary16`` 702format from IEEE 754-2008 for ``_Float16``. 703 704``_Float16`` arithmetic will be performed using native half-precision support 705when available on the target (e.g. on ARMv8.2a); otherwise it will be performed 706at a higher precision (currently always ``float``) and then truncated down to 707``_Float16``. Note that C and C++ allow intermediate floating-point operands 708of an expression to be computed with greater precision than is expressible in 709their type, so Clang may avoid intermediate truncations in certain cases; this may 710lead to results that are inconsistent with native arithmetic. 711 712It is recommended that portable code use ``_Float16`` instead of ``__fp16``, 713as it has been defined by the C standards committee and has behavior that is 714more familiar to most programmers. 715 716Because ``__fp16`` operands are always immediately promoted to ``float``, the 717common real type of ``__fp16`` and ``_Float16`` for the purposes of the usual 718arithmetic conversions is ``float``. 719 720A literal can be given ``_Float16`` type using the suffix ``f16``. For example, 721``3.14f16``. 722 723Because default argument promotion only applies to the standard floating-point 724types, ``_Float16`` values are not promoted to ``double`` when passed as variadic 725or untyped arguments. As a consequence, some caution must be taken when using 726certain library facilities with ``_Float16``; for example, there is no ``printf`` format 727specifier for ``_Float16``, and (unlike ``float``) it will not be implicitly promoted to 728``double`` when passed to ``printf``, so the programmer must explicitly cast it to 729``double`` before using it with an ``%f`` or similar specifier. 730 731Messages on ``deprecated`` and ``unavailable`` Attributes 732========================================================= 733 734An optional string message can be added to the ``deprecated`` and 735``unavailable`` attributes. For example: 736 737.. code-block:: c++ 738 739 void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!"))); 740 741If the deprecated or unavailable declaration is used, the message will be 742incorporated into the appropriate diagnostic: 743 744.. code-block:: none 745 746 harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!! 747 [-Wdeprecated-declarations] 748 explode(); 749 ^ 750 751Query for this feature with 752``__has_extension(attribute_deprecated_with_message)`` and 753``__has_extension(attribute_unavailable_with_message)``. 754 755Attributes on Enumerators 756========================= 757 758Clang allows attributes to be written on individual enumerators. This allows 759enumerators to be deprecated, made unavailable, etc. The attribute must appear 760after the enumerator name and before any initializer, like so: 761 762.. code-block:: c++ 763 764 enum OperationMode { 765 OM_Invalid, 766 OM_Normal, 767 OM_Terrified __attribute__((deprecated)), 768 OM_AbortOnError __attribute__((deprecated)) = 4 769 }; 770 771Attributes on the ``enum`` declaration do not apply to individual enumerators. 772 773Query for this feature with ``__has_extension(enumerator_attributes)``. 774 775C++11 Attributes on using-declarations 776====================================== 777 778Clang allows C++-style ``[[]]`` attributes to be written on using-declarations. 779For instance: 780 781.. code-block:: c++ 782 783 [[clang::using_if_exists]] using foo::bar; 784 using foo::baz [[clang::using_if_exists]]; 785 786You can test for support for this extension with 787``__has_extension(cxx_attributes_on_using_declarations)``. 788 789'User-Specified' System Frameworks 790================================== 791 792Clang provides a mechanism by which frameworks can be built in such a way that 793they will always be treated as being "system frameworks", even if they are not 794present in a system framework directory. This can be useful to system 795framework developers who want to be able to test building other applications 796with development builds of their framework, including the manner in which the 797compiler changes warning behavior for system headers. 798 799Framework developers can opt-in to this mechanism by creating a 800"``.system_framework``" file at the top-level of their framework. That is, the 801framework should have contents like: 802 803.. code-block:: none 804 805 .../TestFramework.framework 806 .../TestFramework.framework/.system_framework 807 .../TestFramework.framework/Headers 808 .../TestFramework.framework/Headers/TestFramework.h 809 ... 810 811Clang will treat the presence of this file as an indicator that the framework 812should be treated as a system framework, regardless of how it was found in the 813framework search path. For consistency, we recommend that such files never be 814included in installed versions of the framework. 815 816Checks for Standard Language Features 817===================================== 818 819The ``__has_feature`` macro can be used to query if certain standard language 820features are enabled. The ``__has_extension`` macro can be used to query if 821language features are available as an extension when compiling for a standard 822which does not provide them. The features which can be tested are listed here. 823 824Since Clang 3.4, the C++ SD-6 feature test macros are also supported. 825These are macros with names of the form ``__cpp_<feature_name>``, and are 826intended to be a portable way to query the supported features of the compiler. 827See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for 828information on the version of SD-6 supported by each Clang release, and the 829macros provided by that revision of the recommendations. 830 831C++98 832----- 833 834The features listed below are part of the C++98 standard. These features are 835enabled by default when compiling C++ code. 836 837C++ exceptions 838^^^^^^^^^^^^^^ 839 840Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been 841enabled. For example, compiling code with ``-fno-exceptions`` disables C++ 842exceptions. 843 844C++ RTTI 845^^^^^^^^ 846 847Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For 848example, compiling code with ``-fno-rtti`` disables the use of RTTI. 849 850C++11 851----- 852 853The features listed below are part of the C++11 standard. As a result, all 854these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option 855when compiling C++ code. 856 857C++11 SFINAE includes access control 858^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 859 860Use ``__has_feature(cxx_access_control_sfinae)`` or 861``__has_extension(cxx_access_control_sfinae)`` to determine whether 862access-control errors (e.g., calling a private constructor) are considered to 863be template argument deduction errors (aka SFINAE errors), per `C++ DR1170 864<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_. 865 866C++11 alias templates 867^^^^^^^^^^^^^^^^^^^^^ 868 869Use ``__has_feature(cxx_alias_templates)`` or 870``__has_extension(cxx_alias_templates)`` to determine if support for C++11's 871alias declarations and alias templates is enabled. 872 873C++11 alignment specifiers 874^^^^^^^^^^^^^^^^^^^^^^^^^^ 875 876Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to 877determine if support for alignment specifiers using ``alignas`` is enabled. 878 879Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to 880determine if support for the ``alignof`` keyword is enabled. 881 882C++11 attributes 883^^^^^^^^^^^^^^^^ 884 885Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to 886determine if support for attribute parsing with C++11's square bracket notation 887is enabled. 888 889C++11 generalized constant expressions 890^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 891 892Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized 893constant expressions (e.g., ``constexpr``) is enabled. 894 895C++11 ``decltype()`` 896^^^^^^^^^^^^^^^^^^^^ 897 898Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to 899determine if support for the ``decltype()`` specifier is enabled. C++11's 900``decltype`` does not require type-completeness of a function call expression. 901Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or 902``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if 903support for this feature is enabled. 904 905C++11 default template arguments in function templates 906^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 907 908Use ``__has_feature(cxx_default_function_template_args)`` or 909``__has_extension(cxx_default_function_template_args)`` to determine if support 910for default template arguments in function templates is enabled. 911 912C++11 ``default``\ ed functions 913^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 914 915Use ``__has_feature(cxx_defaulted_functions)`` or 916``__has_extension(cxx_defaulted_functions)`` to determine if support for 917defaulted function definitions (with ``= default``) is enabled. 918 919C++11 delegating constructors 920^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 921 922Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for 923delegating constructors is enabled. 924 925C++11 ``deleted`` functions 926^^^^^^^^^^^^^^^^^^^^^^^^^^^ 927 928Use ``__has_feature(cxx_deleted_functions)`` or 929``__has_extension(cxx_deleted_functions)`` to determine if support for deleted 930function definitions (with ``= delete``) is enabled. 931 932C++11 explicit conversion functions 933^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 934 935Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for 936``explicit`` conversion functions is enabled. 937 938C++11 generalized initializers 939^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 940 941Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for 942generalized initializers (using braced lists and ``std::initializer_list``) is 943enabled. 944 945C++11 implicit move constructors/assignment operators 946^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 947 948Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly 949generate move constructors and move assignment operators where needed. 950 951C++11 inheriting constructors 952^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 953 954Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for 955inheriting constructors is enabled. 956 957C++11 inline namespaces 958^^^^^^^^^^^^^^^^^^^^^^^ 959 960Use ``__has_feature(cxx_inline_namespaces)`` or 961``__has_extension(cxx_inline_namespaces)`` to determine if support for inline 962namespaces is enabled. 963 964C++11 lambdas 965^^^^^^^^^^^^^ 966 967Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to 968determine if support for lambdas is enabled. 969 970C++11 local and unnamed types as template arguments 971^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 972 973Use ``__has_feature(cxx_local_type_template_args)`` or 974``__has_extension(cxx_local_type_template_args)`` to determine if support for 975local and unnamed types as template arguments is enabled. 976 977C++11 noexcept 978^^^^^^^^^^^^^^ 979 980Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to 981determine if support for noexcept exception specifications is enabled. 982 983C++11 in-class non-static data member initialization 984^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 985 986Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class 987initialization of non-static data members is enabled. 988 989C++11 ``nullptr`` 990^^^^^^^^^^^^^^^^^ 991 992Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to 993determine if support for ``nullptr`` is enabled. 994 995C++11 ``override control`` 996^^^^^^^^^^^^^^^^^^^^^^^^^^ 997 998Use ``__has_feature(cxx_override_control)`` or 999``__has_extension(cxx_override_control)`` to determine if support for the 1000override control keywords is enabled. 1001 1002C++11 reference-qualified functions 1003^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1004 1005Use ``__has_feature(cxx_reference_qualified_functions)`` or 1006``__has_extension(cxx_reference_qualified_functions)`` to determine if support 1007for reference-qualified functions (e.g., member functions with ``&`` or ``&&`` 1008applied to ``*this``) is enabled. 1009 1010C++11 range-based ``for`` loop 1011^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1012 1013Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to 1014determine if support for the range-based for loop is enabled. 1015 1016C++11 raw string literals 1017^^^^^^^^^^^^^^^^^^^^^^^^^ 1018 1019Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw 1020string literals (e.g., ``R"x(foo\bar)x"``) is enabled. 1021 1022C++11 rvalue references 1023^^^^^^^^^^^^^^^^^^^^^^^ 1024 1025Use ``__has_feature(cxx_rvalue_references)`` or 1026``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue 1027references is enabled. 1028 1029C++11 ``static_assert()`` 1030^^^^^^^^^^^^^^^^^^^^^^^^^ 1031 1032Use ``__has_feature(cxx_static_assert)`` or 1033``__has_extension(cxx_static_assert)`` to determine if support for compile-time 1034assertions using ``static_assert`` is enabled. 1035 1036C++11 ``thread_local`` 1037^^^^^^^^^^^^^^^^^^^^^^ 1038 1039Use ``__has_feature(cxx_thread_local)`` to determine if support for 1040``thread_local`` variables is enabled. 1041 1042C++11 type inference 1043^^^^^^^^^^^^^^^^^^^^ 1044 1045Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to 1046determine C++11 type inference is supported using the ``auto`` specifier. If 1047this is disabled, ``auto`` will instead be a storage class specifier, as in C 1048or C++98. 1049 1050C++11 strongly typed enumerations 1051^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1052 1053Use ``__has_feature(cxx_strong_enums)`` or 1054``__has_extension(cxx_strong_enums)`` to determine if support for strongly 1055typed, scoped enumerations is enabled. 1056 1057C++11 trailing return type 1058^^^^^^^^^^^^^^^^^^^^^^^^^^ 1059 1060Use ``__has_feature(cxx_trailing_return)`` or 1061``__has_extension(cxx_trailing_return)`` to determine if support for the 1062alternate function declaration syntax with trailing return type is enabled. 1063 1064C++11 Unicode string literals 1065^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1066 1067Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode 1068string literals is enabled. 1069 1070C++11 unrestricted unions 1071^^^^^^^^^^^^^^^^^^^^^^^^^ 1072 1073Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for 1074unrestricted unions is enabled. 1075 1076C++11 user-defined literals 1077^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1078 1079Use ``__has_feature(cxx_user_literals)`` to determine if support for 1080user-defined literals is enabled. 1081 1082C++11 variadic templates 1083^^^^^^^^^^^^^^^^^^^^^^^^ 1084 1085Use ``__has_feature(cxx_variadic_templates)`` or 1086``__has_extension(cxx_variadic_templates)`` to determine if support for 1087variadic templates is enabled. 1088 1089C++14 1090----- 1091 1092The features listed below are part of the C++14 standard. As a result, all 1093these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option 1094when compiling C++ code. 1095 1096C++14 binary literals 1097^^^^^^^^^^^^^^^^^^^^^ 1098 1099Use ``__has_feature(cxx_binary_literals)`` or 1100``__has_extension(cxx_binary_literals)`` to determine whether 1101binary literals (for instance, ``0b10010``) are recognized. Clang supports this 1102feature as an extension in all language modes. 1103 1104C++14 contextual conversions 1105^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1106 1107Use ``__has_feature(cxx_contextual_conversions)`` or 1108``__has_extension(cxx_contextual_conversions)`` to determine if the C++14 rules 1109are used when performing an implicit conversion for an array bound in a 1110*new-expression*, the operand of a *delete-expression*, an integral constant 1111expression, or a condition in a ``switch`` statement. 1112 1113C++14 decltype(auto) 1114^^^^^^^^^^^^^^^^^^^^ 1115 1116Use ``__has_feature(cxx_decltype_auto)`` or 1117``__has_extension(cxx_decltype_auto)`` to determine if support 1118for the ``decltype(auto)`` placeholder type is enabled. 1119 1120C++14 default initializers for aggregates 1121^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1122 1123Use ``__has_feature(cxx_aggregate_nsdmi)`` or 1124``__has_extension(cxx_aggregate_nsdmi)`` to determine if support 1125for default initializers in aggregate members is enabled. 1126 1127C++14 digit separators 1128^^^^^^^^^^^^^^^^^^^^^^ 1129 1130Use ``__cpp_digit_separators`` to determine if support for digit separators 1131using single quotes (for instance, ``10'000``) is enabled. At this time, there 1132is no corresponding ``__has_feature`` name 1133 1134C++14 generalized lambda capture 1135^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1136 1137Use ``__has_feature(cxx_init_captures)`` or 1138``__has_extension(cxx_init_captures)`` to determine if support for 1139lambda captures with explicit initializers is enabled 1140(for instance, ``[n(0)] { return ++n; }``). 1141 1142C++14 generic lambdas 1143^^^^^^^^^^^^^^^^^^^^^ 1144 1145Use ``__has_feature(cxx_generic_lambdas)`` or 1146``__has_extension(cxx_generic_lambdas)`` to determine if support for generic 1147(polymorphic) lambdas is enabled 1148(for instance, ``[] (auto x) { return x + 1; }``). 1149 1150C++14 relaxed constexpr 1151^^^^^^^^^^^^^^^^^^^^^^^ 1152 1153Use ``__has_feature(cxx_relaxed_constexpr)`` or 1154``__has_extension(cxx_relaxed_constexpr)`` to determine if variable 1155declarations, local variable modification, and control flow constructs 1156are permitted in ``constexpr`` functions. 1157 1158C++14 return type deduction 1159^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1160 1161Use ``__has_feature(cxx_return_type_deduction)`` or 1162``__has_extension(cxx_return_type_deduction)`` to determine if support 1163for return type deduction for functions (using ``auto`` as a return type) 1164is enabled. 1165 1166C++14 runtime-sized arrays 1167^^^^^^^^^^^^^^^^^^^^^^^^^^ 1168 1169Use ``__has_feature(cxx_runtime_array)`` or 1170``__has_extension(cxx_runtime_array)`` to determine if support 1171for arrays of runtime bound (a restricted form of variable-length arrays) 1172is enabled. 1173Clang's implementation of this feature is incomplete. 1174 1175C++14 variable templates 1176^^^^^^^^^^^^^^^^^^^^^^^^ 1177 1178Use ``__has_feature(cxx_variable_templates)`` or 1179``__has_extension(cxx_variable_templates)`` to determine if support for 1180templated variable declarations is enabled. 1181 1182C11 1183--- 1184 1185The features listed below are part of the C11 standard. As a result, all these 1186features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when 1187compiling C code. Additionally, because these features are all 1188backward-compatible, they are available as extensions in all language modes. 1189 1190C11 alignment specifiers 1191^^^^^^^^^^^^^^^^^^^^^^^^ 1192 1193Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine 1194if support for alignment specifiers using ``_Alignas`` is enabled. 1195 1196Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine 1197if support for the ``_Alignof`` keyword is enabled. 1198 1199C11 atomic operations 1200^^^^^^^^^^^^^^^^^^^^^ 1201 1202Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine 1203if support for atomic types using ``_Atomic`` is enabled. Clang also provides 1204:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement 1205the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use 1206``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header 1207is available. 1208 1209Clang will use the system's ``<stdatomic.h>`` header when one is available, and 1210will otherwise use its own. When using its own, implementations of the atomic 1211operations are provided as macros. In the cases where C11 also requires a real 1212function, this header provides only the declaration of that function (along 1213with a shadowing macro implementation), and you must link to a library which 1214provides a definition of the function if you use it instead of the macro. 1215 1216C11 generic selections 1217^^^^^^^^^^^^^^^^^^^^^^ 1218 1219Use ``__has_feature(c_generic_selections)`` or 1220``__has_extension(c_generic_selections)`` to determine if support for generic 1221selections is enabled. 1222 1223As an extension, the C11 generic selection expression is available in all 1224languages supported by Clang. The syntax is the same as that given in the C11 1225standard. 1226 1227In C, type compatibility is decided according to the rules given in the 1228appropriate standard, but in C++, which lacks the type compatibility rules used 1229in C, types are considered compatible only if they are equivalent. 1230 1231C11 ``_Static_assert()`` 1232^^^^^^^^^^^^^^^^^^^^^^^^ 1233 1234Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)`` 1235to determine if support for compile-time assertions using ``_Static_assert`` is 1236enabled. 1237 1238C11 ``_Thread_local`` 1239^^^^^^^^^^^^^^^^^^^^^ 1240 1241Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)`` 1242to determine if support for ``_Thread_local`` variables is enabled. 1243 1244Modules 1245------- 1246 1247Use ``__has_feature(modules)`` to determine if Modules have been enabled. 1248For example, compiling code with ``-fmodules`` enables the use of Modules. 1249 1250More information could be found `here <https://clang.llvm.org/docs/Modules.html>`_. 1251 1252Type Trait Primitives 1253===================== 1254 1255Type trait primitives are special builtin constant expressions that can be used 1256by the standard C++ library to facilitate or simplify the implementation of 1257user-facing type traits in the <type_traits> header. 1258 1259They are not intended to be used directly by user code because they are 1260implementation-defined and subject to change -- as such they're tied closely to 1261the supported set of system headers, currently: 1262 1263* LLVM's own libc++ 1264* GNU libstdc++ 1265* The Microsoft standard C++ library 1266 1267Clang supports the `GNU C++ type traits 1268<https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the 1269`Microsoft Visual C++ type traits 1270<https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_, 1271as well as nearly all of the 1272`Embarcadero C++ type traits 1273<http://docwiki.embarcadero.com/RADStudio/Rio/en/Type_Trait_Functions_(C%2B%2B11)_Index>`_. 1274 1275The following type trait primitives are supported by Clang. Those traits marked 1276(C++) provide implementations for type traits specified by the C++ standard; 1277``__X(...)`` has the same semantics and constraints as the corresponding 1278``std::X_t<...>`` or ``std::X_v<...>`` type trait. 1279 1280* ``__array_rank(type)`` (Embarcadero): 1281 Returns the number of levels of array in the type ``type``: 1282 ``0`` if ``type`` is not an array type, and 1283 ``__array_rank(element) + 1`` if ``type`` is an array of ``element``. 1284* ``__array_extent(type, dim)`` (Embarcadero): 1285 The ``dim``'th array bound in the type ``type``, or ``0`` if 1286 ``dim >= __array_rank(type)``. 1287* ``__has_nothrow_assign`` (GNU, Microsoft, Embarcadero): 1288 Deprecated, use ``__is_nothrow_assignable`` instead. 1289* ``__has_nothrow_move_assign`` (GNU, Microsoft): 1290 Deprecated, use ``__is_nothrow_assignable`` instead. 1291* ``__has_nothrow_copy`` (GNU, Microsoft): 1292 Deprecated, use ``__is_nothrow_constructible`` instead. 1293* ``__has_nothrow_constructor`` (GNU, Microsoft): 1294 Deprecated, use ``__is_nothrow_constructible`` instead. 1295* ``__has_trivial_assign`` (GNU, Microsoft, Embarcadero): 1296 Deprecated, use ``__is_trivially_assignable`` instead. 1297* ``__has_trivial_move_assign`` (GNU, Microsoft): 1298 Deprecated, use ``__is_trivially_assignable`` instead. 1299* ``__has_trivial_copy`` (GNU, Microsoft): 1300 Deprecated, use ``__is_trivially_constructible`` instead. 1301* ``__has_trivial_constructor`` (GNU, Microsoft): 1302 Deprecated, use ``__is_trivially_constructible`` instead. 1303* ``__has_trivial_move_constructor`` (GNU, Microsoft): 1304 Deprecated, use ``__is_trivially_constructible`` instead. 1305* ``__has_trivial_destructor`` (GNU, Microsoft, Embarcadero): 1306 Deprecated, use ``__is_trivially_destructible`` instead. 1307* ``__has_unique_object_representations`` (C++, GNU) 1308* ``__has_virtual_destructor`` (C++, GNU, Microsoft, Embarcadero) 1309* ``__is_abstract`` (C++, GNU, Microsoft, Embarcadero) 1310* ``__is_aggregate`` (C++, GNU, Microsoft) 1311* ``__is_arithmetic`` (C++, Embarcadero) 1312* ``__is_array`` (C++, Embarcadero) 1313* ``__is_assignable`` (C++, MSVC 2015) 1314* ``__is_base_of`` (C++, GNU, Microsoft, Embarcadero) 1315* ``__is_class`` (C++, GNU, Microsoft, Embarcadero) 1316* ``__is_complete_type(type)`` (Embarcadero): 1317 Return ``true`` if ``type`` is a complete type. 1318 Warning: this trait is dangerous because it can return different values at 1319 different points in the same program. 1320* ``__is_compound`` (C++, Embarcadero) 1321* ``__is_const`` (C++, Embarcadero) 1322* ``__is_constructible`` (C++, MSVC 2013) 1323* ``__is_convertible`` (C++, Embarcadero) 1324* ``__is_convertible_to`` (Microsoft): 1325 Synonym for ``__is_convertible``. 1326* ``__is_destructible`` (C++, MSVC 2013): 1327 Only available in ``-fms-extensions`` mode. 1328* ``__is_empty`` (C++, GNU, Microsoft, Embarcadero) 1329* ``__is_enum`` (C++, GNU, Microsoft, Embarcadero) 1330* ``__is_final`` (C++, GNU, Microsoft) 1331* ``__is_floating_point`` (C++, Embarcadero) 1332* ``__is_function`` (C++, Embarcadero) 1333* ``__is_fundamental`` (C++, Embarcadero) 1334* ``__is_integral`` (C++, Embarcadero) 1335* ``__is_interface_class`` (Microsoft): 1336 Returns ``false``, even for types defined with ``__interface``. 1337* ``__is_literal`` (Clang): 1338 Synonym for ``__is_literal_type``. 1339* ``__is_literal_type`` (C++, GNU, Microsoft): 1340 Note, the corresponding standard trait was deprecated in C++17 1341 and removed in C++20. 1342* ``__is_lvalue_reference`` (C++, Embarcadero) 1343* ``__is_member_object_pointer`` (C++, Embarcadero) 1344* ``__is_member_function_pointer`` (C++, Embarcadero) 1345* ``__is_member_pointer`` (C++, Embarcadero) 1346* ``__is_nothrow_assignable`` (C++, MSVC 2013) 1347* ``__is_nothrow_constructible`` (C++, MSVC 2013) 1348* ``__is_nothrow_destructible`` (C++, MSVC 2013) 1349 Only available in ``-fms-extensions`` mode. 1350* ``__is_object`` (C++, Embarcadero) 1351* ``__is_pod`` (C++, GNU, Microsoft, Embarcadero): 1352 Note, the corresponding standard trait was deprecated in C++20. 1353* ``__is_pointer`` (C++, Embarcadero) 1354* ``__is_polymorphic`` (C++, GNU, Microsoft, Embarcadero) 1355* ``__is_reference`` (C++, Embarcadero) 1356* ``__is_rvalue_reference`` (C++, Embarcadero) 1357* ``__is_same`` (C++, Embarcadero) 1358* ``__is_same_as`` (GCC): Synonym for ``__is_same``. 1359* ``__is_scalar`` (C++, Embarcadero) 1360* ``__is_sealed`` (Microsoft): 1361 Synonym for ``__is_final``. 1362* ``__is_signed`` (C++, Embarcadero): 1363 Returns false for enumeration types, and returns true for floating-point 1364 types. Note, before Clang 10, returned true for enumeration types if the 1365 underlying type was signed, and returned false for floating-point types. 1366* ``__is_standard_layout`` (C++, GNU, Microsoft, Embarcadero) 1367* ``__is_trivial`` (C++, GNU, Microsoft, Embarcadero) 1368* ``__is_trivially_assignable`` (C++, GNU, Microsoft) 1369* ``__is_trivially_constructible`` (C++, GNU, Microsoft) 1370* ``__is_trivially_copyable`` (C++, GNU, Microsoft) 1371* ``__is_trivially_destructible`` (C++, MSVC 2013) 1372* ``__is_trivially_relocatable`` (Clang): Returns true if moving an object 1373 of the given type, and then destroying the source object, is known to be 1374 functionally equivalent to copying the underlying bytes and then dropping the 1375 source object on the floor. This is true of trivial types and types which 1376 were made trivially relocatable via the ``clang::trivial_abi`` attribute. 1377* ``__is_union`` (C++, GNU, Microsoft, Embarcadero) 1378* ``__is_unsigned`` (C++, Embarcadero): 1379 Returns false for enumeration types. Note, before Clang 13, returned true for 1380 enumeration types if the underlying type was unsigned. 1381* ``__is_void`` (C++, Embarcadero) 1382* ``__is_volatile`` (C++, Embarcadero) 1383* ``__reference_binds_to_temporary(T, U)`` (Clang): Determines whether a 1384 reference of type ``T`` bound to an expression of type ``U`` would bind to a 1385 materialized temporary object. If ``T`` is not a reference type the result 1386 is false. Note this trait will also return false when the initialization of 1387 ``T`` from ``U`` is ill-formed. 1388* ``__underlying_type`` (C++, GNU, Microsoft) 1389 1390In addition, the following expression traits are supported: 1391 1392* ``__is_lvalue_expr(e)`` (Embarcadero): 1393 Returns true if ``e`` is an lvalue expression. 1394 Deprecated, use ``__is_lvalue_reference(decltype((e)))`` instead. 1395* ``__is_rvalue_expr(e)`` (Embarcadero): 1396 Returns true if ``e`` is a prvalue expression. 1397 Deprecated, use ``!__is_reference(decltype((e)))`` instead. 1398 1399There are multiple ways to detect support for a type trait ``__X`` in the 1400compiler, depending on the oldest version of Clang you wish to support. 1401 1402* From Clang 10 onwards, ``__has_builtin(__X)`` can be used. 1403* From Clang 6 onwards, ``!__is_identifier(__X)`` can be used. 1404* From Clang 3 onwards, ``__has_feature(X)`` can be used, but only supports 1405 the following traits: 1406 1407 * ``__has_nothrow_assign`` 1408 * ``__has_nothrow_copy`` 1409 * ``__has_nothrow_constructor`` 1410 * ``__has_trivial_assign`` 1411 * ``__has_trivial_copy`` 1412 * ``__has_trivial_constructor`` 1413 * ``__has_trivial_destructor`` 1414 * ``__has_virtual_destructor`` 1415 * ``__is_abstract`` 1416 * ``__is_base_of`` 1417 * ``__is_class`` 1418 * ``__is_constructible`` 1419 * ``__is_convertible_to`` 1420 * ``__is_empty`` 1421 * ``__is_enum`` 1422 * ``__is_final`` 1423 * ``__is_literal`` 1424 * ``__is_standard_layout`` 1425 * ``__is_pod`` 1426 * ``__is_polymorphic`` 1427 * ``__is_sealed`` 1428 * ``__is_trivial`` 1429 * ``__is_trivially_assignable`` 1430 * ``__is_trivially_constructible`` 1431 * ``__is_trivially_copyable`` 1432 * ``__is_union`` 1433 * ``__underlying_type`` 1434 1435A simplistic usage example as might be seen in standard C++ headers follows: 1436 1437.. code-block:: c++ 1438 1439 #if __has_builtin(__is_convertible_to) 1440 template<typename From, typename To> 1441 struct is_convertible_to { 1442 static const bool value = __is_convertible_to(From, To); 1443 }; 1444 #else 1445 // Emulate type trait for compatibility with other compilers. 1446 #endif 1447 1448Blocks 1449====== 1450 1451The syntax and high level language feature description is in 1452:doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for 1453the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`. 1454 1455Query for this feature with ``__has_extension(blocks)``. 1456 1457ASM Goto with Output Constraints 1458================================ 1459 1460In addition to the functionality provided by `GCC's extended 1461assembly <https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html>`_, clang 1462supports output constraints with the `goto` form. 1463 1464The goto form of GCC's extended assembly allows the programmer to branch to a C 1465label from within an inline assembly block. Clang extends this behavior by 1466allowing the programmer to use output constraints: 1467 1468.. code-block:: c++ 1469 1470 int foo(int x) { 1471 int y; 1472 asm goto("# %0 %1 %l2" : "=r"(y) : "r"(x) : : err); 1473 return y; 1474 err: 1475 return -1; 1476 } 1477 1478It's important to note that outputs are valid only on the "fallthrough" branch. 1479Using outputs on an indirect branch may result in undefined behavior. For 1480example, in the function above, use of the value assigned to `y` in the `err` 1481block is undefined behavior. 1482 1483When using tied-outputs (i.e. outputs that are inputs and outputs, not just 1484outputs) with the `+r` constraint, there is a hidden input that's created 1485before the label, so numeric references to operands must account for that. 1486 1487.. code-block:: c++ 1488 1489 int foo(int x) { 1490 // %0 and %1 both refer to x 1491 // %l2 refers to err 1492 asm goto("# %0 %1 %l2" : "+r"(x) : : : err); 1493 return x; 1494 err: 1495 return -1; 1496 } 1497 1498This was changed to match GCC in clang-13; for better portability, symbolic 1499references can be used instead of numeric references. 1500 1501.. code-block:: c++ 1502 1503 int foo(int x) { 1504 asm goto("# %[x] %l[err]" : [x]"+r"(x) : : : err); 1505 return x; 1506 err: 1507 return -1; 1508 } 1509 1510Query for this feature with ``__has_extension(gnu_asm_goto_with_outputs)``. 1511 1512Objective-C Features 1513==================== 1514 1515Related result types 1516-------------------- 1517 1518According to Cocoa conventions, Objective-C methods with certain names 1519("``init``", "``alloc``", etc.) always return objects that are an instance of 1520the receiving class's type. Such methods are said to have a "related result 1521type", meaning that a message send to one of these methods will have the same 1522static type as an instance of the receiver class. For example, given the 1523following classes: 1524 1525.. code-block:: objc 1526 1527 @interface NSObject 1528 + (id)alloc; 1529 - (id)init; 1530 @end 1531 1532 @interface NSArray : NSObject 1533 @end 1534 1535and this common initialization pattern 1536 1537.. code-block:: objc 1538 1539 NSArray *array = [[NSArray alloc] init]; 1540 1541the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because 1542``alloc`` implicitly has a related result type. Similarly, the type of the 1543expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a 1544related result type and its receiver is known to have the type ``NSArray *``. 1545If neither ``alloc`` nor ``init`` had a related result type, the expressions 1546would have had type ``id``, as declared in the method signature. 1547 1548A method with a related result type can be declared by using the type 1549``instancetype`` as its result type. ``instancetype`` is a contextual keyword 1550that is only permitted in the result type of an Objective-C method, e.g. 1551 1552.. code-block:: objc 1553 1554 @interface A 1555 + (instancetype)constructAnA; 1556 @end 1557 1558The related result type can also be inferred for some methods. To determine 1559whether a method has an inferred related result type, the first word in the 1560camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered, 1561and the method will have a related result type if its return type is compatible 1562with the type of its class and if: 1563 1564* the first word is "``alloc``" or "``new``", and the method is a class method, 1565 or 1566 1567* the first word is "``autorelease``", "``init``", "``retain``", or "``self``", 1568 and the method is an instance method. 1569 1570If a method with a related result type is overridden by a subclass method, the 1571subclass method must also return a type that is compatible with the subclass 1572type. For example: 1573 1574.. code-block:: objc 1575 1576 @interface NSString : NSObject 1577 - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString 1578 @end 1579 1580Related result types only affect the type of a message send or property access 1581via the given method. In all other respects, a method with a related result 1582type is treated the same way as method that returns ``id``. 1583 1584Use ``__has_feature(objc_instancetype)`` to determine whether the 1585``instancetype`` contextual keyword is available. 1586 1587Automatic reference counting 1588---------------------------- 1589 1590Clang provides support for :doc:`automated reference counting 1591<AutomaticReferenceCounting>` in Objective-C, which eliminates the need 1592for manual ``retain``/``release``/``autorelease`` message sends. There are three 1593feature macros associated with automatic reference counting: 1594``__has_feature(objc_arc)`` indicates the availability of automated reference 1595counting in general, while ``__has_feature(objc_arc_weak)`` indicates that 1596automated reference counting also includes support for ``__weak`` pointers to 1597Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs 1598are allowed to have fields that are pointers to Objective-C objects managed by 1599automatic reference counting. 1600 1601.. _objc-weak: 1602 1603Weak references 1604--------------- 1605 1606Clang supports ARC-style weak and unsafe references in Objective-C even 1607outside of ARC mode. Weak references must be explicitly enabled with 1608the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))`` 1609to test whether they are enabled. Unsafe references are enabled 1610unconditionally. ARC-style weak and unsafe references cannot be used 1611when Objective-C garbage collection is enabled. 1612 1613Except as noted below, the language rules for the ``__weak`` and 1614``__unsafe_unretained`` qualifiers (and the ``weak`` and 1615``unsafe_unretained`` property attributes) are just as laid out 1616in the :doc:`ARC specification <AutomaticReferenceCounting>`. 1617In particular, note that some classes do not support forming weak 1618references to their instances, and note that special care must be 1619taken when storing weak references in memory where initialization 1620and deinitialization are outside the responsibility of the compiler 1621(such as in ``malloc``-ed memory). 1622 1623Loading from a ``__weak`` variable always implicitly retains the 1624loaded value. In non-ARC modes, this retain is normally balanced 1625by an implicit autorelease. This autorelease can be suppressed 1626by performing the load in the receiver position of a ``-retain`` 1627message send (e.g. ``[weakReference retain]``); note that this performs 1628only a single retain (the retain done when primitively loading from 1629the weak reference). 1630 1631For the most part, ``__unsafe_unretained`` in non-ARC modes is just the 1632default behavior of variables and therefore is not needed. However, 1633it does have an effect on the semantics of block captures: normally, 1634copying a block which captures an Objective-C object or block pointer 1635causes the captured pointer to be retained or copied, respectively, 1636but that behavior is suppressed when the captured variable is qualified 1637with ``__unsafe_unretained``. 1638 1639Note that the ``__weak`` qualifier formerly meant the GC qualifier in 1640all non-ARC modes and was silently ignored outside of GC modes. It now 1641means the ARC-style qualifier in all non-GC modes and is no longer 1642allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``. 1643It is expected that ``-fobjc-weak`` will eventually be enabled by default 1644in all non-GC Objective-C modes. 1645 1646.. _objc-fixed-enum: 1647 1648Enumerations with a fixed underlying type 1649----------------------------------------- 1650 1651Clang provides support for C++11 enumerations with a fixed underlying type 1652within Objective-C. For example, one can write an enumeration type as: 1653 1654.. code-block:: c++ 1655 1656 typedef enum : unsigned char { Red, Green, Blue } Color; 1657 1658This specifies that the underlying type, which is used to store the enumeration 1659value, is ``unsigned char``. 1660 1661Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed 1662underlying types is available in Objective-C. 1663 1664Interoperability with C++11 lambdas 1665----------------------------------- 1666 1667Clang provides interoperability between C++11 lambdas and blocks-based APIs, by 1668permitting a lambda to be implicitly converted to a block pointer with the 1669corresponding signature. For example, consider an API such as ``NSArray``'s 1670array-sorting method: 1671 1672.. code-block:: objc 1673 1674 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr; 1675 1676``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult 1677(^)(id, id)``, and parameters of this type are generally provided with block 1678literals as arguments. However, one can also use a C++11 lambda so long as it 1679provides the same signature (in this case, accepting two parameters of type 1680``id`` and returning an ``NSComparisonResult``): 1681 1682.. code-block:: objc 1683 1684 NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11", 1685 @"String 02"]; 1686 const NSStringCompareOptions comparisonOptions 1687 = NSCaseInsensitiveSearch | NSNumericSearch | 1688 NSWidthInsensitiveSearch | NSForcedOrderingSearch; 1689 NSLocale *currentLocale = [NSLocale currentLocale]; 1690 NSArray *sorted 1691 = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult { 1692 NSRange string1Range = NSMakeRange(0, [s1 length]); 1693 return [s1 compare:s2 options:comparisonOptions 1694 range:string1Range locale:currentLocale]; 1695 }]; 1696 NSLog(@"sorted: %@", sorted); 1697 1698This code relies on an implicit conversion from the type of the lambda 1699expression (an unnamed, local class type called the *closure type*) to the 1700corresponding block pointer type. The conversion itself is expressed by a 1701conversion operator in that closure type that produces a block pointer with the 1702same signature as the lambda itself, e.g., 1703 1704.. code-block:: objc 1705 1706 operator NSComparisonResult (^)(id, id)() const; 1707 1708This conversion function returns a new block that simply forwards the two 1709parameters to the lambda object (which it captures by copy), then returns the 1710result. The returned block is first copied (with ``Block_copy``) and then 1711autoreleased. As an optimization, if a lambda expression is immediately 1712converted to a block pointer (as in the first example, above), then the block 1713is not copied and autoreleased: rather, it is given the same lifetime as a 1714block literal written at that point in the program, which avoids the overhead 1715of copying a block to the heap in the common case. 1716 1717The conversion from a lambda to a block pointer is only available in 1718Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory 1719management (autorelease). 1720 1721Object Literals and Subscripting 1722-------------------------------- 1723 1724Clang provides support for :doc:`Object Literals and Subscripting 1725<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C 1726programming patterns, makes programs more concise, and improves the safety of 1727container creation. There are several feature macros associated with object 1728literals and subscripting: ``__has_feature(objc_array_literals)`` tests the 1729availability of array literals; ``__has_feature(objc_dictionary_literals)`` 1730tests the availability of dictionary literals; 1731``__has_feature(objc_subscripting)`` tests the availability of object 1732subscripting. 1733 1734Objective-C Autosynthesis of Properties 1735--------------------------------------- 1736 1737Clang provides support for autosynthesis of declared properties. Using this 1738feature, clang provides default synthesis of those properties not declared 1739@dynamic and not having user provided backing getter and setter methods. 1740``__has_feature(objc_default_synthesize_properties)`` checks for availability 1741of this feature in version of clang being used. 1742 1743.. _langext-objc-retain-release: 1744 1745Objective-C retaining behavior attributes 1746----------------------------------------- 1747 1748In Objective-C, functions and methods are generally assumed to follow the 1749`Cocoa Memory Management 1750<https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_ 1751conventions for ownership of object arguments and 1752return values. However, there are exceptions, and so Clang provides attributes 1753to allow these exceptions to be documented. This are used by ARC and the 1754`static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be 1755better described using the ``objc_method_family`` attribute instead. 1756 1757**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``, 1758``ns_returns_autoreleased``, ``cf_returns_retained``, and 1759``cf_returns_not_retained`` attributes can be placed on methods and functions 1760that return Objective-C or CoreFoundation objects. They are commonly placed at 1761the end of a function prototype or method declaration: 1762 1763.. code-block:: objc 1764 1765 id foo() __attribute__((ns_returns_retained)); 1766 1767 - (NSString *)bar:(int)x __attribute__((ns_returns_retained)); 1768 1769The ``*_returns_retained`` attributes specify that the returned object has a +1 1770retain count. The ``*_returns_not_retained`` attributes specify that the return 1771object has a +0 retain count, even if the normal convention for its selector 1772would be +1. ``ns_returns_autoreleased`` specifies that the returned object is 1773+0, but is guaranteed to live at least as long as the next flush of an 1774autorelease pool. 1775 1776**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on 1777an parameter declaration; they specify that the argument is expected to have a 1778+1 retain count, which will be balanced in some way by the function or method. 1779The ``ns_consumes_self`` attribute can only be placed on an Objective-C 1780method; it specifies that the method expects its ``self`` parameter to have a 1781+1 retain count, which it will balance in some way. 1782 1783.. code-block:: objc 1784 1785 void foo(__attribute__((ns_consumed)) NSString *string); 1786 1787 - (void) bar __attribute__((ns_consumes_self)); 1788 - (void) baz:(id) __attribute__((ns_consumed)) x; 1789 1790Further examples of these attributes are available in the static analyzer's `list of annotations for analysis 1791<https://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_. 1792 1793Query for these features with ``__has_attribute(ns_consumed)``, 1794``__has_attribute(ns_returns_retained)``, etc. 1795 1796Objective-C @available 1797---------------------- 1798 1799It is possible to use the newest SDK but still build a program that can run on 1800older versions of macOS and iOS by passing ``-mmacosx-version-min=`` / 1801``-miphoneos-version-min=``. 1802 1803Before LLVM 5.0, when calling a function that exists only in the OS that's 1804newer than the target OS (as determined by the minimum deployment version), 1805programmers had to carefully check if the function exists at runtime, using 1806null checks for weakly-linked C functions, ``+class`` for Objective-C classes, 1807and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for 1808Objective-C methods. If such a check was missed, the program would compile 1809fine, run fine on newer systems, but crash on older systems. 1810 1811As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes 1812<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together 1813with the new ``@available()`` keyword to assist with this issue. 1814When a method that's introduced in the OS newer than the target OS is called, a 1815-Wunguarded-availability warning is emitted if that call is not guarded: 1816 1817.. code-block:: objc 1818 1819 void my_fun(NSSomeClass* var) { 1820 // If fancyNewMethod was added in e.g. macOS 10.12, but the code is 1821 // built with -mmacosx-version-min=10.11, then this unconditional call 1822 // will emit a -Wunguarded-availability warning: 1823 [var fancyNewMethod]; 1824 } 1825 1826To fix the warning and to avoid the crash on macOS 10.11, wrap it in 1827``if(@available())``: 1828 1829.. code-block:: objc 1830 1831 void my_fun(NSSomeClass* var) { 1832 if (@available(macOS 10.12, *)) { 1833 [var fancyNewMethod]; 1834 } else { 1835 // Put fallback behavior for old macOS versions (and for non-mac 1836 // platforms) here. 1837 } 1838 } 1839 1840The ``*`` is required and means that platforms not explicitly listed will take 1841the true branch, and the compiler will emit ``-Wunguarded-availability`` 1842warnings for unlisted platforms based on those platform's deployment target. 1843More than one platform can be listed in ``@available()``: 1844 1845.. code-block:: objc 1846 1847 void my_fun(NSSomeClass* var) { 1848 if (@available(macOS 10.12, iOS 10, *)) { 1849 [var fancyNewMethod]; 1850 } 1851 } 1852 1853If the caller of ``my_fun()`` already checks that ``my_fun()`` is only called 1854on 10.12, then add an `availability attribute 1855<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it, 1856which will also suppress the warning and require that calls to my_fun() are 1857checked: 1858 1859.. code-block:: objc 1860 1861 API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) { 1862 [var fancyNewMethod]; // Now ok. 1863 } 1864 1865``@available()`` is only available in Objective-C code. To use the feature 1866in C and C++ code, use the ``__builtin_available()`` spelling instead. 1867 1868If existing code uses null checks or ``-respondsToSelector:``, it should 1869be changed to use ``@available()`` (or ``__builtin_available``) instead. 1870 1871``-Wunguarded-availability`` is disabled by default, but 1872``-Wunguarded-availability-new``, which only emits this warning for APIs 1873that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and 1874tvOS >= 11, is enabled by default. 1875 1876.. _langext-overloading: 1877 1878Objective-C++ ABI: protocol-qualifier mangling of parameters 1879------------------------------------------------------------ 1880 1881Starting with LLVM 3.4, Clang produces a new mangling for parameters whose 1882type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such 1883parameters to be differentiated from those with the regular unqualified ``id`` 1884type. 1885 1886This was a non-backward compatible mangling change to the ABI. This change 1887allows proper overloading, and also prevents mangling conflicts with template 1888parameters of protocol-qualified type. 1889 1890Query the presence of this new mangling with 1891``__has_feature(objc_protocol_qualifier_mangling)``. 1892 1893Initializer lists for complex numbers in C 1894========================================== 1895 1896clang supports an extension which allows the following in C: 1897 1898.. code-block:: c++ 1899 1900 #include <math.h> 1901 #include <complex.h> 1902 complex float x = { 1.0f, INFINITY }; // Init to (1, Inf) 1903 1904This construct is useful because there is no way to separately initialize the 1905real and imaginary parts of a complex variable in standard C, given that clang 1906does not support ``_Imaginary``. (Clang also supports the ``__real__`` and 1907``__imag__`` extensions from gcc, which help in some cases, but are not usable 1908in static initializers.) 1909 1910Note that this extension does not allow eliding the braces; the meaning of the 1911following two lines is different: 1912 1913.. code-block:: c++ 1914 1915 complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1) 1916 complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0) 1917 1918This extension also works in C++ mode, as far as that goes, but does not apply 1919to the C++ ``std::complex``. (In C++11, list initialization allows the same 1920syntax to be used with ``std::complex`` with the same meaning.) 1921 1922For GCC compatibility, ``__builtin_complex(re, im)`` can also be used to 1923construct a complex number from the given real and imaginary components. 1924 1925OpenCL Features 1926=============== 1927 1928Clang supports internal OpenCL extensions documented below. 1929 1930``__cl_clang_bitfields`` 1931-------------------------------- 1932 1933With this extension it is possible to enable bitfields in structs 1934or unions using the OpenCL extension pragma mechanism detailed in 1935`the OpenCL Extension Specification, section 1.2 1936<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_. 1937 1938Use of bitfields in OpenCL kernels can result in reduced portability as struct 1939layout is not guaranteed to be consistent when compiled by different compilers. 1940If structs with bitfields are used as kernel function parameters, it can result 1941in incorrect functionality when the layout is different between the host and 1942device code. 1943 1944**Example of Use**: 1945 1946.. code-block:: c++ 1947 1948 #pragma OPENCL EXTENSION __cl_clang_bitfields : enable 1949 struct with_bitfield { 1950 unsigned int i : 5; // compiled - no diagnostic generated 1951 }; 1952 1953 #pragma OPENCL EXTENSION __cl_clang_bitfields : disable 1954 struct without_bitfield { 1955 unsigned int i : 5; // error - bitfields are not supported 1956 }; 1957 1958``__cl_clang_function_pointers`` 1959-------------------------------- 1960 1961With this extension it is possible to enable various language features that 1962are relying on function pointers using regular OpenCL extension pragma 1963mechanism detailed in `the OpenCL Extension Specification, 1964section 1.2 1965<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_. 1966 1967In C++ for OpenCL this also enables: 1968 1969- Use of member function pointers; 1970 1971- Unrestricted use of references to functions; 1972 1973- Virtual member functions. 1974 1975Such functionality is not conformant and does not guarantee to compile 1976correctly in any circumstances. It can be used if: 1977 1978- the kernel source does not contain call expressions to (member-) function 1979 pointers, or virtual functions. For example this extension can be used in 1980 metaprogramming algorithms to be able to specify/detect types generically. 1981 1982- the generated kernel binary does not contain indirect calls because they 1983 are eliminated using compiler optimizations e.g. devirtualization. 1984 1985- the selected target supports the function pointer like functionality e.g. 1986 most CPU targets. 1987 1988**Example of Use**: 1989 1990.. code-block:: c++ 1991 1992 #pragma OPENCL EXTENSION __cl_clang_function_pointers : enable 1993 void foo() 1994 { 1995 void (*fp)(); // compiled - no diagnostic generated 1996 } 1997 1998 #pragma OPENCL EXTENSION __cl_clang_function_pointers : disable 1999 void bar() 2000 { 2001 void (*fp)(); // error - pointers to function are not allowed 2002 } 2003 2004``__cl_clang_variadic_functions`` 2005--------------------------------- 2006 2007With this extension it is possible to enable variadic arguments in functions 2008using regular OpenCL extension pragma mechanism detailed in `the OpenCL 2009Extension Specification, section 1.2 2010<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_. 2011 2012This is not conformant behavior and it can only be used portably when the 2013functions with variadic prototypes do not get generated in binary e.g. the 2014variadic prototype is used to specify a function type with any number of 2015arguments in metaprogramming algorithms in C++ for OpenCL. 2016 2017This extensions can also be used when the kernel code is intended for targets 2018supporting the variadic arguments e.g. majority of CPU targets. 2019 2020**Example of Use**: 2021 2022.. code-block:: c++ 2023 2024 #pragma OPENCL EXTENSION __cl_clang_variadic_functions : enable 2025 void foo(int a, ...); // compiled - no diagnostic generated 2026 2027 #pragma OPENCL EXTENSION __cl_clang_variadic_functions : disable 2028 void bar(int a, ...); // error - variadic prototype is not allowed 2029 2030``__cl_clang_non_portable_kernel_param_types`` 2031---------------------------------------------- 2032 2033With this extension it is possible to enable the use of some restricted types 2034in kernel parameters specified in `C++ for OpenCL v1.0 s2.4 2035<https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html#kernel_function>`_. 2036The restrictions can be relaxed using regular OpenCL extension pragma mechanism 2037detailed in `the OpenCL Extension Specification, section 1.2 2038<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_. 2039 2040This is not a conformant behavior and it can only be used when the 2041kernel arguments are not accessed on the host side or the data layout/size 2042between the host and device is known to be compatible. 2043 2044**Example of Use**: 2045 2046.. code-block:: c++ 2047 2048 // Plain Old Data type. 2049 struct Pod { 2050 int a; 2051 int b; 2052 }; 2053 2054 // Not POD type because of the constructor. 2055 // Standard layout type because there is only one access control. 2056 struct OnlySL { 2057 int a; 2058 int b; 2059 NotPod() : a(0), b(0) {} 2060 }; 2061 2062 // Not standard layout type because of two different access controls. 2063 struct NotSL { 2064 int a; 2065 private: 2066 int b; 2067 } 2068 2069 kernel void kernel_main( 2070 Pod a, 2071 #pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : enable 2072 OnlySL b, 2073 global NotSL *c, 2074 #pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : disable 2075 global OnlySL *d, 2076 ); 2077 2078Remove address space builtin function 2079------------------------------------- 2080 2081``__remove_address_space`` allows to derive types in C++ for OpenCL 2082that have address space qualifiers removed. This utility only affects 2083address space qualifiers, therefore, other type qualifiers such as 2084``const`` or ``volatile`` remain unchanged. 2085 2086**Example of Use**: 2087 2088.. code-block:: c++ 2089 2090 template<typename T> 2091 void foo(T *par){ 2092 T var1; // error - local function variable with global address space 2093 __private T var2; // error - conflicting address space qualifiers 2094 __private __remove_address_space<T>::type var3; // var3 is __private int 2095 } 2096 2097 void bar(){ 2098 __global int* ptr; 2099 foo(ptr); 2100 } 2101 2102Legacy 1.x atomics with generic address space 2103--------------------------------------------- 2104 2105Clang allows use of atomic functions from the OpenCL 1.x standards 2106with the generic address space pointer in C++ for OpenCL mode. 2107 2108This is a non-portable feature and might not be supported by all 2109targets. 2110 2111**Example of Use**: 2112 2113.. code-block:: c++ 2114 2115 void foo(__generic volatile unsigned int* a) { 2116 atomic_add(a, 1); 2117 } 2118 2119Builtin Functions 2120================= 2121 2122Clang supports a number of builtin library functions with the same syntax as 2123GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``, 2124``__builtin_choose_expr``, ``__builtin_types_compatible_p``, 2125``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc. In addition to 2126the GCC builtins, Clang supports a number of builtins that GCC does not, which 2127are listed here. 2128 2129Please note that Clang does not and will not support all of the GCC builtins 2130for vector operations. Instead of using builtins, you should use the functions 2131defined in target-specific header files like ``<xmmintrin.h>``, which define 2132portable wrappers for these. Many of the Clang versions of these functions are 2133implemented directly in terms of :ref:`extended vector support 2134<langext-vectors>` instead of builtins, in order to reduce the number of 2135builtins that we need to implement. 2136 2137``__builtin_alloca`` 2138-------------------- 2139 2140``__builtin_alloca`` is used to dynamically allocate memory on the stack. Memory 2141is automatically freed upon function termination. 2142 2143**Syntax**: 2144 2145.. code-block:: c++ 2146 2147 __builtin_alloca(size_t n) 2148 2149**Example of Use**: 2150 2151.. code-block:: c++ 2152 2153 void init(float* data, size_t nbelems); 2154 void process(float* data, size_t nbelems); 2155 int foo(size_t n) { 2156 auto mem = (float*)__builtin_alloca(n * sizeof(float)); 2157 init(mem, n); 2158 process(mem, n); 2159 /* mem is automatically freed at this point */ 2160 } 2161 2162**Description**: 2163 2164``__builtin_alloca`` is meant to be used to allocate a dynamic amount of memory 2165on the stack. This amount is subject to stack allocation limits. 2166 2167Query for this feature with ``__has_builtin(__builtin_alloca)``. 2168 2169``__builtin_alloca_with_align`` 2170------------------------------- 2171 2172``__builtin_alloca_with_align`` is used to dynamically allocate memory on the 2173stack while controlling its alignment. Memory is automatically freed upon 2174function termination. 2175 2176 2177**Syntax**: 2178 2179.. code-block:: c++ 2180 2181 __builtin_alloca_with_align(size_t n, size_t align) 2182 2183**Example of Use**: 2184 2185.. code-block:: c++ 2186 2187 void init(float* data, size_t nbelems); 2188 void process(float* data, size_t nbelems); 2189 int foo(size_t n) { 2190 auto mem = (float*)__builtin_alloca_with_align( 2191 n * sizeof(float), 2192 CHAR_BIT * alignof(float)); 2193 init(mem, n); 2194 process(mem, n); 2195 /* mem is automatically freed at this point */ 2196 } 2197 2198**Description**: 2199 2200``__builtin_alloca_with_align`` is meant to be used to allocate a dynamic amount of memory 2201on the stack. It is similar to ``__builtin_alloca`` but accepts a second 2202argument whose value is the alignment constraint, as a power of 2 in *bits*. 2203 2204Query for this feature with ``__has_builtin(__builtin_alloca_with_align)``. 2205 2206.. _langext-__builtin_assume: 2207 2208``__builtin_call_with_static_chain`` 2209------------------------------------ 2210 2211``__builtin_call_with_static_chain`` is used to perform a static call while 2212setting updating the static chain register. 2213 2214**Syntax**: 2215 2216.. code-block:: c++ 2217 2218 T __builtin_call_with_static_chain(T expr, void* ptr) 2219 2220**Example of Use**: 2221 2222.. code-block:: c++ 2223 2224 auto v = __builtin_call_with_static_chain(foo(3), foo); 2225 2226**Description**: 2227 2228This builtin returns ``expr`` after checking that ``expr`` is a non-member 2229static call expression. The call to that expression is made while using ``ptr`` 2230as a function pointer stored in a dedicated register to implement *static chain* 2231calling convention, as used by some language to implement closures or nested 2232functions. 2233 2234Query for this feature with ``__has_builtin(__builtin_call_with_static_chain)``. 2235 2236``__builtin_readcyclecounter`` 2237------------------------------ 2238 2239``__builtin_readcyclecounter`` is used to access the cycle counter register (or 2240a similar low-latency, high-accuracy clock) on those targets that support it. 2241 2242**Syntax**: 2243 2244.. code-block:: c++ 2245 2246 __builtin_readcyclecounter() 2247 2248**Example of Use**: 2249 2250.. code-block:: c++ 2251 2252 unsigned long long t0 = __builtin_readcyclecounter(); 2253 do_something(); 2254 unsigned long long t1 = __builtin_readcyclecounter(); 2255 unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow 2256 2257**Description**: 2258 2259The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value, 2260which may be either global or process/thread-specific depending on the target. 2261As the backing counters often overflow quickly (on the order of seconds) this 2262should only be used for timing small intervals. When not supported by the 2263target, the return value is always zero. This builtin takes no arguments and 2264produces an unsigned long long result. 2265 2266Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note 2267that even if present, its use may depend on run-time privilege or other OS 2268controlled state. 2269 2270``__builtin_dump_struct`` 2271------------------------- 2272 2273**Syntax**: 2274 2275.. code-block:: c++ 2276 2277 __builtin_dump_struct(&some_struct, &some_printf_func); 2278 2279**Examples**: 2280 2281.. code-block:: c++ 2282 2283 struct S { 2284 int x, y; 2285 float f; 2286 struct T { 2287 int i; 2288 } t; 2289 }; 2290 2291 void func(struct S *s) { 2292 __builtin_dump_struct(s, &printf); 2293 } 2294 2295Example output: 2296 2297.. code-block:: none 2298 2299 struct S { 2300 int i : 100 2301 int j : 42 2302 float f : 3.14159 2303 struct T t : struct T { 2304 int i : 1997 2305 } 2306 } 2307 2308**Description**: 2309 2310The '``__builtin_dump_struct``' function is used to print the fields of a simple 2311structure and their values for debugging purposes. The builtin accepts a pointer 2312to a structure to dump the fields of, and a pointer to a formatted output 2313function whose signature must be: ``int (*)(const char *, ...)`` and must 2314support the format specifiers used by ``printf()``. 2315 2316.. _langext-__builtin_shufflevector: 2317 2318``__builtin_shufflevector`` 2319--------------------------- 2320 2321``__builtin_shufflevector`` is used to express generic vector 2322permutation/shuffle/swizzle operations. This builtin is also very important 2323for the implementation of various target-specific header files like 2324``<xmmintrin.h>``. 2325 2326**Syntax**: 2327 2328.. code-block:: c++ 2329 2330 __builtin_shufflevector(vec1, vec2, index1, index2, ...) 2331 2332**Examples**: 2333 2334.. code-block:: c++ 2335 2336 // identity operation - return 4-element vector v1. 2337 __builtin_shufflevector(v1, v1, 0, 1, 2, 3) 2338 2339 // "Splat" element 0 of V1 into a 4-element result. 2340 __builtin_shufflevector(V1, V1, 0, 0, 0, 0) 2341 2342 // Reverse 4-element vector V1. 2343 __builtin_shufflevector(V1, V1, 3, 2, 1, 0) 2344 2345 // Concatenate every other element of 4-element vectors V1 and V2. 2346 __builtin_shufflevector(V1, V2, 0, 2, 4, 6) 2347 2348 // Concatenate every other element of 8-element vectors V1 and V2. 2349 __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14) 2350 2351 // Shuffle v1 with some elements being undefined 2352 __builtin_shufflevector(v1, v1, 3, -1, 1, -1) 2353 2354**Description**: 2355 2356The first two arguments to ``__builtin_shufflevector`` are vectors that have 2357the same element type. The remaining arguments are a list of integers that 2358specify the elements indices of the first two vectors that should be extracted 2359and returned in a new vector. These element indices are numbered sequentially 2360starting with the first vector, continuing into the second vector. Thus, if 2361``vec1`` is a 4-element vector, index 5 would refer to the second element of 2362``vec2``. An index of -1 can be used to indicate that the corresponding element 2363in the returned vector is a don't care and can be optimized by the backend. 2364 2365The result of ``__builtin_shufflevector`` is a vector with the same element 2366type as ``vec1``/``vec2`` but that has an element count equal to the number of 2367indices specified. 2368 2369Query for this feature with ``__has_builtin(__builtin_shufflevector)``. 2370 2371.. _langext-__builtin_convertvector: 2372 2373``__builtin_convertvector`` 2374--------------------------- 2375 2376``__builtin_convertvector`` is used to express generic vector 2377type-conversion operations. The input vector and the output vector 2378type must have the same number of elements. 2379 2380**Syntax**: 2381 2382.. code-block:: c++ 2383 2384 __builtin_convertvector(src_vec, dst_vec_type) 2385 2386**Examples**: 2387 2388.. code-block:: c++ 2389 2390 typedef double vector4double __attribute__((__vector_size__(32))); 2391 typedef float vector4float __attribute__((__vector_size__(16))); 2392 typedef short vector4short __attribute__((__vector_size__(8))); 2393 vector4float vf; vector4short vs; 2394 2395 // convert from a vector of 4 floats to a vector of 4 doubles. 2396 __builtin_convertvector(vf, vector4double) 2397 // equivalent to: 2398 (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] } 2399 2400 // convert from a vector of 4 shorts to a vector of 4 floats. 2401 __builtin_convertvector(vs, vector4float) 2402 // equivalent to: 2403 (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] } 2404 2405**Description**: 2406 2407The first argument to ``__builtin_convertvector`` is a vector, and the second 2408argument is a vector type with the same number of elements as the first 2409argument. 2410 2411The result of ``__builtin_convertvector`` is a vector with the same element 2412type as the second argument, with a value defined in terms of the action of a 2413C-style cast applied to each element of the first argument. 2414 2415Query for this feature with ``__has_builtin(__builtin_convertvector)``. 2416 2417``__builtin_bitreverse`` 2418------------------------ 2419 2420* ``__builtin_bitreverse8`` 2421* ``__builtin_bitreverse16`` 2422* ``__builtin_bitreverse32`` 2423* ``__builtin_bitreverse64`` 2424 2425**Syntax**: 2426 2427.. code-block:: c++ 2428 2429 __builtin_bitreverse32(x) 2430 2431**Examples**: 2432 2433.. code-block:: c++ 2434 2435 uint8_t rev_x = __builtin_bitreverse8(x); 2436 uint16_t rev_x = __builtin_bitreverse16(x); 2437 uint32_t rev_y = __builtin_bitreverse32(y); 2438 uint64_t rev_z = __builtin_bitreverse64(z); 2439 2440**Description**: 2441 2442The '``__builtin_bitreverse``' family of builtins is used to reverse 2443the bitpattern of an integer value; for example ``0b10110110`` becomes 2444``0b01101101``. These builtins can be used within constant expressions. 2445 2446``__builtin_rotateleft`` 2447------------------------ 2448 2449* ``__builtin_rotateleft8`` 2450* ``__builtin_rotateleft16`` 2451* ``__builtin_rotateleft32`` 2452* ``__builtin_rotateleft64`` 2453 2454**Syntax**: 2455 2456.. code-block:: c++ 2457 2458 __builtin_rotateleft32(x, y) 2459 2460**Examples**: 2461 2462.. code-block:: c++ 2463 2464 uint8_t rot_x = __builtin_rotateleft8(x, y); 2465 uint16_t rot_x = __builtin_rotateleft16(x, y); 2466 uint32_t rot_x = __builtin_rotateleft32(x, y); 2467 uint64_t rot_x = __builtin_rotateleft64(x, y); 2468 2469**Description**: 2470 2471The '``__builtin_rotateleft``' family of builtins is used to rotate 2472the bits in the first argument by the amount in the second argument. 2473For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``. 2474The shift value is treated as an unsigned amount modulo the size of 2475the arguments. Both arguments and the result have the bitwidth specified 2476by the name of the builtin. These builtins can be used within constant 2477expressions. 2478 2479``__builtin_rotateright`` 2480------------------------- 2481 2482* ``__builtin_rotateright8`` 2483* ``__builtin_rotateright16`` 2484* ``__builtin_rotateright32`` 2485* ``__builtin_rotateright64`` 2486 2487**Syntax**: 2488 2489.. code-block:: c++ 2490 2491 __builtin_rotateright32(x, y) 2492 2493**Examples**: 2494 2495.. code-block:: c++ 2496 2497 uint8_t rot_x = __builtin_rotateright8(x, y); 2498 uint16_t rot_x = __builtin_rotateright16(x, y); 2499 uint32_t rot_x = __builtin_rotateright32(x, y); 2500 uint64_t rot_x = __builtin_rotateright64(x, y); 2501 2502**Description**: 2503 2504The '``__builtin_rotateright``' family of builtins is used to rotate 2505the bits in the first argument by the amount in the second argument. 2506For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``. 2507The shift value is treated as an unsigned amount modulo the size of 2508the arguments. Both arguments and the result have the bitwidth specified 2509by the name of the builtin. These builtins can be used within constant 2510expressions. 2511 2512``__builtin_unreachable`` 2513------------------------- 2514 2515``__builtin_unreachable`` is used to indicate that a specific point in the 2516program cannot be reached, even if the compiler might otherwise think it can. 2517This is useful to improve optimization and eliminates certain warnings. For 2518example, without the ``__builtin_unreachable`` in the example below, the 2519compiler assumes that the inline asm can fall through and prints a "function 2520declared '``noreturn``' should not return" warning. 2521 2522**Syntax**: 2523 2524.. code-block:: c++ 2525 2526 __builtin_unreachable() 2527 2528**Example of use**: 2529 2530.. code-block:: c++ 2531 2532 void myabort(void) __attribute__((noreturn)); 2533 void myabort(void) { 2534 asm("int3"); 2535 __builtin_unreachable(); 2536 } 2537 2538**Description**: 2539 2540The ``__builtin_unreachable()`` builtin has completely undefined behavior. 2541Since it has undefined behavior, it is a statement that it is never reached and 2542the optimizer can take advantage of this to produce better code. This builtin 2543takes no arguments and produces a void result. 2544 2545Query for this feature with ``__has_builtin(__builtin_unreachable)``. 2546 2547``__builtin_unpredictable`` 2548--------------------------- 2549 2550``__builtin_unpredictable`` is used to indicate that a branch condition is 2551unpredictable by hardware mechanisms such as branch prediction logic. 2552 2553**Syntax**: 2554 2555.. code-block:: c++ 2556 2557 __builtin_unpredictable(long long) 2558 2559**Example of use**: 2560 2561.. code-block:: c++ 2562 2563 if (__builtin_unpredictable(x > 0)) { 2564 foo(); 2565 } 2566 2567**Description**: 2568 2569The ``__builtin_unpredictable()`` builtin is expected to be used with control 2570flow conditions such as in ``if`` and ``switch`` statements. 2571 2572Query for this feature with ``__has_builtin(__builtin_unpredictable)``. 2573 2574 2575``__builtin_expect`` 2576-------------------- 2577 2578``__builtin_expect`` is used to indicate that the value of an expression is 2579anticipated to be the same as a statically known result. 2580 2581**Syntax**: 2582 2583.. code-block:: c++ 2584 2585 long __builtin_expect(long expr, long val) 2586 2587**Example of use**: 2588 2589.. code-block:: c++ 2590 2591 if (__builtin_expect(x, 0)) { 2592 bar(); 2593 } 2594 2595**Description**: 2596 2597The ``__builtin_expect()`` builtin is typically used with control flow 2598conditions such as in ``if`` and ``switch`` statements to help branch 2599prediction. It means that its first argument ``expr`` is expected to take the 2600value of its second argument ``val``. It always returns ``expr``. 2601 2602Query for this feature with ``__has_builtin(__builtin_expect)``. 2603 2604``__builtin_expect_with_probability`` 2605------------------------------------- 2606 2607``__builtin_expect_with_probability`` is similar to ``__builtin_expect`` but it 2608takes a probability as third argument. 2609 2610**Syntax**: 2611 2612.. code-block:: c++ 2613 2614 long __builtin_expect_with_probability(long expr, long val, double p) 2615 2616**Example of use**: 2617 2618.. code-block:: c++ 2619 2620 if (__builtin_expect_with_probability(x, 0, .3)) { 2621 bar(); 2622 } 2623 2624**Description**: 2625 2626The ``__builtin_expect_with_probability()`` builtin is typically used with 2627control flow conditions such as in ``if`` and ``switch`` statements to help 2628branch prediction. It means that its first argument ``expr`` is expected to take 2629the value of its second argument ``val`` with probability ``p``. ``p`` must be 2630within ``[0.0 ; 1.0]`` bounds. This builtin always returns the value of ``expr``. 2631 2632Query for this feature with ``__has_builtin(__builtin_expect_with_probability)``. 2633 2634``__builtin_prefetch`` 2635---------------------- 2636 2637``__builtin_prefetch`` is used to communicate with the cache handler to bring 2638data into the cache before it gets used. 2639 2640**Syntax**: 2641 2642.. code-block:: c++ 2643 2644 void __builtin_prefetch(const void *addr, int rw=0, int locality=3) 2645 2646**Example of use**: 2647 2648.. code-block:: c++ 2649 2650 __builtin_prefetch(a + i); 2651 2652**Description**: 2653 2654The ``__builtin_prefetch(addr, rw, locality)`` builtin is expected to be used to 2655avoid cache misses when the developper has a good understanding of which data 2656are going to be used next. ``addr`` is the address that needs to be brought into 2657the cache. ``rw`` indicates the expected access mode: ``0`` for *read* and ``1`` 2658for *write*. In case of *read write* access, ``1`` is to be used. ``locality`` 2659indicates the expected persistance of data in cache, from ``0`` which means that 2660data can be discarded from cache after its next use to ``3`` which means that 2661data is going to be reused a lot once in cache. ``1`` and ``2`` provide 2662intermediate behavior between these two extremes. 2663 2664Query for this feature with ``__has_builtin(__builtin_prefetch)``. 2665 2666``__sync_swap`` 2667--------------- 2668 2669``__sync_swap`` is used to atomically swap integers or pointers in memory. 2670 2671**Syntax**: 2672 2673.. code-block:: c++ 2674 2675 type __sync_swap(type *ptr, type value, ...) 2676 2677**Example of Use**: 2678 2679.. code-block:: c++ 2680 2681 int old_value = __sync_swap(&value, new_value); 2682 2683**Description**: 2684 2685The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of 2686atomic intrinsics to allow code to atomically swap the current value with the 2687new value. More importantly, it helps developers write more efficient and 2688correct code by avoiding expensive loops around 2689``__sync_bool_compare_and_swap()`` or relying on the platform specific 2690implementation details of ``__sync_lock_test_and_set()``. The 2691``__sync_swap()`` builtin is a full barrier. 2692 2693``__builtin_addressof`` 2694----------------------- 2695 2696``__builtin_addressof`` performs the functionality of the built-in ``&`` 2697operator, ignoring any ``operator&`` overload. This is useful in constant 2698expressions in C++11, where there is no other way to take the address of an 2699object that overloads ``operator&``. 2700 2701**Example of use**: 2702 2703.. code-block:: c++ 2704 2705 template<typename T> constexpr T *addressof(T &value) { 2706 return __builtin_addressof(value); 2707 } 2708 2709``__builtin_function_start`` 2710----------------------------- 2711 2712``__builtin_function_start`` returns the address of a function body. 2713 2714**Syntax**: 2715 2716.. code-block:: c++ 2717 2718 void *__builtin_function_start(function) 2719 2720**Example of use**: 2721 2722.. code-block:: c++ 2723 2724 void a() {} 2725 void *p = __builtin_function_start(a); 2726 2727 class A { 2728 public: 2729 void a(int n); 2730 void a(); 2731 }; 2732 2733 void A::a(int n) {} 2734 void A::a() {} 2735 2736 void *pa1 = __builtin_function_start((void(A::*)(int)) &A::a); 2737 void *pa2 = __builtin_function_start((void(A::*)()) &A::a); 2738 2739**Description**: 2740 2741The ``__builtin_function_start`` builtin accepts an argument that can be 2742constant-evaluated to a function, and returns the address of the function 2743body. This builtin is not supported on all targets. 2744 2745The returned pointer may differ from the normally taken function address 2746and is not safe to call. For example, with ``-fsanitize=cfi``, taking a 2747function address produces a callable pointer to a CFI jump table, while 2748``__builtin_function_start`` returns an address that fails 2749:doc:`cfi-icall<ControlFlowIntegrity>` checks. 2750 2751``__builtin_operator_new`` and ``__builtin_operator_delete`` 2752------------------------------------------------------------ 2753 2754A call to ``__builtin_operator_new(args)`` is exactly the same as a call to 2755``::operator new(args)``, except that it allows certain optimizations 2756that the C++ standard does not permit for a direct function call to 2757``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and 2758merging allocations), and that the call is required to resolve to a 2759`replaceable global allocation function 2760<https://en.cppreference.com/w/cpp/memory/new/operator_new>`_. 2761 2762Likewise, ``__builtin_operator_delete`` is exactly the same as a call to 2763``::operator delete(args)``, except that it permits optimizations 2764and that the call is required to resolve to a 2765`replaceable global deallocation function 2766<https://en.cppreference.com/w/cpp/memory/new/operator_delete>`_. 2767 2768These builtins are intended for use in the implementation of ``std::allocator`` 2769and other similar allocation libraries, and are only available in C++. 2770 2771Query for this feature with ``__has_builtin(__builtin_operator_new)`` or 2772``__has_builtin(__builtin_operator_delete)``: 2773 2774 * If the value is at least ``201802L``, the builtins behave as described above. 2775 2776 * If the value is non-zero, the builtins may not support calling arbitrary 2777 replaceable global (de)allocation functions, but do support calling at least 2778 ``::operator new(size_t)`` and ``::operator delete(void*)``. 2779 2780``__builtin_preserve_access_index`` 2781----------------------------------- 2782 2783``__builtin_preserve_access_index`` specifies a code section where 2784array subscript access and structure/union member access are relocatable 2785under bpf compile-once run-everywhere framework. Debuginfo (typically 2786with ``-g``) is needed, otherwise, the compiler will exit with an error. 2787The return type for the intrinsic is the same as the type of the 2788argument. 2789 2790**Syntax**: 2791 2792.. code-block:: c 2793 2794 type __builtin_preserve_access_index(type arg) 2795 2796**Example of Use**: 2797 2798.. code-block:: c 2799 2800 struct t { 2801 int i; 2802 int j; 2803 union { 2804 int a; 2805 int b; 2806 } c[4]; 2807 }; 2808 struct t *v = ...; 2809 int *pb =__builtin_preserve_access_index(&v->c[3].b); 2810 __builtin_preserve_access_index(v->j); 2811 2812``__builtin_debugtrap`` 2813----------------------- 2814 2815``__builtin_debugtrap`` causes the program to stop its execution in such a way that a debugger can catch it. 2816 2817**Syntax**: 2818 2819.. code-block:: c++ 2820 2821 __builtin_debugtrap() 2822 2823**Description** 2824 2825``__builtin_debugtrap`` is lowered to the ` ``llvm.debugtrap`` <https://llvm.org/docs/LangRef.html#llvm-debugtrap-intrinsic>`_ builtin. It should have the same effect as setting a breakpoint on the line where the builtin is called. 2826 2827Query for this feature with ``__has_builtin(__builtin_debugtrap)``. 2828 2829 2830``__builtin_trap`` 2831------------------ 2832 2833``__builtin_trap`` causes the program to stop its execution abnormally. 2834 2835**Syntax**: 2836 2837.. code-block:: c++ 2838 2839 __builtin_trap() 2840 2841**Description** 2842 2843``__builtin_trap`` is lowered to the ` ``llvm.trap`` <https://llvm.org/docs/LangRef.html#llvm-trap-intrinsic>`_ builtin. 2844 2845Query for this feature with ``__has_builtin(__builtin_trap)``. 2846 2847 2848``__builtin_sycl_unique_stable_name`` 2849------------------------------------- 2850 2851``__builtin_sycl_unique_stable_name()`` is a builtin that takes a type and 2852produces a string literal containing a unique name for the type that is stable 2853across split compilations, mainly to support SYCL/Data Parallel C++ language. 2854 2855In cases where the split compilation needs to share a unique token for a type 2856across the boundary (such as in an offloading situation), this name can be used 2857for lookup purposes, such as in the SYCL Integration Header. 2858 2859The value of this builtin is computed entirely at compile time, so it can be 2860used in constant expressions. This value encodes lambda functions based on a 2861stable numbering order in which they appear in their local declaration contexts. 2862Once this builtin is evaluated in a constexpr context, it is erroneous to use 2863it in an instantiation which changes its value. 2864 2865In order to produce the unique name, the current implementation of the bultin 2866uses Itanium mangling even if the host compilation uses a different name 2867mangling scheme at runtime. The mangler marks all the lambdas required to name 2868the SYCL kernel and emits a stable local ordering of the respective lambdas. 2869The resulting pattern is demanglable. When non-lambda types are passed to the 2870builtin, the mangler emits their usual pattern without any special treatment. 2871 2872**Syntax**: 2873 2874.. code-block:: c 2875 2876 // Computes a unique stable name for the given type. 2877 constexpr const char * __builtin_sycl_unique_stable_name( type-id ); 2878 2879Multiprecision Arithmetic Builtins 2880---------------------------------- 2881 2882Clang provides a set of builtins which expose multiprecision arithmetic in a 2883manner amenable to C. They all have the following form: 2884 2885.. code-block:: c 2886 2887 unsigned x = ..., y = ..., carryin = ..., carryout; 2888 unsigned sum = __builtin_addc(x, y, carryin, &carryout); 2889 2890Thus one can form a multiprecision addition chain in the following manner: 2891 2892.. code-block:: c 2893 2894 unsigned *x, *y, *z, carryin=0, carryout; 2895 z[0] = __builtin_addc(x[0], y[0], carryin, &carryout); 2896 carryin = carryout; 2897 z[1] = __builtin_addc(x[1], y[1], carryin, &carryout); 2898 carryin = carryout; 2899 z[2] = __builtin_addc(x[2], y[2], carryin, &carryout); 2900 carryin = carryout; 2901 z[3] = __builtin_addc(x[3], y[3], carryin, &carryout); 2902 2903The complete list of builtins are: 2904 2905.. code-block:: c 2906 2907 unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout); 2908 unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout); 2909 unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout); 2910 unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout); 2911 unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout); 2912 unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout); 2913 unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout); 2914 unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout); 2915 unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout); 2916 unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout); 2917 2918Checked Arithmetic Builtins 2919--------------------------- 2920 2921Clang provides a set of builtins that implement checked arithmetic for security 2922critical applications in a manner that is fast and easily expressible in C. As 2923an example of their usage: 2924 2925.. code-block:: c 2926 2927 errorcode_t security_critical_application(...) { 2928 unsigned x, y, result; 2929 ... 2930 if (__builtin_mul_overflow(x, y, &result)) 2931 return kErrorCodeHackers; 2932 ... 2933 use_multiply(result); 2934 ... 2935 } 2936 2937Clang provides the following checked arithmetic builtins: 2938 2939.. code-block:: c 2940 2941 bool __builtin_add_overflow (type1 x, type2 y, type3 *sum); 2942 bool __builtin_sub_overflow (type1 x, type2 y, type3 *diff); 2943 bool __builtin_mul_overflow (type1 x, type2 y, type3 *prod); 2944 bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum); 2945 bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum); 2946 bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum); 2947 bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff); 2948 bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff); 2949 bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff); 2950 bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod); 2951 bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod); 2952 bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod); 2953 bool __builtin_sadd_overflow (int x, int y, int *sum); 2954 bool __builtin_saddl_overflow (long x, long y, long *sum); 2955 bool __builtin_saddll_overflow(long long x, long long y, long long *sum); 2956 bool __builtin_ssub_overflow (int x, int y, int *diff); 2957 bool __builtin_ssubl_overflow (long x, long y, long *diff); 2958 bool __builtin_ssubll_overflow(long long x, long long y, long long *diff); 2959 bool __builtin_smul_overflow (int x, int y, int *prod); 2960 bool __builtin_smull_overflow (long x, long y, long *prod); 2961 bool __builtin_smulll_overflow(long long x, long long y, long long *prod); 2962 2963Each builtin performs the specified mathematical operation on the 2964first two arguments and stores the result in the third argument. If 2965possible, the result will be equal to mathematically-correct result 2966and the builtin will return 0. Otherwise, the builtin will return 29671 and the result will be equal to the unique value that is equivalent 2968to the mathematically-correct result modulo two raised to the *k* 2969power, where *k* is the number of bits in the result type. The 2970behavior of these builtins is well-defined for all argument values. 2971 2972The first three builtins work generically for operands of any integer type, 2973including boolean types. The operands need not have the same type as each 2974other, or as the result. The other builtins may implicitly promote or 2975convert their operands before performing the operation. 2976 2977Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc. 2978 2979Floating point builtins 2980--------------------------------------- 2981 2982``__builtin_canonicalize`` 2983-------------------------- 2984 2985.. code-block:: c 2986 2987 double __builtin_canonicalize(double); 2988 float __builtin_canonicalizef(float); 2989 long double__builtin_canonicalizel(long double); 2990 2991Returns the platform specific canonical encoding of a floating point 2992number. This canonicalization is useful for implementing certain 2993numeric primitives such as frexp. See `LLVM canonicalize intrinsic 2994<https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for 2995more information on the semantics. 2996 2997String builtins 2998--------------- 2999 3000Clang provides constant expression evaluation support for builtins forms of 3001the following functions from the C standard library headers 3002``<string.h>`` and ``<wchar.h>``: 3003 3004* ``memchr`` 3005* ``memcmp`` (and its deprecated BSD / POSIX alias ``bcmp``) 3006* ``strchr`` 3007* ``strcmp`` 3008* ``strlen`` 3009* ``strncmp`` 3010* ``wcschr`` 3011* ``wcscmp`` 3012* ``wcslen`` 3013* ``wcsncmp`` 3014* ``wmemchr`` 3015* ``wmemcmp`` 3016 3017In each case, the builtin form has the name of the C library function prefixed 3018by ``__builtin_``. Example: 3019 3020.. code-block:: c 3021 3022 void *p = __builtin_memchr("foobar", 'b', 5); 3023 3024In addition to the above, one further builtin is provided: 3025 3026.. code-block:: c 3027 3028 char *__builtin_char_memchr(const char *haystack, int needle, size_t size); 3029 3030``__builtin_char_memchr(a, b, c)`` is identical to 3031``(char*)__builtin_memchr(a, b, c)`` except that its use is permitted within 3032constant expressions in C++11 onwards (where a cast from ``void*`` to ``char*`` 3033is disallowed in general). 3034 3035Constant evaluation support for the ``__builtin_mem*`` functions is provided 3036only for arrays of ``char``, ``signed char``, ``unsigned char``, or ``char8_t``, 3037despite these functions accepting an argument of type ``const void*``. 3038 3039Support for constant expression evaluation for the above builtins can be detected 3040with ``__has_feature(cxx_constexpr_string_builtins)``. 3041 3042Memory builtins 3043--------------- 3044 3045Clang provides constant expression evaluation support for builtin forms of the 3046following functions from the C standard library headers 3047``<string.h>`` and ``<wchar.h>``: 3048 3049* ``memcpy`` 3050* ``memmove`` 3051* ``wmemcpy`` 3052* ``wmemmove`` 3053 3054In each case, the builtin form has the name of the C library function prefixed 3055by ``__builtin_``. 3056 3057Constant evaluation support is only provided when the source and destination 3058are pointers to arrays with the same trivially copyable element type, and the 3059given size is an exact multiple of the element size that is no greater than 3060the number of elements accessible through the source and destination operands. 3061 3062Guaranteed inlined copy 3063^^^^^^^^^^^^^^^^^^^^^^^ 3064 3065.. code-block:: c 3066 3067 void __builtin_memcpy_inline(void *dst, const void *src, size_t size); 3068 3069 3070``__builtin_memcpy_inline`` has been designed as a building block for efficient 3071``memcpy`` implementations. It is identical to ``__builtin_memcpy`` but also 3072guarantees not to call any external functions. See LLVM IR `llvm.memcpy.inline 3073<https://llvm.org/docs/LangRef.html#llvm-memcpy-inline-intrinsic>`_ intrinsic 3074for more information. 3075 3076This is useful to implement a custom version of ``memcpy``, implement a 3077``libc`` memcpy or work around the absence of a ``libc``. 3078 3079Note that the `size` argument must be a compile time constant. 3080 3081Note that this intrinsic cannot yet be called in a ``constexpr`` context. 3082 3083 3084Atomic Min/Max builtins with memory ordering 3085-------------------------------------------- 3086 3087There are two atomic builtins with min/max in-memory comparison and swap. 3088The syntax and semantics are similar to GCC-compatible __atomic_* builtins. 3089 3090* ``__atomic_fetch_min`` 3091* ``__atomic_fetch_max`` 3092 3093The builtins work with signed and unsigned integers and require to specify memory ordering. 3094The return value is the original value that was stored in memory before comparison. 3095 3096Example: 3097 3098.. code-block:: c 3099 3100 unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED); 3101 3102The third argument is one of the memory ordering specifiers ``__ATOMIC_RELAXED``, 3103``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, ``__ATOMIC_RELEASE``, 3104``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics. 3105 3106In terms or aquire-release ordering barriers these two operations are always 3107considered as operations with *load-store* semantics, even when the original value 3108is not actually modified after comparison. 3109 3110.. _langext-__c11_atomic: 3111 3112__c11_atomic builtins 3113--------------------- 3114 3115Clang provides a set of builtins which are intended to be used to implement 3116C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the 3117``_explicit`` form of the corresponding C11 operation, and are named with a 3118``__c11_`` prefix. The supported operations, and the differences from 3119the corresponding C11 operations, are: 3120 3121* ``__c11_atomic_init`` 3122* ``__c11_atomic_thread_fence`` 3123* ``__c11_atomic_signal_fence`` 3124* ``__c11_atomic_is_lock_free`` (The argument is the size of the 3125 ``_Atomic(...)`` object, instead of its address) 3126* ``__c11_atomic_store`` 3127* ``__c11_atomic_load`` 3128* ``__c11_atomic_exchange`` 3129* ``__c11_atomic_compare_exchange_strong`` 3130* ``__c11_atomic_compare_exchange_weak`` 3131* ``__c11_atomic_fetch_add`` 3132* ``__c11_atomic_fetch_sub`` 3133* ``__c11_atomic_fetch_and`` 3134* ``__c11_atomic_fetch_or`` 3135* ``__c11_atomic_fetch_xor`` 3136* ``__c11_atomic_fetch_nand`` (Nand is not presented in ``<stdatomic.h>``) 3137* ``__c11_atomic_fetch_max`` 3138* ``__c11_atomic_fetch_min`` 3139 3140The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, 3141``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are 3142provided, with values corresponding to the enumerators of C11's 3143``memory_order`` enumeration. 3144 3145(Note that Clang additionally provides GCC-compatible ``__atomic_*`` 3146builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.0 3147atomic builtins are an explicit form of the corresponding OpenCL 2.0 3148builtin function, and are named with a ``__opencl_`` prefix. The macros 3149``__OPENCL_MEMORY_SCOPE_WORK_ITEM``, ``__OPENCL_MEMORY_SCOPE_WORK_GROUP``, 3150``__OPENCL_MEMORY_SCOPE_DEVICE``, ``__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES``, 3151and ``__OPENCL_MEMORY_SCOPE_SUB_GROUP`` are provided, with values 3152corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.) 3153 3154Low-level ARM exclusive memory builtins 3155--------------------------------------- 3156 3157Clang provides overloaded builtins giving direct access to the three key ARM 3158instructions for implementing atomic operations. 3159 3160.. code-block:: c 3161 3162 T __builtin_arm_ldrex(const volatile T *addr); 3163 T __builtin_arm_ldaex(const volatile T *addr); 3164 int __builtin_arm_strex(T val, volatile T *addr); 3165 int __builtin_arm_stlex(T val, volatile T *addr); 3166 void __builtin_arm_clrex(void); 3167 3168The types ``T`` currently supported are: 3169 3170* Integer types with width at most 64 bits (or 128 bits on AArch64). 3171* Floating-point types 3172* Pointer types. 3173 3174Note that the compiler does not guarantee it will not insert stores which clear 3175the exclusive monitor in between an ``ldrex`` type operation and its paired 3176``strex``. In practice this is only usually a risk when the extra store is on 3177the same cache line as the variable being modified and Clang will only insert 3178stack stores on its own, so it is best not to use these operations on variables 3179with automatic storage duration. 3180 3181Also, loads and stores may be implicit in code written between the ``ldrex`` and 3182``strex``. Clang will not necessarily mitigate the effects of these either, so 3183care should be exercised. 3184 3185For these reasons the higher level atomic primitives should be preferred where 3186possible. 3187 3188Non-temporal load/store builtins 3189-------------------------------- 3190 3191Clang provides overloaded builtins allowing generation of non-temporal memory 3192accesses. 3193 3194.. code-block:: c 3195 3196 T __builtin_nontemporal_load(T *addr); 3197 void __builtin_nontemporal_store(T value, T *addr); 3198 3199The types ``T`` currently supported are: 3200 3201* Integer types. 3202* Floating-point types. 3203* Vector types. 3204 3205Note that the compiler does not guarantee that non-temporal loads or stores 3206will be used. 3207 3208C++ Coroutines support builtins 3209-------------------------------- 3210 3211.. warning:: 3212 This is a work in progress. Compatibility across Clang/LLVM releases is not 3213 guaranteed. 3214 3215Clang provides experimental builtins to support C++ Coroutines as defined by 3216https://wg21.link/P0057. The following four are intended to be used by the 3217standard library to implement the ``std::coroutine_handle`` type. 3218 3219**Syntax**: 3220 3221.. code-block:: c 3222 3223 void __builtin_coro_resume(void *addr); 3224 void __builtin_coro_destroy(void *addr); 3225 bool __builtin_coro_done(void *addr); 3226 void *__builtin_coro_promise(void *addr, int alignment, bool from_promise) 3227 3228**Example of use**: 3229 3230.. code-block:: c++ 3231 3232 template <> struct coroutine_handle<void> { 3233 void resume() const { __builtin_coro_resume(ptr); } 3234 void destroy() const { __builtin_coro_destroy(ptr); } 3235 bool done() const { return __builtin_coro_done(ptr); } 3236 // ... 3237 protected: 3238 void *ptr; 3239 }; 3240 3241 template <typename Promise> struct coroutine_handle : coroutine_handle<> { 3242 // ... 3243 Promise &promise() const { 3244 return *reinterpret_cast<Promise *>( 3245 __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false)); 3246 } 3247 static coroutine_handle from_promise(Promise &promise) { 3248 coroutine_handle p; 3249 p.ptr = __builtin_coro_promise(&promise, alignof(Promise), 3250 /*from-promise=*/true); 3251 return p; 3252 } 3253 }; 3254 3255 3256Other coroutine builtins are either for internal clang use or for use during 3257development of the coroutine feature. See `Coroutines in LLVM 3258<https://llvm.org/docs/Coroutines.html#intrinsics>`_ for 3259more information on their semantics. Note that builtins matching the intrinsics 3260that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc, 3261llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to 3262an appropriate value during the emission. 3263 3264**Syntax**: 3265 3266.. code-block:: c 3267 3268 size_t __builtin_coro_size() 3269 void *__builtin_coro_frame() 3270 void *__builtin_coro_free(void *coro_frame) 3271 3272 void *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts) 3273 bool __builtin_coro_alloc() 3274 void *__builtin_coro_begin(void *memory) 3275 void __builtin_coro_end(void *coro_frame, bool unwind) 3276 char __builtin_coro_suspend(bool final) 3277 3278Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM 3279automatically will insert one if the first argument to `llvm.coro.suspend` is 3280token `none`. If a user calls `__builin_suspend`, clang will insert `token none` 3281as the first argument to the intrinsic. 3282 3283Source location builtins 3284------------------------ 3285 3286Clang provides experimental builtins to support C++ standard library implementation 3287of ``std::experimental::source_location`` as specified in http://wg21.link/N4600. 3288With the exception of ``__builtin_COLUMN``, these builtins are also implemented by 3289GCC. 3290 3291**Syntax**: 3292 3293.. code-block:: c 3294 3295 const char *__builtin_FILE(); 3296 const char *__builtin_FUNCTION(); 3297 unsigned __builtin_LINE(); 3298 unsigned __builtin_COLUMN(); // Clang only 3299 3300**Example of use**: 3301 3302.. code-block:: c++ 3303 3304 void my_assert(bool pred, int line = __builtin_LINE(), // Captures line of caller 3305 const char* file = __builtin_FILE(), 3306 const char* function = __builtin_FUNCTION()) { 3307 if (pred) return; 3308 printf("%s:%d assertion failed in function %s\n", file, line, function); 3309 std::abort(); 3310 } 3311 3312 struct MyAggregateType { 3313 int x; 3314 int line = __builtin_LINE(); // captures line where aggregate initialization occurs 3315 }; 3316 static_assert(MyAggregateType{42}.line == __LINE__); 3317 3318 struct MyClassType { 3319 int line = __builtin_LINE(); // captures line of the constructor used during initialization 3320 constexpr MyClassType(int) { assert(line == __LINE__); } 3321 }; 3322 3323**Description**: 3324 3325The builtins ``__builtin_LINE``, ``__builtin_FUNCTION``, and ``__builtin_FILE`` return 3326the values, at the "invocation point", for ``__LINE__``, ``__FUNCTION__``, and 3327``__FILE__`` respectively. These builtins are constant expressions. 3328 3329When the builtins appear as part of a default function argument the invocation 3330point is the location of the caller. When the builtins appear as part of a 3331default member initializer, the invocation point is the location of the 3332constructor or aggregate initialization used to create the object. Otherwise 3333the invocation point is the same as the location of the builtin. 3334 3335When the invocation point of ``__builtin_FUNCTION`` is not a function scope the 3336empty string is returned. 3337 3338Alignment builtins 3339------------------ 3340Clang provides builtins to support checking and adjusting alignment of 3341pointers and integers. 3342These builtins can be used to avoid relying on implementation-defined behavior 3343of arithmetic on integers derived from pointers. 3344Additionally, these builtins retain type information and, unlike bitwise 3345arithmetic, they can perform semantic checking on the alignment value. 3346 3347**Syntax**: 3348 3349.. code-block:: c 3350 3351 Type __builtin_align_up(Type value, size_t alignment); 3352 Type __builtin_align_down(Type value, size_t alignment); 3353 bool __builtin_is_aligned(Type value, size_t alignment); 3354 3355 3356**Example of use**: 3357 3358.. code-block:: c++ 3359 3360 char* global_alloc_buffer; 3361 void* my_aligned_allocator(size_t alloc_size, size_t alignment) { 3362 char* result = __builtin_align_up(global_alloc_buffer, alignment); 3363 // result now contains the value of global_alloc_buffer rounded up to the 3364 // next multiple of alignment. 3365 global_alloc_buffer = result + alloc_size; 3366 return result; 3367 } 3368 3369 void* get_start_of_page(void* ptr) { 3370 return __builtin_align_down(ptr, PAGE_SIZE); 3371 } 3372 3373 void example(char* buffer) { 3374 if (__builtin_is_aligned(buffer, 64)) { 3375 do_fast_aligned_copy(buffer); 3376 } else { 3377 do_unaligned_copy(buffer); 3378 } 3379 } 3380 3381 // In addition to pointers, the builtins can also be used on integer types 3382 // and are evaluatable inside constant expressions. 3383 static_assert(__builtin_align_up(123, 64) == 128, ""); 3384 static_assert(__builtin_align_down(123u, 64) == 64u, ""); 3385 static_assert(!__builtin_is_aligned(123, 64), ""); 3386 3387 3388**Description**: 3389 3390The builtins ``__builtin_align_up``, ``__builtin_align_down``, return their 3391first argument aligned up/down to the next multiple of the second argument. 3392If the value is already sufficiently aligned, it is returned unchanged. 3393The builtin ``__builtin_is_aligned`` returns whether the first argument is 3394aligned to a multiple of the second argument. 3395All of these builtins expect the alignment to be expressed as a number of bytes. 3396 3397These builtins can be used for all integer types as well as (non-function) 3398pointer types. For pointer types, these builtins operate in terms of the integer 3399address of the pointer and return a new pointer of the same type (including 3400qualifiers such as ``const``) with an adjusted address. 3401When aligning pointers up or down, the resulting value must be within the same 3402underlying allocation or one past the end (see C17 6.5.6p8, C++ [expr.add]). 3403This means that arbitrary integer values stored in pointer-type variables must 3404not be passed to these builtins. For those use cases, the builtins can still be 3405used, but the operation must be performed on the pointer cast to ``uintptr_t``. 3406 3407If Clang can determine that the alignment is not a power of two at compile time, 3408it will result in a compilation failure. If the alignment argument is not a 3409power of two at run time, the behavior of these builtins is undefined. 3410 3411Non-standard C++11 Attributes 3412============================= 3413 3414Clang's non-standard C++11 attributes live in the ``clang`` attribute 3415namespace. 3416 3417Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which 3418are accepted with the ``__attribute__((foo))`` syntax are also accepted as 3419``[[gnu::foo]]``. This only extends to attributes which are specified by GCC 3420(see the list of `GCC function attributes 3421<https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable 3422attributes <https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and 3423`GCC type attributes 3424<https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC 3425implementation, these attributes must appertain to the *declarator-id* in a 3426declaration, which means they must go either at the start of the declaration or 3427immediately after the name being declared. 3428 3429For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and 3430also applies the GNU ``noreturn`` attribute to ``f``. 3431 3432.. code-block:: c++ 3433 3434 [[gnu::unused]] int a, f [[gnu::noreturn]] (); 3435 3436Target-Specific Extensions 3437========================== 3438 3439Clang supports some language features conditionally on some targets. 3440 3441ARM/AArch64 Language Extensions 3442------------------------------- 3443 3444Memory Barrier Intrinsics 3445^^^^^^^^^^^^^^^^^^^^^^^^^ 3446Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined 3447in the `ARM C Language Extensions Release 2.0 3448<http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053c/IHI0053C_acle_2_0.pdf>`_. 3449Note that these intrinsics are implemented as motion barriers that block 3450reordering of memory accesses and side effect instructions. Other instructions 3451like simple arithmetic may be reordered around the intrinsic. If you expect to 3452have no reordering at all, use inline assembly instead. 3453 3454X86/X86-64 Language Extensions 3455------------------------------ 3456 3457The X86 backend has these language extensions: 3458 3459Memory references to specified segments 3460^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3461 3462Annotating a pointer with address space #256 causes it to be code generated 3463relative to the X86 GS segment register, address space #257 causes it to be 3464relative to the X86 FS segment, and address space #258 causes it to be 3465relative to the X86 SS segment. Note that this is a very very low-level 3466feature that should only be used if you know what you're doing (for example in 3467an OS kernel). 3468 3469Here is an example: 3470 3471.. code-block:: c++ 3472 3473 #define GS_RELATIVE __attribute__((address_space(256))) 3474 int foo(int GS_RELATIVE *P) { 3475 return *P; 3476 } 3477 3478Which compiles to (on X86-32): 3479 3480.. code-block:: gas 3481 3482 _foo: 3483 movl 4(%esp), %eax 3484 movl %gs:(%eax), %eax 3485 ret 3486 3487You can also use the GCC compatibility macros ``__seg_fs`` and ``__seg_gs`` for 3488the same purpose. The preprocessor symbols ``__SEG_FS`` and ``__SEG_GS`` 3489indicate their support. 3490 3491PowerPC Language Extensions 3492--------------------------- 3493 3494Set the Floating Point Rounding Mode 3495^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3496PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set 3497the floating point rounding mode. This function will use the least significant 3498two bits of integer argument to set the floating point rounding mode. 3499 3500.. code-block:: c++ 3501 3502 double __builtin_setrnd(int mode); 3503 3504The effective values for mode are: 3505 3506 - 0 - round to nearest 3507 - 1 - round to zero 3508 - 2 - round to +infinity 3509 - 3 - round to -infinity 3510 3511Note that the mode argument will modulo 4, so if the integer argument is greater 3512than 3, it will only use the least significant two bits of the mode. 3513Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``. 3514 3515PowerPC cache builtins 3516^^^^^^^^^^^^^^^^^^^^^^ 3517 3518The PowerPC architecture specifies instructions implementing cache operations. 3519Clang provides builtins that give direct programmer access to these cache 3520instructions. 3521 3522Currently the following builtins are implemented in clang: 3523 3524``__builtin_dcbf`` copies the contents of a modified block from the data cache 3525to main memory and flushes the copy from the data cache. 3526 3527**Syntax**: 3528 3529.. code-block:: c 3530 3531 void __dcbf(const void* addr); /* Data Cache Block Flush */ 3532 3533**Example of Use**: 3534 3535.. code-block:: c 3536 3537 int a = 1; 3538 __builtin_dcbf (&a); 3539 3540Extensions for Static Analysis 3541============================== 3542 3543Clang supports additional attributes that are useful for documenting program 3544invariants and rules for static analysis tools, such as the `Clang Static 3545Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented 3546in the analyzer's `list of source-level annotations 3547<https://clang-analyzer.llvm.org/annotations.html>`_. 3548 3549 3550Extensions for Dynamic Analysis 3551=============================== 3552 3553Use ``__has_feature(address_sanitizer)`` to check if the code is being built 3554with :doc:`AddressSanitizer`. 3555 3556Use ``__has_feature(thread_sanitizer)`` to check if the code is being built 3557with :doc:`ThreadSanitizer`. 3558 3559Use ``__has_feature(memory_sanitizer)`` to check if the code is being built 3560with :doc:`MemorySanitizer`. 3561 3562Use ``__has_feature(safe_stack)`` to check if the code is being built 3563with :doc:`SafeStack`. 3564 3565 3566Extensions for selectively disabling optimization 3567================================================= 3568 3569Clang provides a mechanism for selectively disabling optimizations in functions 3570and methods. 3571 3572To disable optimizations in a single function definition, the GNU-style or C++11 3573non-standard attribute ``optnone`` can be used. 3574 3575.. code-block:: c++ 3576 3577 // The following functions will not be optimized. 3578 // GNU-style attribute 3579 __attribute__((optnone)) int foo() { 3580 // ... code 3581 } 3582 // C++11 attribute 3583 [[clang::optnone]] int bar() { 3584 // ... code 3585 } 3586 3587To facilitate disabling optimization for a range of function definitions, a 3588range-based pragma is provided. Its syntax is ``#pragma clang optimize`` 3589followed by ``off`` or ``on``. 3590 3591All function definitions in the region between an ``off`` and the following 3592``on`` will be decorated with the ``optnone`` attribute unless doing so would 3593conflict with explicit attributes already present on the function (e.g. the 3594ones that control inlining). 3595 3596.. code-block:: c++ 3597 3598 #pragma clang optimize off 3599 // This function will be decorated with optnone. 3600 int foo() { 3601 // ... code 3602 } 3603 3604 // optnone conflicts with always_inline, so bar() will not be decorated. 3605 __attribute__((always_inline)) int bar() { 3606 // ... code 3607 } 3608 #pragma clang optimize on 3609 3610If no ``on`` is found to close an ``off`` region, the end of the region is the 3611end of the compilation unit. 3612 3613Note that a stray ``#pragma clang optimize on`` does not selectively enable 3614additional optimizations when compiling at low optimization levels. This feature 3615can only be used to selectively disable optimizations. 3616 3617The pragma has an effect on functions only at the point of their definition; for 3618function templates, this means that the state of the pragma at the point of an 3619instantiation is not necessarily relevant. Consider the following example: 3620 3621.. code-block:: c++ 3622 3623 template<typename T> T twice(T t) { 3624 return 2 * t; 3625 } 3626 3627 #pragma clang optimize off 3628 template<typename T> T thrice(T t) { 3629 return 3 * t; 3630 } 3631 3632 int container(int a, int b) { 3633 return twice(a) + thrice(b); 3634 } 3635 #pragma clang optimize on 3636 3637In this example, the definition of the template function ``twice`` is outside 3638the pragma region, whereas the definition of ``thrice`` is inside the region. 3639The ``container`` function is also in the region and will not be optimized, but 3640it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of 3641these two instantiations, ``twice`` will be optimized (because its definition 3642was outside the region) and ``thrice`` will not be optimized. 3643 3644Extensions for loop hint optimizations 3645====================================== 3646 3647The ``#pragma clang loop`` directive is used to specify hints for optimizing the 3648subsequent for, while, do-while, or c++11 range-based for loop. The directive 3649provides options for vectorization, interleaving, predication, unrolling and 3650distribution. Loop hints can be specified before any loop and will be ignored if 3651the optimization is not safe to apply. 3652 3653There are loop hints that control transformations (e.g. vectorization, loop 3654unrolling) and there are loop hints that set transformation options (e.g. 3655``vectorize_width``, ``unroll_count``). Pragmas setting transformation options 3656imply the transformation is enabled, as if it was enabled via the corresponding 3657transformation pragma (e.g. ``vectorize(enable)``). If the transformation is 3658disabled (e.g. ``vectorize(disable)``), that takes precedence over 3659transformations option pragmas implying that transformation. 3660 3661Vectorization, Interleaving, and Predication 3662-------------------------------------------- 3663 3664A vectorized loop performs multiple iterations of the original loop 3665in parallel using vector instructions. The instruction set of the target 3666processor determines which vector instructions are available and their vector 3667widths. This restricts the types of loops that can be vectorized. The vectorizer 3668automatically determines if the loop is safe and profitable to vectorize. A 3669vector instruction cost model is used to select the vector width. 3670 3671Interleaving multiple loop iterations allows modern processors to further 3672improve instruction-level parallelism (ILP) using advanced hardware features, 3673such as multiple execution units and out-of-order execution. The vectorizer uses 3674a cost model that depends on the register pressure and generated code size to 3675select the interleaving count. 3676 3677Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled 3678by ``interleave(enable)``. This is useful when compiling with ``-Os`` to 3679manually enable vectorization or interleaving. 3680 3681.. code-block:: c++ 3682 3683 #pragma clang loop vectorize(enable) 3684 #pragma clang loop interleave(enable) 3685 for(...) { 3686 ... 3687 } 3688 3689The vector width is specified by 3690``vectorize_width(_value_[, fixed|scalable])``, where _value_ is a positive 3691integer and the type of vectorization can be specified with an optional 3692second parameter. The default for the second parameter is 'fixed' and 3693refers to fixed width vectorization, whereas 'scalable' indicates the 3694compiler should use scalable vectors instead. Another use of vectorize_width 3695is ``vectorize_width(fixed|scalable)`` where the user can hint at the type 3696of vectorization to use without specifying the exact width. In both variants 3697of the pragma the vectorizer may decide to fall back on fixed width 3698vectorization if the target does not support scalable vectors. 3699 3700The interleave count is specified by ``interleave_count(_value_)``, where 3701_value_ is a positive integer. This is useful for specifying the optimal 3702width/count of the set of target architectures supported by your application. 3703 3704.. code-block:: c++ 3705 3706 #pragma clang loop vectorize_width(2) 3707 #pragma clang loop interleave_count(2) 3708 for(...) { 3709 ... 3710 } 3711 3712Specifying a width/count of 1 disables the optimization, and is equivalent to 3713``vectorize(disable)`` or ``interleave(disable)``. 3714 3715Vector predication is enabled by ``vectorize_predicate(enable)``, for example: 3716 3717.. code-block:: c++ 3718 3719 #pragma clang loop vectorize(enable) 3720 #pragma clang loop vectorize_predicate(enable) 3721 for(...) { 3722 ... 3723 } 3724 3725This predicates (masks) all instructions in the loop, which allows the scalar 3726remainder loop (the tail) to be folded into the main vectorized loop. This 3727might be more efficient when vector predication is efficiently supported by the 3728target platform. 3729 3730Loop Unrolling 3731-------------- 3732 3733Unrolling a loop reduces the loop control overhead and exposes more 3734opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling 3735eliminates the loop and replaces it with an enumerated sequence of loop 3736iterations. Full unrolling is only possible if the loop trip count is known at 3737compile time. Partial unrolling replicates the loop body within the loop and 3738reduces the trip count. 3739 3740If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the 3741loop if the trip count is known at compile time. If the fully unrolled code size 3742is greater than an internal limit the loop will be partially unrolled up to this 3743limit. If the trip count is not known at compile time the loop will be partially 3744unrolled with a heuristically chosen unroll factor. 3745 3746.. code-block:: c++ 3747 3748 #pragma clang loop unroll(enable) 3749 for(...) { 3750 ... 3751 } 3752 3753If ``unroll(full)`` is specified the unroller will attempt to fully unroll the 3754loop if the trip count is known at compile time identically to 3755``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled 3756if the loop count is not known at compile time. 3757 3758.. code-block:: c++ 3759 3760 #pragma clang loop unroll(full) 3761 for(...) { 3762 ... 3763 } 3764 3765The unroll count can be specified explicitly with ``unroll_count(_value_)`` where 3766_value_ is a positive integer. If this value is greater than the trip count the 3767loop will be fully unrolled. Otherwise the loop is partially unrolled subject 3768to the same code size limit as with ``unroll(enable)``. 3769 3770.. code-block:: c++ 3771 3772 #pragma clang loop unroll_count(8) 3773 for(...) { 3774 ... 3775 } 3776 3777Unrolling of a loop can be prevented by specifying ``unroll(disable)``. 3778 3779Loop unroll parameters can be controlled by options 3780`-mllvm -unroll-count=n` and `-mllvm -pragma-unroll-threshold=n`. 3781 3782Loop Distribution 3783----------------- 3784 3785Loop Distribution allows splitting a loop into multiple loops. This is 3786beneficial for example when the entire loop cannot be vectorized but some of the 3787resulting loops can. 3788 3789If ``distribute(enable))`` is specified and the loop has memory dependencies 3790that inhibit vectorization, the compiler will attempt to isolate the offending 3791operations into a new loop. This optimization is not enabled by default, only 3792loops marked with the pragma are considered. 3793 3794.. code-block:: c++ 3795 3796 #pragma clang loop distribute(enable) 3797 for (i = 0; i < N; ++i) { 3798 S1: A[i + 1] = A[i] + B[i]; 3799 S2: C[i] = D[i] * E[i]; 3800 } 3801 3802This loop will be split into two loops between statements S1 and S2. The 3803second loop containing S2 will be vectorized. 3804 3805Loop Distribution is currently not enabled by default in the optimizer because 3806it can hurt performance in some cases. For example, instruction-level 3807parallelism could be reduced by sequentializing the execution of the 3808statements S1 and S2 above. 3809 3810If Loop Distribution is turned on globally with 3811``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can 3812be used the disable it on a per-loop basis. 3813 3814Additional Information 3815---------------------- 3816 3817For convenience multiple loop hints can be specified on a single line. 3818 3819.. code-block:: c++ 3820 3821 #pragma clang loop vectorize_width(4) interleave_count(8) 3822 for(...) { 3823 ... 3824 } 3825 3826If an optimization cannot be applied any hints that apply to it will be ignored. 3827For example, the hint ``vectorize_width(4)`` is ignored if the loop is not 3828proven safe to vectorize. To identify and diagnose optimization issues use 3829`-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the 3830user guide for details. 3831 3832Extensions to specify floating-point flags 3833==================================================== 3834 3835The ``#pragma clang fp`` pragma allows floating-point options to be specified 3836for a section of the source code. This pragma can only appear at file scope or 3837at the start of a compound statement (excluding comments). When using within a 3838compound statement, the pragma is active within the scope of the compound 3839statement. 3840 3841Currently, the following settings can be controlled with this pragma: 3842 3843``#pragma clang fp reassociate`` allows control over the reassociation 3844of floating point expressions. When enabled, this pragma allows the expression 3845``x + (y + z)`` to be reassociated as ``(x + y) + z``. 3846Reassociation can also occur across multiple statements. 3847This pragma can be used to disable reassociation when it is otherwise 3848enabled for the translation unit with the ``-fassociative-math`` flag. 3849The pragma can take two values: ``on`` and ``off``. 3850 3851.. code-block:: c++ 3852 3853 float f(float x, float y, float z) 3854 { 3855 // Enable floating point reassociation across statements 3856 #pragma clang fp reassociate(on) 3857 float t = x + y; 3858 float v = t + z; 3859 } 3860 3861 3862``#pragma clang fp contract`` specifies whether the compiler should 3863contract a multiply and an addition (or subtraction) into a fused FMA 3864operation when supported by the target. 3865 3866The pragma can take three values: ``on``, ``fast`` and ``off``. The ``on`` 3867option is identical to using ``#pragma STDC FP_CONTRACT(ON)`` and it allows 3868fusion as specified the language standard. The ``fast`` option allows fusion 3869in cases when the language standard does not make this possible (e.g. across 3870statements in C). 3871 3872.. code-block:: c++ 3873 3874 for(...) { 3875 #pragma clang fp contract(fast) 3876 a = b[i] * c[i]; 3877 d[i] += a; 3878 } 3879 3880 3881The pragma can also be used with ``off`` which turns FP contraction off for a 3882section of the code. This can be useful when fast contraction is otherwise 3883enabled for the translation unit with the ``-ffp-contract=fast-honor-pragmas`` flag. 3884Note that ``-ffp-contract=fast`` will override pragmas to fuse multiply and 3885addition across statements regardless of any controlling pragmas. 3886 3887``#pragma clang fp exceptions`` specifies floating point exception behavior. It 3888may take one the the values: ``ignore``, ``maytrap`` or ``strict``. Meaning of 3889these values is same as for `constrained floating point intrinsics <http://llvm.org/docs/LangRef.html#constrained-floating-point-intrinsics>`_. 3890 3891.. code-block:: c++ 3892 3893 { 3894 // Preserve floating point exceptions 3895 #pragma clang fp exceptions(strict) 3896 z = x + y; 3897 if (fetestexcept(FE_OVERFLOW)) 3898 ... 3899 } 3900 3901A ``#pragma clang fp`` pragma may contain any number of options: 3902 3903.. code-block:: c++ 3904 3905 void func(float *dest, float a, float b) { 3906 #pragma clang fp exceptions(maytrap) contract(fast) reassociate(on) 3907 ... 3908 } 3909 3910 3911The ``#pragma float_control`` pragma allows precise floating-point 3912semantics and floating-point exception behavior to be specified 3913for a section of the source code. This pragma can only appear at file or 3914namespace scope, within a language linkage specification or at the start of a 3915compound statement (excluding comments). When used within a compound statement, 3916the pragma is active within the scope of the compound statement. This pragma 3917is modeled after a Microsoft pragma with the same spelling and syntax. For 3918pragmas specified at file or namespace scope, or within a language linkage 3919specification, a stack is supported so that the ``pragma float_control`` 3920settings can be pushed or popped. 3921 3922When ``pragma float_control(precise, on)`` is enabled, the section of code 3923governed by the pragma uses precise floating point semantics, effectively 3924``-ffast-math`` is disabled and ``-ffp-contract=on`` 3925(fused multiply add) is enabled. 3926 3927When ``pragma float_control(except, on)`` is enabled, the section of code 3928governed by the pragma behaves as though the command-line option 3929``-ffp-exception-behavior=strict`` is enabled, 3930when ``pragma float_control(except, off)`` is enabled, the section of code 3931governed by the pragma behaves as though the command-line option 3932``-ffp-exception-behavior=ignore`` is enabled. 3933 3934The full syntax this pragma supports is 3935``float_control(except|precise, on|off [, push])`` and 3936``float_control(push|pop)``. 3937The ``push`` and ``pop`` forms, including using ``push`` as the optional 3938third argument, can only occur at file scope. 3939 3940.. code-block:: c++ 3941 3942 for(...) { 3943 // This block will be compiled with -fno-fast-math and -ffp-contract=on 3944 #pragma float_control(precise, on) 3945 a = b[i] * c[i] + e; 3946 } 3947 3948Specifying an attribute for multiple declarations (#pragma clang attribute) 3949=========================================================================== 3950 3951The ``#pragma clang attribute`` directive can be used to apply an attribute to 3952multiple declarations. The ``#pragma clang attribute push`` variation of the 3953directive pushes a new "scope" of ``#pragma clang attribute`` that attributes 3954can be added to. The ``#pragma clang attribute (...)`` variation adds an 3955attribute to that scope, and the ``#pragma clang attribute pop`` variation pops 3956the scope. You can also use ``#pragma clang attribute push (...)``, which is a 3957shorthand for when you want to add one attribute to a new scope. Multiple push 3958directives can be nested inside each other. 3959 3960The attributes that are used in the ``#pragma clang attribute`` directives 3961can be written using the GNU-style syntax: 3962 3963.. code-block:: c++ 3964 3965 #pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function) 3966 3967 void function(); // The function now has the annotate("custom") attribute 3968 3969 #pragma clang attribute pop 3970 3971The attributes can also be written using the C++11 style syntax: 3972 3973.. code-block:: c++ 3974 3975 #pragma clang attribute push ([[noreturn]], apply_to = function) 3976 3977 void function(); // The function now has the [[noreturn]] attribute 3978 3979 #pragma clang attribute pop 3980 3981The ``__declspec`` style syntax is also supported: 3982 3983.. code-block:: c++ 3984 3985 #pragma clang attribute push (__declspec(dllexport), apply_to = function) 3986 3987 void function(); // The function now has the __declspec(dllexport) attribute 3988 3989 #pragma clang attribute pop 3990 3991A single push directive accepts only one attribute regardless of the syntax 3992used. 3993 3994Because multiple push directives can be nested, if you're writing a macro that 3995expands to ``_Pragma("clang attribute")`` it's good hygiene (though not 3996required) to add a namespace to your push/pop directives. A pop directive with a 3997namespace will pop the innermost push that has that same namespace. This will 3998ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note 3999that an ``pop`` without a namespace will pop the innermost ``push`` without a 4000namespace. ``push``es with a namespace can only be popped by ``pop`` with the 4001same namespace. For instance: 4002 4003.. code-block:: c++ 4004 4005 #define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)") 4006 #define ASSUME_NORETURN_END _Pragma("clang attribute AssumeNoreturn.pop") 4007 4008 #define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)") 4009 #define ASSUME_UNAVAILABLE_END _Pragma("clang attribute Unavailable.pop") 4010 4011 4012 ASSUME_NORETURN_BEGIN 4013 ASSUME_UNAVAILABLE_BEGIN 4014 void function(); // function has [[noreturn]] and __attribute__((unavailable)) 4015 ASSUME_NORETURN_END 4016 void other_function(); // function has __attribute__((unavailable)) 4017 ASSUME_UNAVAILABLE_END 4018 4019Without the namespaces on the macros, ``other_function`` will be annotated with 4020``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like 4021a contrived example, but its very possible for this kind of situation to appear 4022in real code if the pragmas are spread out across a large file. You can test if 4023your version of clang supports namespaces on ``#pragma clang attribute`` with 4024``__has_extension(pragma_clang_attribute_namespaces)``. 4025 4026Subject Match Rules 4027------------------- 4028 4029The set of declarations that receive a single attribute from the attribute stack 4030depends on the subject match rules that were specified in the pragma. Subject 4031match rules are specified after the attribute. The compiler expects an 4032identifier that corresponds to the subject set specifier. The ``apply_to`` 4033specifier is currently the only supported subject set specifier. It allows you 4034to specify match rules that form a subset of the attribute's allowed subject 4035set, i.e. the compiler doesn't require all of the attribute's subjects. For 4036example, an attribute like ``[[nodiscard]]`` whose subject set includes 4037``enum``, ``record`` and ``hasType(functionType)``, requires the presence of at 4038least one of these rules after ``apply_to``: 4039 4040.. code-block:: c++ 4041 4042 #pragma clang attribute push([[nodiscard]], apply_to = enum) 4043 4044 enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]] 4045 4046 struct Record1 { }; // The struct will *not* receive [[nodiscard]] 4047 4048 #pragma clang attribute pop 4049 4050 #pragma clang attribute push([[nodiscard]], apply_to = any(record, enum)) 4051 4052 enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]] 4053 4054 struct Record2 { }; // The struct *will* receive [[nodiscard]] 4055 4056 #pragma clang attribute pop 4057 4058 // This is an error, since [[nodiscard]] can't be applied to namespaces: 4059 #pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace)) 4060 4061 #pragma clang attribute pop 4062 4063Multiple match rules can be specified using the ``any`` match rule, as shown 4064in the example above. The ``any`` rule applies attributes to all declarations 4065that are matched by at least one of the rules in the ``any``. It doesn't nest 4066and can't be used inside the other match rules. Redundant match rules or rules 4067that conflict with one another should not be used inside of ``any``. Failing to 4068specify a rule within the ``any`` rule results in an error. 4069 4070Clang supports the following match rules: 4071 4072- ``function``: Can be used to apply attributes to functions. This includes C++ 4073 member functions, static functions, operators, and constructors/destructors. 4074 4075- ``function(is_member)``: Can be used to apply attributes to C++ member 4076 functions. This includes members like static functions, operators, and 4077 constructors/destructors. 4078 4079- ``hasType(functionType)``: Can be used to apply attributes to functions, C++ 4080 member functions, and variables/fields whose type is a function pointer. It 4081 does not apply attributes to Objective-C methods or blocks. 4082 4083- ``type_alias``: Can be used to apply attributes to ``typedef`` declarations 4084 and C++11 type aliases. 4085 4086- ``record``: Can be used to apply attributes to ``struct``, ``class``, and 4087 ``union`` declarations. 4088 4089- ``record(unless(is_union))``: Can be used to apply attributes only to 4090 ``struct`` and ``class`` declarations. 4091 4092- ``enum``: Can be be used to apply attributes to enumeration declarations. 4093 4094- ``enum_constant``: Can be used to apply attributes to enumerators. 4095 4096- ``variable``: Can be used to apply attributes to variables, including 4097 local variables, parameters, global variables, and static member variables. 4098 It does not apply attributes to instance member variables or Objective-C 4099 ivars. 4100 4101- ``variable(is_thread_local)``: Can be used to apply attributes to thread-local 4102 variables only. 4103 4104- ``variable(is_global)``: Can be used to apply attributes to global variables 4105 only. 4106 4107- ``variable(is_local)``: Can be used to apply attributes to local variables 4108 only. 4109 4110- ``variable(is_parameter)``: Can be used to apply attributes to parameters 4111 only. 4112 4113- ``variable(unless(is_parameter))``: Can be used to apply attributes to all 4114 the variables that are not parameters. 4115 4116- ``field``: Can be used to apply attributes to non-static member variables 4117 in a record. This includes Objective-C ivars. 4118 4119- ``namespace``: Can be used to apply attributes to ``namespace`` declarations. 4120 4121- ``objc_interface``: Can be used to apply attributes to ``@interface`` 4122 declarations. 4123 4124- ``objc_protocol``: Can be used to apply attributes to ``@protocol`` 4125 declarations. 4126 4127- ``objc_category``: Can be used to apply attributes to category declarations, 4128 including class extensions. 4129 4130- ``objc_method``: Can be used to apply attributes to Objective-C methods, 4131 including instance and class methods. Implicit methods like implicit property 4132 getters and setters do not receive the attribute. 4133 4134- ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C 4135 instance methods. 4136 4137- ``objc_property``: Can be used to apply attributes to ``@property`` 4138 declarations. 4139 4140- ``block``: Can be used to apply attributes to block declarations. This does 4141 not include variables/fields of block pointer type. 4142 4143The use of ``unless`` in match rules is currently restricted to a strict set of 4144sub-rules that are used by the supported attributes. That means that even though 4145``variable(unless(is_parameter))`` is a valid match rule, 4146``variable(unless(is_thread_local))`` is not. 4147 4148Supported Attributes 4149-------------------- 4150 4151Not all attributes can be used with the ``#pragma clang attribute`` directive. 4152Notably, statement attributes like ``[[fallthrough]]`` or type attributes 4153like ``address_space`` aren't supported by this directive. You can determine 4154whether or not an attribute is supported by the pragma by referring to the 4155:doc:`individual documentation for that attribute <AttributeReference>`. 4156 4157The attributes are applied to all matching declarations individually, even when 4158the attribute is semantically incorrect. The attributes that aren't applied to 4159any declaration are not verified semantically. 4160 4161Specifying section names for global objects (#pragma clang section) 4162=================================================================== 4163 4164The ``#pragma clang section`` directive provides a means to assign section-names 4165to global variables, functions and static variables. 4166 4167The section names can be specified as: 4168 4169.. code-block:: c++ 4170 4171 #pragma clang section bss="myBSS" data="myData" rodata="myRodata" relro="myRelro" text="myText" 4172 4173The section names can be reverted back to default name by supplying an empty 4174string to the section kind, for example: 4175 4176.. code-block:: c++ 4177 4178 #pragma clang section bss="" data="" text="" rodata="" relro="" 4179 4180The ``#pragma clang section`` directive obeys the following rules: 4181 4182* The pragma applies to all global variable, statics and function declarations 4183 from the pragma to the end of the translation unit. 4184 4185* The pragma clang section is enabled automatically, without need of any flags. 4186 4187* This feature is only defined to work sensibly for ELF targets. 4188 4189* If section name is specified through _attribute_((section("myname"))), then 4190 the attribute name gains precedence. 4191 4192* Global variables that are initialized to zero will be placed in the named 4193 bss section, if one is present. 4194 4195* The ``#pragma clang section`` directive does not does try to infer section-kind 4196 from the name. For example, naming a section "``.bss.mySec``" does NOT mean 4197 it will be a bss section name. 4198 4199* The decision about which section-kind applies to each global is taken in the back-end. 4200 Once the section-kind is known, appropriate section name, as specified by the user using 4201 ``#pragma clang section`` directive, is applied to that global. 4202 4203Specifying Linker Options on ELF Targets 4204======================================== 4205 4206The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets. 4207The second parameter is the library name (without the traditional Unix prefix of 4208``lib``). This allows you to provide an implicit link of dependent libraries. 4209 4210Evaluating Object Size Dynamically 4211================================== 4212 4213Clang supports the builtin ``__builtin_dynamic_object_size``, the semantics are 4214the same as GCC's ``__builtin_object_size`` (which Clang also supports), but 4215``__builtin_dynamic_object_size`` can evaluate the object's size at runtime. 4216``__builtin_dynamic_object_size`` is meant to be used as a drop-in replacement 4217for ``__builtin_object_size`` in libraries that support it. 4218 4219For instance, here is a program that ``__builtin_dynamic_object_size`` will make 4220safer: 4221 4222.. code-block:: c 4223 4224 void copy_into_buffer(size_t size) { 4225 char* buffer = malloc(size); 4226 strlcpy(buffer, "some string", strlen("some string")); 4227 // Previous line preprocesses to: 4228 // __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buffer, 0)) 4229 } 4230 4231Since the size of ``buffer`` can't be known at compile time, Clang will fold 4232``__builtin_object_size(buffer, 0)`` into ``-1``. However, if this was written 4233as ``__builtin_dynamic_object_size(buffer, 0)``, Clang will fold it into 4234``size``, providing some extra runtime safety. 4235 4236Deprecating Macros 4237================== 4238 4239Clang supports the pragma ``#pragma clang deprecated``, which can be used to 4240provide deprecation warnings for macro uses. For example: 4241 4242.. code-block:: c 4243 4244 #define MIN(x, y) x < y ? x : y 4245 #pragma clang deprecated(MIN, "use std::min instead") 4246 4247 void min(int a, int b) { 4248 return MIN(a, b); // warning: MIN is deprecated: use std::min instead 4249 } 4250 4251``#pragma clang deprecated`` should be preferred for this purpose over 4252``#pragma GCC warning`` because the warning can be controlled with 4253``-Wdeprecated``. 4254 4255Restricted Expansion Macros 4256=========================== 4257 4258Clang supports the pragma ``#pragma clang restrict_expansion``, which can be 4259used restrict macro expansion in headers. This can be valuable when providing 4260headers with ABI stability requirements. Any expansion of the annotated macro 4261processed by the preprocessor after the ``#pragma`` annotation will log a 4262warning. Redefining the macro or undefining the macro will not be diagnosed, nor 4263will expansion of the macro within the main source file. For example: 4264 4265.. code-block:: c 4266 4267 #define TARGET_ARM 1 4268 #pragma clang restrict_expansion(TARGET_ARM, "<reason>") 4269 4270 /// Foo.h 4271 struct Foo { 4272 #if TARGET_ARM // warning: TARGET_ARM is marked unsafe in headers: <reason> 4273 uint32_t X; 4274 #else 4275 uint64_t X; 4276 #endif 4277 }; 4278 4279 /// main.c 4280 #include "foo.h" 4281 #if TARGET_ARM // No warning in main source file 4282 X_TYPE uint32_t 4283 #else 4284 X_TYPE uint64_t 4285 #endif 4286 4287This warning is controlled by ``-Wpedantic-macros``. 4288 4289Final Macros 4290============ 4291 4292Clang supports the pragma ``#pragma clang final``, which can be used to 4293mark macros as final, meaning they cannot be undef'd or re-defined. For example: 4294 4295.. code-block:: c 4296 4297 #define FINAL_MACRO 1 4298 #pragma clang final(FINAL_MACRO) 4299 4300 #define FINAL_MACRO // warning: FINAL_MACRO is marked final and should not be redefined 4301 #undef FINAL_MACRO // warning: FINAL_MACRO is marked final and should not be undefined 4302 4303This is useful for enforcing system-provided macros that should not be altered 4304in user headers or code. This is controlled by ``-Wpedantic-macros``. Final 4305macros will always warn on redefinition, including situations with identical 4306bodies and in system headers. 4307 4308Line Control 4309============ 4310 4311Clang supports an extension for source line control, which takes the 4312form of a preprocessor directive starting with an unsigned integral 4313constant. In addition to the standard ``#line`` directive, this form 4314allows control of an include stack and header file type, which is used 4315in issuing diagnostics. These lines are emitted in preprocessed 4316output. 4317 4318.. code-block:: c 4319 4320 # <line:number> <filename:string> <header-type:numbers> 4321 4322The filename is optional, and if unspecified indicates no change in 4323source filename. The header-type is an optional, whitespace-delimited, 4324sequence of magic numbers as follows. 4325 4326* ``1:`` Push the current source file name onto the include stack and 4327 enter a new file. 4328 4329* ``2``: Pop the include stack and return to the specified file. If 4330 the filename is ``""``, the name popped from the include stack is 4331 used. Otherwise there is no requirement that the specified filename 4332 matches the current source when originally pushed. 4333 4334* ``3``: Enter a system-header region. System headers often contain 4335 implementation-specific source that would normally emit a diagnostic. 4336 4337* ``4``: Enter an implicit ``extern "C"`` region. This is not required on 4338 modern systems where system headers are C++-aware. 4339 4340At most a single ``1`` or ``2`` can be present, and values must be in 4341ascending order. 4342 4343Examples are: 4344 4345.. code-block:: c 4346 4347 # 57 // Advance (or return) to line 57 of the current source file 4348 # 57 "frob" // Set to line 57 of "frob" 4349 # 1 "foo.h" 1 // Enter "foo.h" at line 1 4350 # 59 "main.c" 2 // Leave current include and return to "main.c" 4351 # 1 "/usr/include/stdio.h" 1 3 // Enter a system header 4352 # 60 "" 2 // return to "main.c" 4353 # 1 "/usr/ancient/header.h" 1 4 // Enter an implicit extern "C" header 4354 4355Extended Integer Types 4356====================== 4357 4358Clang supports the C23 ``_BitInt(N)`` feature as an extension in older C modes 4359and in C++. This type was previously implemented in Clang with the same 4360semantics, but spelled ``_ExtInt(N)``. This spelling has been deprecated in 4361favor of the standard type. 4362 4363Note: the ABI for ``_BitInt(N)`` is still in the process of being stabilized, 4364so this type should not yet be used in interfaces that require ABI stability. 4365 4366Intrinsics Support within Constant Expressions 4367============================================== 4368 4369The following builtin intrinsics can be used in constant expressions: 4370 4371* ``__builtin_bitreverse8`` 4372* ``__builtin_bitreverse16`` 4373* ``__builtin_bitreverse32`` 4374* ``__builtin_bitreverse64`` 4375* ``__builtin_bswap16`` 4376* ``__builtin_bswap32`` 4377* ``__builtin_bswap64`` 4378* ``__builtin_clrsb`` 4379* ``__builtin_clrsbl`` 4380* ``__builtin_clrsbll`` 4381* ``__builtin_clz`` 4382* ``__builtin_clzl`` 4383* ``__builtin_clzll`` 4384* ``__builtin_clzs`` 4385* ``__builtin_ctz`` 4386* ``__builtin_ctzl`` 4387* ``__builtin_ctzll`` 4388* ``__builtin_ctzs`` 4389* ``__builtin_ffs`` 4390* ``__builtin_ffsl`` 4391* ``__builtin_ffsll`` 4392* ``__builtin_fpclassify`` 4393* ``__builtin_inf`` 4394* ``__builtin_isinf`` 4395* ``__builtin_isinf_sign`` 4396* ``__builtin_isfinite`` 4397* ``__builtin_isnan`` 4398* ``__builtin_isnormal`` 4399* ``__builtin_nan`` 4400* ``__builtin_nans`` 4401* ``__builtin_parity`` 4402* ``__builtin_parityl`` 4403* ``__builtin_parityll`` 4404* ``__builtin_popcount`` 4405* ``__builtin_popcountl`` 4406* ``__builtin_popcountll`` 4407* ``__builtin_rotateleft8`` 4408* ``__builtin_rotateleft16`` 4409* ``__builtin_rotateleft32`` 4410* ``__builtin_rotateleft64`` 4411* ``__builtin_rotateright8`` 4412* ``__builtin_rotateright16`` 4413* ``__builtin_rotateright32`` 4414* ``__builtin_rotateright64`` 4415 4416The following x86-specific intrinsics can be used in constant expressions: 4417 4418* ``_bit_scan_forward`` 4419* ``_bit_scan_reverse`` 4420* ``__bsfd`` 4421* ``__bsfq`` 4422* ``__bsrd`` 4423* ``__bsrq`` 4424* ``__bswap`` 4425* ``__bswapd`` 4426* ``__bswap64`` 4427* ``__bswapq`` 4428* ``_castf32_u32`` 4429* ``_castf64_u64`` 4430* ``_castu32_f32`` 4431* ``_castu64_f64`` 4432* ``_mm_popcnt_u32`` 4433* ``_mm_popcnt_u64`` 4434* ``_popcnt32`` 4435* ``_popcnt64`` 4436* ``__popcntd`` 4437* ``__popcntq`` 4438* ``__rolb`` 4439* ``__rolw`` 4440* ``__rold`` 4441* ``__rolq`` 4442* ``__rorb`` 4443* ``__rorw`` 4444* ``__rord`` 4445* ``__rorq`` 4446* ``_rotl`` 4447* ``_rotr`` 4448* ``_rotwl`` 4449* ``_rotwr`` 4450* ``_lrotl`` 4451* ``_lrotr`` 4452