brintos

brintos / llvm-project-archived public Read only

0
0
Text · 259.8 KiB · 40cc189 Raw
6819 lines · plain
1=========================2Clang Language Extensions3=========================4 5.. contents::6   :local:7   :depth: 18 9.. toctree::10   :hidden:11 12   ObjectiveCLiterals13   BlockLanguageSpec14   Block-ABI-Apple15   AutomaticReferenceCounting16   PointerAuthentication17   MatrixTypes18   CXXTypeAwareAllocators19 20Introduction21============22 23This document describes the language extensions provided by Clang.  In addition24to the language extensions listed here, Clang aims to support a broad range of25GCC extensions.  Please see the `GCC manual26<https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on27these extensions.28 29.. _langext-feature_check:30 31Feature Checking Macros32=======================33 34Language extensions can be very useful, but only if you know you can depend on35them.  In order to allow fine-grained feature checks, we support three builtin36function-like macros.  This allows you to directly test for a feature in your37code without having to resort to something like autoconf or fragile "compiler38version checks".39 40``__has_builtin``41-----------------42 43This function-like macro takes a single identifier argument that is the name of44a builtin function, a builtin pseudo-function (taking one or more type45arguments), or a builtin template.46It evaluates to 1 if the builtin is supported or 0 if not.47It can be used like this:48 49.. code-block:: c++50 51  #ifndef __has_builtin         // Optional of course.52    #define __has_builtin(x) 0  // Compatibility with non-clang compilers.53  #endif54 55  ...56  #if __has_builtin(__builtin_trap)57    __builtin_trap();58  #else59    abort();60  #endif61  ...62 63.. note::64 65  Prior to Clang 10, ``__has_builtin`` could not be used to detect most builtin66  pseudo-functions.67 68  ``__has_builtin`` should not be used to detect support for a builtin macro;69  use ``#ifdef`` instead.70 71  When compiling with target offloading, ``__has_builtin`` only considers the72  currently active target.73 74``__has_constexpr_builtin``75---------------------------76 77This function-like macro takes a single identifier argument that is the name of78a builtin function, a builtin pseudo-function (taking one or more type79arguments), or a builtin template.80It evaluates to 1 if the builtin is supported and can be constant evaluated or810 if not. It can be used for writing conditionally constexpr code like this:82 83.. code-block:: c++84 85  #ifndef __has_constexpr_builtin         // Optional of course.86    #define __has_constexpr_builtin(x) 0  // Compatibility with non-clang compilers.87  #endif88 89  ...90  #if __has_constexpr_builtin(__builtin_fmax)91    constexpr92  #endif93    double money_fee(double amount) {94        return __builtin_fmax(amount * 0.03, 10.0);95    }96  ...97 98For example, ``__has_constexpr_builtin`` is used in libcxx's implementation of99the ``<cmath>`` header file to conditionally make a function constexpr whenever100the constant evaluation of the corresponding builtin (for example,101``std::fmax`` calls ``__builtin_fmax``) is supported in Clang.102 103.. _langext-__has_feature-__has_extension:104 105``__has_feature`` and ``__has_extension``106-----------------------------------------107 108These function-like macros take a single identifier argument that is the name109of a feature.  ``__has_feature`` evaluates to 1 if the feature is both110supported by Clang and standardized in the current language standard or 0 if111not (but see :ref:`below <langext-has-feature-back-compat>`), while112``__has_extension`` evaluates to 1 if the feature is supported by Clang in the113current language (either as a language extension or a standard language114feature) or 0 if not.  They can be used like this:115 116.. code-block:: c++117 118  #ifndef __has_feature         // Optional of course.119    #define __has_feature(x) 0  // Compatibility with non-clang compilers.120  #endif121  #ifndef __has_extension122    #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.123  #endif124 125  ...126  #if __has_feature(cxx_rvalue_references)127  // This code will only be compiled with the -std=c++11 and -std=gnu++11128  // options, because rvalue references are only standardized in C++11.129  #endif130 131  #if __has_extension(cxx_rvalue_references)132  // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98133  // and -std=gnu++98 options, because rvalue references are supported as a134  // language extension in C++98.135  #endif136 137.. _langext-has-feature-back-compat:138 139For backward compatibility, ``__has_feature`` can also be used to test140for support for non-standardized features, i.e., features not prefixed ``c_``,141``cxx_`` or ``objc_``.142 143Another use of ``__has_feature`` is to check for compiler features not related144to the language standard, such as :doc:`AddressSanitizer145<AddressSanitizer>`.146 147If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent148to ``__has_feature``.149 150The feature tag is described along with the language feature below.151 152The feature name or extension name can also be specified with a preceding and153following ``__`` (double underscore) to avoid interference from a macro with154the same name.  For instance, ``__cxx_rvalue_references__`` can be used instead155of ``cxx_rvalue_references``.156 157``__has_cpp_attribute``158-----------------------159 160This function-like macro is available in C++20 by default, and is provided as an161extension in earlier language standards. It takes a single argument that is the162name of a double-square-bracket-style attribute. The argument can be either a163single identifier or a scoped identifier. If the attribute is supported, a164nonzero value is returned. If the attribute is a standards-based attribute, this165macro returns a nonzero value based on the year and month in which the attribute166was voted into the working draft. See `WG21 SD-6167<https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_168for the list of values returned for standards-based attributes. If the attribute169is not supported by the current compilation target, this macro evaluates to 0.170It can be used like this:171 172.. code-block:: c++173 174  #ifndef __has_cpp_attribute         // For backwards compatibility175    #define __has_cpp_attribute(x) 0176  #endif177 178  ...179  #if __has_cpp_attribute(clang::fallthrough)180  #define FALLTHROUGH [[clang::fallthrough]]181  #else182  #define FALLTHROUGH183  #endif184  ...185 186The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are187the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either188of these namespaces can be specified with a preceding and following ``__``189(double underscore) to avoid interference from a macro with the same name. For190instance, ``gnu::__const__`` can be used instead of ``gnu::const``.191 192``__has_c_attribute``193---------------------194 195This function-like macro takes a single argument that is the name of an196attribute exposed with the double square-bracket syntax in C mode. The argument197can either be a single identifier or a scoped identifier. If the attribute is198supported, a nonzero value is returned. If the attribute is not supported by the199current compilation target, this macro evaluates to 0. It can be used like this:200 201.. code-block:: c202 203  #ifndef __has_c_attribute         // Optional of course.204    #define __has_c_attribute(x) 0  // Compatibility with non-clang compilers.205  #endif206 207  ...208  #if __has_c_attribute(fallthrough)209    #define FALLTHROUGH [[fallthrough]]210  #else211    #define FALLTHROUGH212  #endif213  ...214 215The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are216the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either217of these namespaces can be specified with a preceding and following ``__``218(double underscore) to avoid interference from a macro with the same name. For219instance, ``gnu::__const__`` can be used instead of ``gnu::const``.220 221``__has_attribute``222-------------------223 224This function-like macro takes a single identifier argument that is the name of225a GNU-style attribute.  It evaluates to 1 if the attribute is supported by the226current compilation target, or 0 if not.  It can be used like this:227 228.. code-block:: c++229 230  #ifndef __has_attribute         // Optional of course.231    #define __has_attribute(x) 0  // Compatibility with non-clang compilers.232  #endif233 234  ...235  #if __has_attribute(always_inline)236  #define ALWAYS_INLINE __attribute__((always_inline))237  #else238  #define ALWAYS_INLINE239  #endif240  ...241 242The attribute name can also be specified with a preceding and following ``__``243(double underscore) to avoid interference from a macro with the same name.  For244instance, ``__always_inline__`` can be used instead of ``always_inline``.245 246 247``__has_declspec_attribute``248----------------------------249 250This function-like macro takes a single identifier argument that is the name of251an attribute implemented as a Microsoft-style ``__declspec`` attribute.  It252evaluates to 1 if the attribute is supported by the current compilation target,253or 0 if not.  It can be used like this:254 255.. code-block:: c++256 257  #ifndef __has_declspec_attribute         // Optional of course.258    #define __has_declspec_attribute(x) 0  // Compatibility with non-clang compilers.259  #endif260 261  ...262  #if __has_declspec_attribute(dllexport)263  #define DLLEXPORT __declspec(dllexport)264  #else265  #define DLLEXPORT266  #endif267  ...268 269The attribute name can also be specified with a preceding and following ``__``270(double underscore) to avoid interference from a macro with the same name.  For271instance, ``__dllexport__`` can be used instead of ``dllexport``.272 273``__is_identifier``274-------------------275 276This function-like macro takes a single identifier argument that might be either277a reserved word or a regular identifier. It evaluates to 1 if the argument is just278a regular identifier and not a reserved word, in the sense that it can then be279used as the name of a user-defined function or variable. Otherwise it evaluates280to 0.  It can be used like this:281 282.. code-block:: c++283 284  ...285  #ifdef __is_identifier          // Compatibility with non-clang compilers.286    #if __is_identifier(__wchar_t)287      typedef wchar_t __wchar_t;288    #endif289  #endif290 291  __wchar_t WideCharacter;292  ...293 294Include File Checking Macros295============================296 297Not all developments systems have the same include files.  The298:ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow299you to check for the existence of an include file before doing a possibly300failing ``#include`` directive.  Include file checking macros must be used301as expressions in ``#if`` or ``#elif`` preprocessing directives.302 303.. _langext-__has_include:304 305``__has_include``306-----------------307 308This function-like macro takes a single file name string argument that is the309name of an include file.  It evaluates to 1 if the file can be found using the310include paths, or 0 otherwise:311 312.. code-block:: c++313 314  // Note the two possible file name string formats.315  #if __has_include("myinclude.h") && __has_include(<stdint.h>)316  # include "myinclude.h"317  #endif318 319To test for this feature, use ``#if defined(__has_include)``:320 321.. code-block:: c++322 323  // To avoid problems with non-clang compilers not having this macro.324  #if defined(__has_include)325  #if __has_include("myinclude.h")326  # include "myinclude.h"327  #endif328  #endif329 330.. _langext-__has_include_next:331 332``__has_include_next``333----------------------334 335This function-like macro takes a single file name string argument that is the336name of an include file.  It is like ``__has_include`` except that it looks for337the second instance of the given file found in the include paths.  It evaluates338to 1 if the second instance of the file can be found using the include paths,339or 0 otherwise:340 341.. code-block:: c++342 343  // Note the two possible file name string formats.344  #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)345  # include_next "myinclude.h"346  #endif347 348  // To avoid problems with non-clang compilers not having this macro.349  #if defined(__has_include_next)350  #if __has_include_next("myinclude.h")351  # include_next "myinclude.h"352  #endif353  #endif354 355Note that ``__has_include_next``, like the GNU extension ``#include_next``356directive, is intended for use in headers only, and will issue a warning if357used in the top-level compilation file.  A warning will also be issued if an358absolute path is used in the file argument.359 360``__has_warning``361-----------------362 363This function-like macro takes a string literal that represents a command line364option for a warning and returns ``true`` if that is a valid warning option.365 366.. code-block:: c++367 368  #if __has_warning("-Wformat")369  ...370  #endif371 372.. _languageextensions-builtin-macros:373 374Builtin Macros375==============376 377``__BASE_FILE__``378  Defined to a string that contains the name of the main input file passed to379  Clang.380 381``__FILE_NAME__``382  Clang-specific extension that functions similar to ``__FILE__`` but only383  renders the last path component (the filename) instead of an384  invocation-dependent full path to that file.385 386``__COUNTER__``387  Defined to an integer value that starts at zero and is incremented each time388  the ``__COUNTER__`` macro is expanded. This is a standard feature in C2y but389  is an extension in earlier language modes and in C++. This macro can only be390  expanded 2147483647 times at most.391 392``__INCLUDE_LEVEL__``393  Defined to an integral value that is the include depth of the file currently394  being translated.  For the main file, this value is zero.395 396``__TIMESTAMP__``397  Defined to the date and time of the last modification of the current source398  file.399 400``__clang__``401  Defined when compiling with Clang.402 403``__clang_major__``404  Defined to the major marketing version number of Clang (e.g., the 2 in405  2.0.1).  Note that marketing version numbers should not be used to check for406  language features, as different vendors use different numbering schemes.407  Instead, use the :ref:`langext-feature_check`.408 409``__clang_minor__``410  Defined to the minor version number of Clang (e.g., the 0 in 2.0.1).  Note411  that marketing version numbers should not be used to check for language412  features, as different vendors use different numbering schemes.  Instead, use413  the :ref:`langext-feature_check`.414 415``__clang_patchlevel__``416  Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).417 418``__clang_version__``419  Defined to a string that captures the Clang marketing version, including the420  Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".421 422``__clang_literal_encoding__``423  Defined to a narrow string literal that represents the current encoding of424  narrow string literals, e.g., ``"hello"``. This macro typically expands to425  "UTF-8" (but may change in the future if the426  ``-fexec-charset="Encoding-Name"`` option is implemented.)427 428``__clang_wide_literal_encoding__``429  Defined to a narrow string literal that represents the current encoding of430  wide string literals, e.g., ``L"hello"``. This macro typically expands to431  "UTF-16" or "UTF-32" (but may change in the future if the432  ``-fwide-exec-charset="Encoding-Name"`` option is implemented.)433 434Implementation-defined keywords435===============================436 437__datasizeof438------------439 440``__datasizeof`` behaves like ``sizeof``, except that it returns the size of the441type ignoring tail padding.442 443_BitInt, _ExtInt444----------------445 446Clang supports the C23 ``_BitInt(N)`` feature as an extension in older C modes447and in C++. This type was previously implemented in Clang with the same448semantics, but spelled ``_ExtInt(N)``. This spelling has been deprecated in449favor of the standard type.450 451Note: the ABI for ``_BitInt(N)`` is still in the process of being stabilized,452so this type should not yet be used in interfaces that require ABI stability.453 454C keywords supported in all language modes455------------------------------------------456 457Clang supports ``_Alignas``, ``_Alignof``, ``_Atomic``, ``_Complex``,458``_Generic``, ``_Imaginary``, ``_Noreturn``, ``_Static_assert``,459``_Thread_local``, and ``_Float16`` in all language modes with the C semantics.460 461__alignof, __alignof__462----------------------463 464``__alignof`` and ``__alignof__`` return, in contrast to ``_Alignof`` and465``alignof``, the preferred alignment of a type. This may be larger than the466required alignment for improved performance.467 468__extension__469-------------470 471``__extension__`` suppresses extension diagnostics in the statement it is472prepended to.473 474__auto_type475-----------476 477``__auto_type`` behaves the same as ``auto`` in C++11 but is available in all478language modes.479 480__imag, __imag__481----------------482 483``__imag`` and ``__imag__`` can be used to get the imaginary part of a complex484value.485 486__real, __real__487----------------488 489``__real`` and ``__real__`` can be used to get the real part of a complex value.490 491__asm, __asm__492--------------493 494``__asm`` and ``__asm__`` are alternate spellings for ``asm``, but available in495all language modes.496 497__complex, __complex__498----------------------499 500``__complex`` and ``__complex__`` are alternate spellings for ``_Complex``.501 502__const, __const__, __volatile, __volatile__, __restrict, __restrict__503----------------------------------------------------------------------504 505These are alternate spellings for their non-underscore counterparts, but are506available in all language modes.507 508__decltype509----------510 511``__decltype`` is an alternate spelling for ``decltype``, but is also available512in C++ modes before C++11.513 514__inline, __inline__515--------------------516 517``__inline`` and ``__inline__`` are alternate spellings for ``inline``, but are518available in all language modes.519 520__nullptr521---------522 523``__nullptr`` is an alternate spelling for ``nullptr``. It is available in all C and C++ language modes.524 525__signed, __signed__526--------------------527 528``__signed`` and ``__signed__`` are alternate spellings for ``signed``.529``__unsigned`` and ``__unsigned__`` are **not** supported.530 531__typeof, __typeof__, __typeof_unqual, __typeof_unqual__532--------------------------------------------------------533 534``__typeof`` and ``__typeof__`` are alternate spellings for ``typeof``, but are535available in all language modes. These spellings result in the operand,536retaining all qualifiers.537 538``__typeof_unqual`` and ``__typeof_unqual__`` are alternate spellings for the539C23 ``typeof_unqual`` type specifier, but are available in all language modes.540These spellings result in the type of the operand, stripping all qualifiers.541 542__char16_t, __char32_t543----------------------544 545``__char16_t`` and ``__char32_t`` are alternate spellings for ``char16_t`` and546``char32_t`` respectively, but are also available in C++ modes before C++11.547They are only supported in C++. ``__char8_t`` is not available.548 549..550  FIXME: This should list all the keyword extensions551 552.. _langext-vectors:553 554Vectors and Extended Vectors555============================556 557Supports the GCC, OpenCL, AltiVec, NEON and SVE vector extensions.558 559OpenCL vector types are created using the ``ext_vector_type`` attribute.  It560supports the ``V.xyzw`` syntax and other tidbits as seen in OpenCL.  An example561is:562 563.. code-block:: c++564 565  typedef float float4 __attribute__((ext_vector_type(4)));566  typedef float float2 __attribute__((ext_vector_type(2)));567 568  float4 foo(float2 a, float2 b) {569    float4 c;570    c.xz = a;571    c.yw = b;572    return c;573  }574 575Query for this feature with ``__has_attribute(ext_vector_type)``.576 577Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax578and functions.  For example:579 580.. code-block:: c++581 582  vector float foo(vector int a) {583    vector int b;584    b = vec_add(a, a) + a;585    return (vector float)b;586  }587 588NEON vector types are created using ``neon_vector_type`` and589``neon_polyvector_type`` attributes.  For example:590 591.. code-block:: c++592 593  typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;594  typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;595 596  int8x8_t foo(int8x8_t a) {597    int8x8_t v;598    v = a;599    return v;600  }601 602GCC vector types are created using the ``vector_size(N)`` attribute.  The603argument ``N`` specifies the number of bytes that will be allocated for an604object of this type.  The size has to be a multiple of the size of the vector605element type. For example:606 607.. code-block:: c++608 609  // OK: This declares a vector type with four 'int' elements610  typedef int int4 __attribute__((vector_size(4 * sizeof(int))));611 612  // ERROR: '11' is not a multiple of sizeof(int)613  typedef int int_impossible __attribute__((vector_size(11)));614 615  int4 foo(int4 a) {616    int4 v;617    v = a;618    return v;619  }620 621 622Boolean Vectors623---------------624 625Clang also supports the ``ext_vector_type`` attribute with boolean element types in626C and C++.  For example:627 628.. code-block:: c++629 630  // legal for Clang, error for GCC:631  typedef bool bool4 __attribute__((ext_vector_type(4)));632  // Objects of bool4 type hold 8 bits, sizeof(bool4) == 1633 634  bool4 foo(bool4 a) {635    bool4 v;636    v = a;637    return v;638  }639 640 641Boolean vectors are a Clang extension of the ext vector type.  Boolean vectors642are intended, though not guaranteed, to map to vector mask registers.  The size643parameter of a boolean vector type is the number of bits in the vector.  The644boolean vector is dense and each bit in the boolean vector is one vector645element. Query for this feature with ``__has_feature(ext_vector_type_boolean)``.646 647The semantics of boolean vectors borrows from C bit-fields with the following648differences:649 650* Distinct boolean vectors are always distinct memory objects (there is no651  packing).652* Only the operators `?:`, `!`, `~`, `|`, `&`, `^` and comparison are allowed on653  boolean vectors.654* Casting a scalar bool value to a boolean vector type means broadcasting the655  scalar value onto all lanes (same as general ext_vector_type).656* It is not possible to access or swizzle elements of a boolean vector657  (different than general ext_vector_type).658 659The size and alignment are both the number of bits rounded up to the next power660of two, but the alignment is at most the maximum vector alignment of the661target.662 663A boolean vector can be used in a ternary `?:` operator to select vector664elements of a different type.665 666.. code-block:: c++667 668  typedef int int4 __attribute__((ext_vector_type(4)));669  typedef bool bool4 __attribute__((ext_vector_type(4)));670 671  int4 blend(bool4 cond, int4 a, int4 b) { return cond ? a : b; }672 673 674Vector Literals675---------------676 677Vector literals can be used to create vectors from a set of scalars, or678vectors.  Either parentheses or braces form can be used.  In the parentheses679form the number of literal values specified must be one, i.e., referring to a680scalar value, or must match the size of the vector type being created.  If a681single scalar literal value is specified, the scalar literal value will be682replicated to all the components of the vector type.  In the brackets form any683number of literals can be specified.  For example:684 685.. code-block:: c++686 687  typedef int v4si __attribute__((__vector_size__(16)));688  typedef float float4 __attribute__((ext_vector_type(4)));689  typedef float float2 __attribute__((ext_vector_type(2)));690 691  v4si vsi = (v4si){1, 2, 3, 4};692  float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);693  vector int vi1 = (vector int)(1);    // vi1 will be (1, 1, 1, 1).694  vector int vi2 = (vector int){1};    // vi2 will be (1, 0, 0, 0).695  vector int vi3 = (vector int)(1, 2); // error696  vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).697  vector int vi5 = (vector int)(1, 2, 3, 4);698  float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));699 700Vector Operations701-----------------702 703The table below shows the support for each operation by vector extension.  A704dash indicates that an operation is not accepted according to a corresponding705specification.706 707============================== ======= ======= ============= ======= =====708         Operator              OpenCL  AltiVec     GCC        NEON    SVE709============================== ======= ======= ============= ======= =====710[]                               yes     yes       yes         yes    yes711unary operators +, --            yes     yes       yes         yes    yes712++, -- --                        yes     yes       yes         no     no713+,--,*,/,%                       yes     yes       yes         yes    yes714bitwise operators &,|,^,~        yes     yes       yes         yes    yes715>>,<<                            yes     yes       yes         yes    yes716!, &&, ||                        yes     --        yes         yes    yes717==, !=, >, <, >=, <=             yes     yes       yes         yes    yes718=                                yes     yes       yes         yes    yes719?: [#]_                          yes     --        yes         yes    yes720sizeof                           yes     yes       yes         yes    yes [#]_721C-style cast                     yes     yes       yes         no     no722reinterpret_cast                 yes     no        yes         no     no723static_cast                      yes     no        yes         no     no724const_cast                       no      no        no          no     no725address &v[i]                    no      no        no [#]_     no     no726============================== ======= ======= ============= ======= =====727 728See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.729 730.. [#] ternary operator(?:) has different behaviors depending on the condition731  operand's vector type. If the condition is a GNU vector (i.e., ``__vector_size__``),732  a NEON vector or an SVE vector, it's only available in C++ and uses normal bool733  conversions (that is, != 0).734  If it's an extension (OpenCL) vector, it's only available in C and OpenCL C.735  And it selects based on the signedness of the condition operands (OpenCL v1.1 s6.3.9).736.. [#] sizeof can only be used on vector length specific SVE types.737.. [#] Clang does not allow the address of an element to be taken while GCC738   allows this. This is intentional for vectors with a boolean element type and739   not implemented otherwise.740 741Vector Builtins742---------------743 744**Note: The implementation of vector builtins is work-in-progress and incomplete.**745 746In addition to the operators mentioned above, Clang provides a set of builtins747to perform additional operations on certain scalar and vector types.748 749Let ``T`` be one of the following types:750 751* an integer type (as in C23 6.2.5p22), but excluding enumerated types and ``bool``752* the standard floating types ``float`` or ``double``753* a half-precision floating point type, if one is supported on the target754* a vector type.755 756For scalar types, consider the operation applied to a vector with a single element.757 758*Vector Size*759To determine the number of elements in a vector, use ``__builtin_vectorelements()``.760For fixed-sized vectors, e.g., defined via ``__attribute__((vector_size(N)))`` or ARM761NEON's vector types (e.g., ``uint16x8_t``), this returns the constant number of762elements at compile-time. For scalable vectors, e.g., SVE or RISC-V V, the number of763elements is not known at compile-time and is determined at runtime. This builtin can764be used, e.g., to increment the loop-counter in vector-type agnostic loops.765 766*Elementwise Builtins*767 768Each builtin returns a vector equivalent to applying the specified operation769elementwise to the input.770 771Unless specified otherwise operation(±0) = ±0 and operation(±infinity) = ±infinity772 773The elementwise intrinsics ``__builtin_elementwise_popcount``,774``__builtin_elementwise_bitreverse``, ``__builtin_elementwise_add_sat``,775``__builtin_elementwise_sub_sat``, ``__builtin_elementwise_max``,776``__builtin_elementwise_min``, ``__builtin_elementwise_abs``,777``__builtin_elementwise_clzg``, ``__builtin_elementwise_ctzg``, and778``__builtin_elementwise_fma`` can be called in a ``constexpr`` context.779 780No implicit promotion of integer types takes place. The mixing of integer types781of different sizes and signs is forbidden in binary and ternary builtins.782 783============================================== ====================================================================== =========================================784         Name                                   Operation                                                             Supported element types785============================================== ====================================================================== =========================================786 T __builtin_elementwise_abs(T x)               return the absolute value of a number x; the absolute value of         signed integer and floating point types787                                                the most negative integer remains the most negative integer788 T __builtin_elementwise_fma(T x, T y, T z)     fused multiply add, (x * y) +  z.                                      floating point types789 T __builtin_elementwise_ceil(T x)              return the smallest integral value greater than or equal to x          floating point types790 T __builtin_elementwise_sin(T x)               return the sine of x interpreted as an angle in radians                floating point types791 T __builtin_elementwise_cos(T x)               return the cosine of x interpreted as an angle in radians              floating point types792 T __builtin_elementwise_tan(T x)               return the tangent of x interpreted as an angle in radians             floating point types793 T __builtin_elementwise_asin(T x)              return the arcsine of x interpreted as an angle in radians             floating point types794 T __builtin_elementwise_acos(T x)              return the arccosine of x interpreted as an angle in radians           floating point types795 T __builtin_elementwise_atan(T x)              return the arctangent of x interpreted as an angle in radians          floating point types796 T __builtin_elementwise_atan2(T y, T x)        return the arctangent of y/x                                           floating point types797 T __builtin_elementwise_sinh(T x)              return the hyperbolic sine of angle x in radians                       floating point types798 T __builtin_elementwise_cosh(T x)              return the hyperbolic cosine of angle x in radians                     floating point types799 T __builtin_elementwise_tanh(T x)              return the hyperbolic tangent of angle x in radians                    floating point types800 T __builtin_elementwise_floor(T x)             return the largest integral value less than or equal to x              floating point types801 T __builtin_elementwise_log(T x)               return the natural logarithm of x                                      floating point types802 T __builtin_elementwise_log2(T x)              return the base 2 logarithm of x                                       floating point types803 T __builtin_elementwise_log10(T x)             return the base 10 logarithm of x                                      floating point types804 T __builtin_elementwise_popcount(T x)          return the number of 1 bits in x                                       integer types805 T __builtin_elementwise_pow(T x, T y)          return x raised to the power of y                                      floating point types806 T __builtin_elementwise_bitreverse(T x)        return the integer represented after reversing the bits of x           integer types807 T __builtin_elementwise_exp(T x)               returns the base-e exponential, e^x, of the specified value            floating point types808 T __builtin_elementwise_exp2(T x)              returns the base-2 exponential, 2^x, of the specified value            floating point types809 T __builtin_elementwise_exp10(T x)             returns the base-10 exponential, 10^x, of the specified value          floating point types810 T __builtin_elementwise_ldexp(T x, IntT y)     returns the product of x and 2 raised to the power y.                  T: floating point types,811                                                y must be an integer type matching the shape of x.                     IntT: integer types812 813 T __builtin_elementwise_sqrt(T x)              return the square root of a floating-point number                      floating point types814 T __builtin_elementwise_roundeven(T x)         round x to the nearest integer value in floating point format,         floating point types815                                                rounding halfway cases to even (that is, to the nearest value816                                                that is an even integer), regardless of the current rounding817                                                direction.818 T __builtin_elementwise_round(T x)             round x to the nearest  integer value in floating point format,        floating point types819                                                rounding halfway cases away from zero, regardless of the820                                                current rounding direction. May raise floating-point821                                                exceptions.822 T __builtin_elementwise_trunc(T x)             return the integral value nearest to but no larger in                  floating point types823                                                magnitude than x824 825  T __builtin_elementwise_nearbyint(T x)        round x to the nearest  integer value in floating point format,        floating point types826                                                rounding according to the current rounding direction.827                                                May not raise the inexact floating-point exception. This is828                                                treated the same as ``__builtin_elementwise_rint`` unless829                                                :ref:`FENV_ACCESS is enabled <floating-point-environment>`.830 831 T __builtin_elementwise_rint(T x)              round x to the nearest  integer value in floating point format,        floating point types832                                                rounding according to the current rounding833                                                direction. May raise floating-point exceptions. This is treated834                                                the same as ``__builtin_elementwise_nearbyint`` unless835                                                :ref:`FENV_ACCESS is enabled <floating-point-environment>`.836 837 T __builtin_elementwise_canonicalize(T x)      return the platform specific canonical encoding                        floating point types838                                                of a floating-point number839 T __builtin_elementwise_copysign(T x, T y)     return the magnitude of x with the sign of y.                          floating point types840 T __builtin_elementwise_fmod(T x, T y)         return the floating-point remainder of (x/y) whose sign                floating point types841                                                matches the sign of x.842 T __builtin_elementwise_max(T x, T y)          return x or y, whichever is larger                                     integer and floating point types843                                                For floating point types, follows semantics of maxNum844                                                in IEEE 754-2008. See `LangRef845                                                <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_846                                                for the comparison.847 T __builtin_elementwise_min(T x, T y)          return x or y, whichever is smaller                                    integer and floating point types848                                                For floating point types, follows semantics of minNum849                                                in IEEE 754-2008. See `LangRef850                                                <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_851                                                for the comparison.852 T __builtin_elementwise_maxnum(T x, T y)       return x or y, whichever is larger. Follows IEEE 754-2008              floating point types853                                                semantics (maxNum) with +0.0>-0.0. See `LangRef854                                                <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_855                                                for the comparison.856 T __builtin_elementwise_minnum(T x, T y)       return x or y, whichever is smaller. Follows IEEE 754-2008             floating point types857                                                semantics (minNum) with +0.0>-0.0. See `LangRef858                                                <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_859                                                for the comparison.860 T __builtin_elementwise_add_sat(T x, T y)      return the sum of x and y, clamped to the range of                     integer types861                                                representable values for the signed/unsigned integer type.862 T __builtin_elementwise_sub_sat(T x, T y)      return the difference of x and y, clamped to the range of              integer types863                                                representable values for the signed/unsigned integer type.864 T __builtin_elementwise_maximum(T x, T y)      return x or y, whichever is larger. Follows IEEE 754-2019              floating point types865                                                semantics, see `LangRef866                                                <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_867                                                for the comparison.868 T __builtin_elementwise_minimum(T x, T y)      return x or y, whichever is smaller. Follows IEEE 754-2019             floating point types869                                                semantics, see `LangRef870                                                <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_871                                                for the comparison.872 T __builtin_elementwise_maximumnum(T x, T y)   return x or y, whichever is larger. Follows IEEE 754-2019              floating point types873                                                semantics, see `LangRef874                                                <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_875                                                for the comparison.876 T __builtin_elementwise_minimumnum(T x, T y)   return x or y, whichever is smaller. Follows IEEE 754-2019             floating point types877                                                semantics, see `LangRef878                                                <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_879                                                for the comparison.880T __builtin_elementwise_fshl(T x, T y, T z)     perform a funnel shift left. Concatenate x and y (x is the most        integer types881                                                significant bits of the wide value), the combined value is shifted882                                                left by z (modulo the bit width of the original arguments),883                                                and the most significant bits are extracted to produce884                                                a result that is the same size as the original arguments.885 886T __builtin_elementwise_fshr(T x, T y, T z)     perform a funnel shift right. Concatenate x and y (x is the most       integer types887                                                significant bits of the wide value), the combined value is shifted888                                                right by z (modulo the bit width of the original arguments),889                                                and the least significant bits are extracted to produce890                                                a result that is the same size as the original arguments.891 T __builtin_elementwise_clzg(T x[, T y])       return the number of leading 0 bits in the first argument. If          integer types892                                                the first argument is 0 and an optional second argument is provided,893                                                the second argument is returned. It is undefined behaviour if the894                                                first argument is 0 and no second argument is provided.895 T __builtin_elementwise_ctzg(T x[, T y])       return the number of trailing 0 bits in the first argument. If         integer types896                                                the first argument is 0 and an optional second argument is provided,897                                                the second argument is returned. It is undefined behaviour if the898                                                first argument is 0 and no second argument is provided.899============================================== ====================================================================== =========================================900 901 902*Reduction Builtins*903 904Each builtin returns a scalar equivalent to applying the specified905operation(x, y) as recursive even-odd pairwise reduction to all vector906elements. ``operation(x, y)`` is repeatedly applied to each non-overlapping907even-odd element pair with indices ``i * 2`` and ``i * 2 + 1`` with908``i in [0, Number of elements / 2)``. If the number of elements is not a909power of 2, the vector is widened with neutral elements for the reduction910at the end to the next power of 2.911 912These reductions support both fixed-sized and scalable vector types.913 914The integer reduction intrinsics, including ``__builtin_reduce_max``,915``__builtin_reduce_min``, ``__builtin_reduce_add``, ``__builtin_reduce_mul``,916``__builtin_reduce_and``, ``__builtin_reduce_or``, and ``__builtin_reduce_xor``,917can be called in a ``constexpr`` context.918 919Example:920 921.. code-block:: c++922 923    __builtin_reduce_add([e3, e2, e1, e0]) = __builtin_reduced_add([e3 + e2, e1 + e0])924                                           = (e3 + e2) + (e1 + e0)925 926 927Let ``VT`` be a vector type and ``ET`` the element type of ``VT``.928 929======================================= ====================================================================== ==================================930         Name                            Operation                                                              Supported element types931======================================= ====================================================================== ==================================932 ET __builtin_reduce_max(VT a)           return the largest element of the vector. The floating point result    integer and floating point types933                                         will always be a number unless all elements of the vector are NaN.934 ET __builtin_reduce_min(VT a)           return the smallest element of the vector. The floating point result   integer and floating point types935                                         will always be a number unless all elements of the vector are NaN.936 ET __builtin_reduce_add(VT a)           \+                                                                     integer types937 ET __builtin_reduce_mul(VT a)           \*                                                                     integer types938 ET __builtin_reduce_and(VT a)           &                                                                      integer types939 ET __builtin_reduce_or(VT a)            \|                                                                     integer types940 ET __builtin_reduce_xor(VT a)           ^                                                                      integer types941 ET __builtin_reduce_maximum(VT a)       return the largest element of the vector. Follows IEEE 754-2019        floating point types942                                         semantics, see `LangRef943                                         <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_944                                         for the comparison.945 ET __builtin_reduce_minimum(VT a)       return the smallest element of the vector. Follows IEEE 754-2019       floating point types946                                         semantics, see `LangRef947                                         <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_948                                         for the comparison.949======================================= ====================================================================== ==================================950 951*Masked Builtins*952 953Each builtin accesses memory according to a provided boolean mask. These are954provided as ``__builtin_masked_load`` and ``__builtin_masked_store``. The first955argument is always a boolean mask vector. The ``__builtin_masked_load`` builtin956takes an optional third vector argument that will be used for the result of the957masked-off lanes. These builtins assume the memory is unaligned, use958``__builtin_assume_aligned`` if alignment is desired.959 960The ``__builtin_masked_expand_load`` and ``__builtin_masked_compress_store``961builtins have the same interface but store the result in consecutive indices.962Effectively this performs the ``if (mask[i]) val[i] = ptr[j++]`` and ``if963(mask[i]) ptr[j++] = val[i]`` pattern respectively.964 965The ``__builtin_masked_gather`` and ``__builtin_masked_scatter`` builtins handle966non-sequential memory access for vector types. These use a base pointer and a967vector of integer indices to gather memory into a vector type or scatter it to968separate indices.969 970Example:971 972.. code-block:: c++973 974    using v8b = bool [[clang::ext_vector_type(8)]];975    using v8i = int [[clang::ext_vector_type(8)]];976 977    v8i load(v8b mask, int *ptr) { return __builtin_masked_load(mask, ptr); }978    979    v8i load_expand(v8b mask, int *ptr) {980      return __builtin_masked_expand_load(mask, ptr);981    }982    983    void store(v8b mask, v8i val, int *ptr) {984      __builtin_masked_store(mask, val, ptr);985    }986    987    void store_compress(v8b mask, v8i val, int *ptr) {988      __builtin_masked_compress_store(mask, val, ptr);989    }990 991    v8i gather(v8b mask, v8i idx, int *ptr) {992      return __builtin_masked_gather(mask, idx, ptr);993    }994 995    void scatter(v8b mask, v8i val, v8i idx, int *ptr) {996      __builtin_masked_scatter(mask, idx, val, ptr);997    }998 999 1000Matrix Types1001============1002 1003Clang provides an extension for matrix types, which is currently being1004implemented. See :ref:`the draft specification <matrixtypes>` for more details.1005 1006For example, the code below uses the matrix types extension to multiply two 4x41007float matrices and add the result to a third 4x4 matrix.1008 1009.. code-block:: c++1010 1011  typedef float m4x4_t __attribute__((matrix_type(4, 4)));1012 1013  m4x4_t f(m4x4_t a, m4x4_t b, m4x4_t c) {1014    return a + b * c;1015  }1016 1017The matrix type extension also supports operations on a matrix and a scalar.1018 1019.. code-block:: c++1020 1021  typedef float m4x4_t __attribute__((matrix_type(4, 4)));1022 1023  m4x4_t f(m4x4_t a) {1024    return (a + 23) * 12;1025  }1026 1027The matrix type extension supports division on a matrix and a scalar but not on a matrix and a matrix.1028 1029.. code-block:: c++1030 1031  typedef float m4x4_t __attribute__((matrix_type(4, 4)));1032 1033  m4x4_t f(m4x4_t a) {1034    a = a / 3.0;1035    return a;1036  }1037 1038The matrix type extension supports compound assignments for addition, subtraction, and multiplication on matrices1039and on a matrix and a scalar, provided their types are consistent.1040 1041.. code-block:: c++1042 1043  typedef float m4x4_t __attribute__((matrix_type(4, 4)));1044 1045  m4x4_t f(m4x4_t a, m4x4_t b) {1046    a += b;1047    a -= b;1048    a *= b;1049    a += 23;1050    a -= 12;1051    return a;1052  }1053 1054The matrix type extension supports explicit casts. Implicit type conversion between matrix types is not allowed.1055 1056.. code-block:: c++1057 1058  typedef int ix5x5 __attribute__((matrix_type(5, 5)));1059  typedef float fx5x5 __attribute__((matrix_type(5, 5)));1060 1061  fx5x5 f1(ix5x5 i, fx5x5 f) {1062    return (fx5x5) i;1063  }1064 1065 1066  template <typename X>1067  using matrix_4_4 = X __attribute__((matrix_type(4, 4)));1068 1069  void f2() {1070    matrix_5_5<double> d;1071    matrix_5_5<int> i;1072    i = (matrix_5_5<int>)d;1073    i = static_cast<matrix_5_5<int>>(d);1074  }1075 1076Half-Precision Floating Point1077=============================1078 1079Clang supports three half-precision (16-bit) floating point types:1080``__fp16``, ``_Float16`` and ``__bf16``. These types are supported1081in all language modes, but their support differs between targets.1082A target is said to have "native support" for a type if the target1083processor offers instructions for directly performing basic arithmetic1084on that type.  In the absence of native support, a type can still be1085supported if the compiler can emulate arithmetic on the type by promoting1086to ``float``; see below for more information on this emulation.1087 1088* ``__fp16`` is supported on all targets. The special semantics of this1089  type mean that no arithmetic is ever performed directly on ``__fp16`` values;1090  see below.1091 1092* ``_Float16`` is supported on the following targets:1093 1094  * 32-bit ARM (natively on some architecture versions)1095  * 64-bit ARM (AArch64) (natively on ARMv8.2a and above)1096  * AMDGPU (natively)1097  * NVPTX (natively)1098  * SPIR (natively)1099  * X86 (if SSE2 is available; natively if AVX512-FP16 is also available)1100  * RISC-V (natively if Zfh or Zhinx is available)1101  * SystemZ (emulated)1102  * LoongArch (emulated)1103 1104* ``__bf16`` is supported on the following targets (currently never natively):1105 1106  * 32-bit ARM1107  * 64-bit ARM (AArch64)1108  * RISC-V1109  * X86 (when SSE2 is available)1110  * LoongArch1111 1112(For X86, SSE2 is available on 64-bit and all recent 32-bit processors.)1113 1114``__fp16`` and ``_Float16`` both use the binary16 format from IEEE1115754-2008, which provides a 5-bit exponent and an 11-bit significand1116(including the implicit leading 1). ``__bf16`` uses the `bfloat161117<https://en.wikipedia.org/wiki/Bfloat16_floating-point_format>`_ format,1118which provides an 8-bit exponent and an 8-bit significand; this is the same1119exponent range as `float`, just with greatly reduced precision.1120 1121``_Float16`` and ``__bf16`` follow the usual rules for arithmetic1122floating-point types. Most importantly, this means that arithmetic operations1123on operands of these types are formally performed in the type and produce1124values of the type. ``__fp16`` does not follow those rules: most operations1125immediately promote operands of type ``__fp16`` to ``float``, and so1126arithmetic operations are defined to be performed in ``float`` and so result in1127a value of type ``float`` (unless further promoted because of other operands).1128See below for more information on the exact specifications of these types.1129 1130When compiling arithmetic on ``_Float16`` and ``__bf16`` for a target without1131native support, Clang will perform the arithmetic in ``float``, inserting1132extensions and truncations as necessary. This can be done in a way that1133exactly matches the operation-by-operation behavior of native support,1134but that can require many extra truncations and extensions. By default,1135when emulating ``_Float16`` and ``__bf16`` arithmetic using ``float``, Clang1136does not truncate intermediate operands back to their true type unless the1137operand is the result of an explicit cast or assignment. This is generally1138much faster but can generate different results from strict operation-by-operation1139emulation. Usually the results are more precise. This is permitted by the1140C and C++ standards under the rules for excess precision in intermediate operands;1141see the discussion of evaluation formats in the C standard and [expr.pre] in1142the C++ standard.1143 1144The use of excess precision can be independently controlled for these two1145types with the ``-ffloat16-excess-precision=`` and1146``-fbfloat16-excess-precision=`` options. Valid values include:1147 1148* ``none``: meaning to perform strict operation-by-operation emulation1149* ``standard``: meaning that excess precision is permitted under the rules1150  described in the standard, i.e., never across explicit casts or statements1151* ``fast``: meaning that excess precision is permitted whenever the1152  optimizer sees an opportunity to avoid truncations; currently this has no1153  effect beyond ``standard``1154 1155The ``_Float16`` type is an interchange floating type specified in1156ISO/IEC TS 18661-3:2015 ("Floating-point extensions for C"). It will1157be supported on more targets as they define ABIs for it.1158 1159The ``__bf16`` type is a non-standard extension, but it generally follows1160the rules for arithmetic interchange floating types from ISO/IEC TS116118661-3:2015. In previous versions of Clang, it was a storage-only type1162that forbade arithmetic operations. It will be supported on more targets1163as they define ABIs for it.1164 1165The ``__fp16`` type was originally an ARM extension and is specified1166by the `ARM C Language Extensions <https://github.com/ARM-software/acle/releases>`_.1167Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``,1168not the ARM alternative format. Operators that expect arithmetic operands1169immediately promote ``__fp16`` operands to ``float``.1170 1171It is recommended that portable code use ``_Float16`` instead of ``__fp16``,1172as it has been defined by the C standards committee and has behavior that is1173more familiar to most programmers.1174 1175Because ``__fp16`` operands are always immediately promoted to ``float``, the1176common real type of ``__fp16`` and ``_Float16`` for the purposes of the usual1177arithmetic conversions is ``float``.1178 1179A literal can be given ``_Float16`` type using the suffix ``f16``. For example,1180``3.14f16``.1181 1182Because default argument promotion only applies to the standard floating-point1183types, ``_Float16`` values are not promoted to ``double`` when passed as variadic1184or untyped arguments. As a consequence, some caution must be taken when using1185certain library facilities with ``_Float16``; for example, there is no ``printf`` format1186specifier for ``_Float16``, and (unlike ``float``) it will not be implicitly promoted to1187``double`` when passed to ``printf``, so the programmer must explicitly cast it to1188``double`` before using it with an ``%f`` or similar specifier.1189 1190Messages on ``deprecated`` and ``unavailable`` Attributes1191=========================================================1192 1193An optional string message can be added to the ``deprecated`` and1194``unavailable`` attributes.  For example:1195 1196.. code-block:: c++1197 1198  void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));1199 1200If the deprecated or unavailable declaration is used, the message will be1201incorporated into the appropriate diagnostic:1202 1203.. code-block:: none1204 1205  harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!1206        [-Wdeprecated-declarations]1207    explode();1208    ^1209 1210Query for this feature with1211``__has_extension(attribute_deprecated_with_message)`` and1212``__has_extension(attribute_unavailable_with_message)``.1213 1214Attributes on Enumerators1215=========================1216 1217Clang allows attributes to be written on individual enumerators.  This allows1218enumerators to be deprecated, made unavailable, etc.  The attribute must appear1219after the enumerator name and before any initializer, like so:1220 1221.. code-block:: c++1222 1223  enum OperationMode {1224    OM_Invalid,1225    OM_Normal,1226    OM_Terrified __attribute__((deprecated)),1227    OM_AbortOnError __attribute__((deprecated)) = 41228  };1229 1230Attributes on the ``enum`` declaration do not apply to individual enumerators.1231 1232Query for this feature with ``__has_extension(enumerator_attributes)``.1233 1234C++11 Attributes on using-declarations1235======================================1236 1237Clang allows C++-style ``[[]]`` attributes to be written on using-declarations.1238For instance:1239 1240.. code-block:: c++1241 1242  [[clang::using_if_exists]] using foo::bar;1243  using foo::baz [[clang::using_if_exists]];1244 1245You can test for support for this extension with1246``__has_extension(cxx_attributes_on_using_declarations)``.1247 1248'User-Specified' System Frameworks1249==================================1250 1251Clang provides a mechanism by which frameworks can be built in such a way that1252they will always be treated as being "system frameworks", even if they are not1253present in a system framework directory.  This can be useful to system1254framework developers who want to be able to test building other applications1255with development builds of their framework, including the manner in which the1256compiler changes warning behavior for system headers.1257 1258Framework developers can opt-in to this mechanism by creating a1259"``.system_framework``" file at the top-level of their framework.  That is, the1260framework should have contents like:1261 1262.. code-block:: none1263 1264  .../TestFramework.framework1265  .../TestFramework.framework/.system_framework1266  .../TestFramework.framework/Headers1267  .../TestFramework.framework/Headers/TestFramework.h1268  ...1269 1270Clang will treat the presence of this file as an indicator that the framework1271should be treated as a system framework, regardless of how it was found in the1272framework search path.  For consistency, we recommend that such files never be1273included in installed versions of the framework.1274 1275Checks for Standard Language Features1276=====================================1277 1278The ``__has_feature`` macro can be used to query if certain standard language1279features are enabled.  The ``__has_extension`` macro can be used to query if1280language features are available as an extension when compiling for a standard1281which does not provide them.  The features which can be tested are listed here.1282 1283Since Clang 3.4, the C++ SD-6 feature test macros are also supported.1284These are macros with names of the form ``__cpp_<feature_name>``, and are1285intended to be a portable way to query the supported features of the compiler.1286See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for1287information on the version of SD-6 supported by each Clang release, and the1288macros provided by that revision of the recommendations.1289 1290C++981291-----1292 1293The features listed below are part of the C++98 standard.  These features are1294enabled by default when compiling C++ code.1295 1296C++ exceptions1297^^^^^^^^^^^^^^1298 1299Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been1300enabled.  For example, compiling code with ``-fno-exceptions`` disables C++1301exceptions.1302 1303C++ RTTI1304^^^^^^^^1305 1306Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled.  For1307example, compiling code with ``-fno-rtti`` disables the use of RTTI.1308 1309C++111310-----1311 1312The features listed below are part of the C++11 standard.  As a result, all1313these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option1314when compiling C++ code.1315 1316C++11 SFINAE includes access control1317^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1318 1319Use ``__has_feature(cxx_access_control_sfinae)`` or1320``__has_extension(cxx_access_control_sfinae)`` to determine whether1321access-control errors (e.g., calling a private constructor) are considered to1322be template argument deduction errors (aka SFINAE errors), per `C++ DR11701323<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.1324 1325C++11 alias templates1326^^^^^^^^^^^^^^^^^^^^^1327 1328Use ``__has_feature(cxx_alias_templates)`` or1329``__has_extension(cxx_alias_templates)`` to determine if support for C++11's1330alias declarations and alias templates is enabled.1331 1332C++11 alignment specifiers1333^^^^^^^^^^^^^^^^^^^^^^^^^^1334 1335Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to1336determine if support for alignment specifiers using ``alignas`` is enabled.1337 1338Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to1339determine if support for the ``alignof`` keyword is enabled.1340 1341C++11 attributes1342^^^^^^^^^^^^^^^^1343 1344Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to1345determine if support for attribute parsing with C++11's square bracket notation1346is enabled.1347 1348C++11 generalized constant expressions1349^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1350 1351Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized1352constant expressions (e.g., ``constexpr``) is enabled.1353 1354C++11 ``decltype()``1355^^^^^^^^^^^^^^^^^^^^1356 1357Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to1358determine if support for the ``decltype()`` specifier is enabled.  C++11's1359``decltype`` does not require type-completeness of a function call expression.1360Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or1361``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if1362support for this feature is enabled.1363 1364C++11 default template arguments in function templates1365^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1366 1367Use ``__has_feature(cxx_default_function_template_args)`` or1368``__has_extension(cxx_default_function_template_args)`` to determine if support1369for default template arguments in function templates is enabled.1370 1371C++11 ``default``\ ed functions1372^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1373 1374Use ``__has_feature(cxx_defaulted_functions)`` or1375``__has_extension(cxx_defaulted_functions)`` to determine if support for1376defaulted function definitions (with ``= default``) is enabled.1377 1378C++11 delegating constructors1379^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1380 1381Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for1382delegating constructors is enabled.1383 1384C++11 ``deleted`` functions1385^^^^^^^^^^^^^^^^^^^^^^^^^^^1386 1387Use ``__has_feature(cxx_deleted_functions)`` or1388``__has_extension(cxx_deleted_functions)`` to determine if support for deleted1389function definitions (with ``= delete``) is enabled.1390 1391C++11 explicit conversion functions1392^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1393 1394Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for1395``explicit`` conversion functions is enabled.1396 1397C++11 generalized initializers1398^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1399 1400Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for1401generalized initializers (using braced lists and ``std::initializer_list``) is1402enabled.1403 1404C++11 implicit move constructors/assignment operators1405^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1406 1407Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly1408generate move constructors and move assignment operators where needed.1409 1410C++11 inheriting constructors1411^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1412 1413Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for1414inheriting constructors is enabled.1415 1416C++11 inline namespaces1417^^^^^^^^^^^^^^^^^^^^^^^1418 1419Use ``__has_feature(cxx_inline_namespaces)`` or1420``__has_extension(cxx_inline_namespaces)`` to determine if support for inline1421namespaces is enabled.1422 1423C++11 lambdas1424^^^^^^^^^^^^^1425 1426Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to1427determine if support for lambdas is enabled.1428 1429C++11 local and unnamed types as template arguments1430^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1431 1432Use ``__has_feature(cxx_local_type_template_args)`` or1433``__has_extension(cxx_local_type_template_args)`` to determine if support for1434local and unnamed types as template arguments is enabled.1435 1436C++11 noexcept1437^^^^^^^^^^^^^^1438 1439Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to1440determine if support for noexcept exception specifications is enabled.1441 1442C++11 in-class non-static data member initialization1443^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1444 1445Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class1446initialization of non-static data members is enabled.1447 1448C++11 ``nullptr``1449^^^^^^^^^^^^^^^^^1450 1451Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to1452determine if support for ``nullptr`` is enabled.1453 1454C++11 ``override control``1455^^^^^^^^^^^^^^^^^^^^^^^^^^1456 1457Use ``__has_feature(cxx_override_control)`` or1458``__has_extension(cxx_override_control)`` to determine if support for the1459override control keywords is enabled.1460 1461C++11 reference-qualified functions1462^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1463 1464Use ``__has_feature(cxx_reference_qualified_functions)`` or1465``__has_extension(cxx_reference_qualified_functions)`` to determine if support1466for reference-qualified functions (e.g., member functions with ``&`` or ``&&``1467applied to ``*this``) is enabled.1468 1469C++11 range-based ``for`` loop1470^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1471 1472Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to1473determine if support for the range-based for loop is enabled.1474 1475C++11 raw string literals1476^^^^^^^^^^^^^^^^^^^^^^^^^1477 1478Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw1479string literals (e.g., ``R"x(foo\bar)x"``) is enabled.1480 1481C++11 rvalue references1482^^^^^^^^^^^^^^^^^^^^^^^1483 1484Use ``__has_feature(cxx_rvalue_references)`` or1485``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue1486references is enabled.1487 1488C++11 ``static_assert()``1489^^^^^^^^^^^^^^^^^^^^^^^^^1490 1491Use ``__has_feature(cxx_static_assert)`` or1492``__has_extension(cxx_static_assert)`` to determine if support for compile-time1493assertions using ``static_assert`` is enabled.1494 1495C++11 ``thread_local``1496^^^^^^^^^^^^^^^^^^^^^^1497 1498Use ``__has_feature(cxx_thread_local)`` to determine if support for1499``thread_local`` variables is enabled.1500 1501C++11 type inference1502^^^^^^^^^^^^^^^^^^^^1503 1504Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to1505determine C++11 type inference is supported using the ``auto`` specifier.  If1506this is disabled, ``auto`` will instead be a storage class specifier, as in C1507or C++98.1508 1509C++11 strongly typed enumerations1510^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1511 1512Use ``__has_feature(cxx_strong_enums)`` or1513``__has_extension(cxx_strong_enums)`` to determine if support for strongly1514typed, scoped enumerations is enabled.1515 1516C++11 trailing return type1517^^^^^^^^^^^^^^^^^^^^^^^^^^1518 1519Use ``__has_feature(cxx_trailing_return)`` or1520``__has_extension(cxx_trailing_return)`` to determine if support for the1521alternate function declaration syntax with trailing return type is enabled.1522 1523C++11 Unicode string literals1524^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1525 1526Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode1527string literals is enabled.1528 1529C++11 unrestricted unions1530^^^^^^^^^^^^^^^^^^^^^^^^^1531 1532Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for1533unrestricted unions is enabled.1534 1535C++11 user-defined literals1536^^^^^^^^^^^^^^^^^^^^^^^^^^^1537 1538Use ``__has_feature(cxx_user_literals)`` to determine if support for1539user-defined literals is enabled.1540 1541C++11 variadic templates1542^^^^^^^^^^^^^^^^^^^^^^^^1543 1544Use ``__has_feature(cxx_variadic_templates)`` or1545``__has_extension(cxx_variadic_templates)`` to determine if support for1546variadic templates is enabled.1547 1548C++141549-----1550 1551The features listed below are part of the C++14 standard.  As a result, all1552these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option1553when compiling C++ code.1554 1555C++14 binary literals1556^^^^^^^^^^^^^^^^^^^^^1557 1558Use ``__has_feature(cxx_binary_literals)`` or1559``__has_extension(cxx_binary_literals)`` to determine whether1560binary literals (for instance, ``0b10010``) are recognized. Clang supports this1561feature as an extension in all language modes.1562 1563C++14 contextual conversions1564^^^^^^^^^^^^^^^^^^^^^^^^^^^^1565 1566Use ``__has_feature(cxx_contextual_conversions)`` or1567``__has_extension(cxx_contextual_conversions)`` to determine if the C++14 rules1568are used when performing an implicit conversion for an array bound in a1569*new-expression*, the operand of a *delete-expression*, an integral constant1570expression, or a condition in a ``switch`` statement.1571 1572C++14 decltype(auto)1573^^^^^^^^^^^^^^^^^^^^1574 1575Use ``__has_feature(cxx_decltype_auto)`` or1576``__has_extension(cxx_decltype_auto)`` to determine if support1577for the ``decltype(auto)`` placeholder type is enabled.1578 1579C++14 default initializers for aggregates1580^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1581 1582Use ``__has_feature(cxx_aggregate_nsdmi)`` or1583``__has_extension(cxx_aggregate_nsdmi)`` to determine if support1584for default initializers in aggregate members is enabled.1585 1586C++14 digit separators1587^^^^^^^^^^^^^^^^^^^^^^1588 1589Use ``__cpp_digit_separators`` to determine if support for digit separators1590using single quotes (for instance, ``10'000``) is enabled. At this time, there1591is no corresponding ``__has_feature`` name.1592 1593C++14 generalized lambda capture1594^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1595 1596Use ``__has_feature(cxx_init_captures)`` or1597``__has_extension(cxx_init_captures)`` to determine if support for1598lambda captures with explicit initializers is enabled1599(for instance, ``[n(0)] { return ++n; }``).1600 1601C++14 generic lambdas1602^^^^^^^^^^^^^^^^^^^^^1603 1604Use ``__has_feature(cxx_generic_lambdas)`` or1605``__has_extension(cxx_generic_lambdas)`` to determine if support for generic1606(polymorphic) lambdas is enabled1607(for instance, ``[] (auto x) { return x + 1; }``).1608 1609C++14 relaxed constexpr1610^^^^^^^^^^^^^^^^^^^^^^^1611 1612Use ``__has_feature(cxx_relaxed_constexpr)`` or1613``__has_extension(cxx_relaxed_constexpr)`` to determine if variable1614declarations, local variable modification, and control flow constructs1615are permitted in ``constexpr`` functions.1616 1617C++14 return type deduction1618^^^^^^^^^^^^^^^^^^^^^^^^^^^1619 1620Use ``__has_feature(cxx_return_type_deduction)`` or1621``__has_extension(cxx_return_type_deduction)`` to determine if support1622for return type deduction for functions (using ``auto`` as a return type)1623is enabled.1624 1625C++14 runtime-sized arrays1626^^^^^^^^^^^^^^^^^^^^^^^^^^1627 1628Use ``__has_feature(cxx_runtime_array)`` or1629``__has_extension(cxx_runtime_array)`` to determine if support1630for arrays of runtime bound (a restricted form of variable-length arrays)1631is enabled.1632Clang's implementation of this feature is incomplete.1633 1634C++14 variable templates1635^^^^^^^^^^^^^^^^^^^^^^^^1636 1637Use ``__has_feature(cxx_variable_templates)`` or1638``__has_extension(cxx_variable_templates)`` to determine if support for1639templated variable declarations is enabled.1640 1641C++ type aware allocators1642^^^^^^^^^^^^^^^^^^^^^^^^^1643 1644Use ``__has_extension(cxx_type_aware_allocators)`` to determine the existence of1645support for the future C++2d type aware allocator feature. For full details, see1646:doc:`C++ Type Aware Allocators <CXXTypeAwareAllocators>` for additional details.1647 1648C111649---1650 1651The features listed below are part of the C11 standard.  As a result, all these1652features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when1653compiling C code.  Additionally, because these features are all1654backward-compatible, they are available as extensions in all language modes.1655 1656C11 alignment specifiers1657^^^^^^^^^^^^^^^^^^^^^^^^1658 1659Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine1660if support for alignment specifiers using ``_Alignas`` is enabled.1661 1662Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine1663if support for the ``_Alignof`` keyword is enabled.1664 1665C11 atomic operations1666^^^^^^^^^^^^^^^^^^^^^1667 1668Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine1669if support for atomic types using ``_Atomic`` is enabled.  Clang also provides1670:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement1671the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use1672``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header1673is available.1674 1675Clang will use the system's ``<stdatomic.h>`` header when one is available, and1676will otherwise use its own. When using its own, implementations of the atomic1677operations are provided as macros. In the cases where C11 also requires a real1678function, this header provides only the declaration of that function (along1679with a shadowing macro implementation), and you must link to a library which1680provides a definition of the function if you use it instead of the macro.1681 1682C11 generic selections1683^^^^^^^^^^^^^^^^^^^^^^1684 1685Use ``__has_feature(c_generic_selections)`` or1686``__has_extension(c_generic_selections)`` to determine if support for generic1687selections is enabled.1688 1689As an extension, the C11 generic selection expression is available in all1690languages supported by Clang.  The syntax is the same as that given in the C111691standard.1692 1693In C, type compatibility is decided according to the rules given in the1694appropriate standard, but in C++, which lacks the type compatibility rules used1695in C, types are considered compatible only if they are equivalent.1696 1697Clang also supports an extended form of ``_Generic`` with a controlling type1698rather than a controlling expression. Unlike with a controlling expression, a1699controlling type argument does not undergo any conversions and thus is suitable1700for use when trying to match qualified types, incomplete types, or function1701types. Variable-length array types lack the necessary compile-time information1702to resolve which association they match with and thus are not allowed as a1703controlling type argument.1704 1705Use ``__has_extension(c_generic_selection_with_controlling_type)`` to determine1706if support for this extension is enabled.1707 1708C11 ``_Static_assert()``1709^^^^^^^^^^^^^^^^^^^^^^^^1710 1711Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``1712to determine if support for compile-time assertions using ``_Static_assert`` is1713enabled.1714 1715C11 ``_Thread_local``1716^^^^^^^^^^^^^^^^^^^^^1717 1718Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)``1719to determine if support for ``_Thread_local`` variables is enabled.1720 1721C2y1722---1723 1724The features listed below are part of the C2y standard.  As a result, all these1725features are enabled with the ``-std=c2y`` or ``-std=gnu2y`` option when1726compiling C code.1727 1728C2y ``_Countof``1729^^^^^^^^^^^^^^^^1730 1731Use ``__has_feature(c_countof)`` (in C2y or later mode) or1732``__has_extension(c_countof)`` (in C23 or earlier mode) to determine if support1733for the ``_Countof`` operator is enabled. This feature is not available in C++1734mode.1735 1736 1737Modules1738-------1739 1740Use ``__has_feature(modules)`` to determine if Modules have been enabled.1741For example, compiling code with ``-fmodules`` enables the use of Modules.1742 1743More information can be found `here <https://clang.llvm.org/docs/Modules.html>`_.1744 1745Language Extensions Back-ported to Previous Standards1746=====================================================1747 1748============================================= ================================ ============= =============1749Feature                                       Feature Test Macro               Introduced In Backported To1750============================================= ================================ ============= =============1751variadic templates                            __cpp_variadic_templates         C++11         C++031752Alias templates                               __cpp_alias_templates            C++11         C++031753Non-static data member initializers           __cpp_nsdmi                      C++11         C++031754Range-based ``for`` loop                      __cpp_range_based_for            C++11         C++031755RValue references                             __cpp_rvalue_references          C++11         C++031756Attributes                                    __cpp_attributes                 C++11         C++031757Lambdas                                       __cpp_lambdas                    C++11         C++031758Generalized lambda captures                   __cpp_init_captures              C++14         C++031759Generic lambda expressions                    __cpp_generic_lambdas            C++14         C++031760variable templates                            __cpp_variable_templates         C++14         C++031761Binary literals                               __cpp_binary_literals            C++14         C++031762Relaxed constexpr                             __cpp_constexpr                  C++14         C++111763Static assert with no message                 __cpp_static_assert >= 201411L   C++17         C++111764Pack expansion in generalized lambda-capture  __cpp_init_captures              C++17         C++031765``if constexpr``                              __cpp_if_constexpr               C++17         C++111766fold expressions                              __cpp_fold_expressions           C++17         C++031767Lambda capture of \*this by value             __cpp_capture_star_this          C++17         C++031768Attributes on enums                           __cpp_enumerator_attributes      C++17         C++031769Guaranteed copy elision                       __cpp_guaranteed_copy_elision    C++17         C++031770Hexadecimal floating literals                 __cpp_hex_float                  C++17         C++031771``inline`` variables                          __cpp_inline_variables           C++17         C++031772Attributes on namespaces                      __cpp_namespace_attributes       C++17         C++111773Structured bindings                           __cpp_structured_bindings        C++17         C++031774template template arguments                   __cpp_template_template_args     C++17         C++031775Familiar template syntax for generic lambdas  __cpp_generic_lambdas            C++20         C++031776``static operator[]``                         __cpp_multidimensional_subscript C++20         C++031777Designated initializers                       __cpp_designated_initializers    C++20         C++031778Conditional ``explicit``                      __cpp_conditional_explicit       C++20         C++031779``using enum``                                __cpp_using_enum                 C++20         C++031780``if consteval``                              __cpp_if_consteval               C++23         C++201781``static operator()``                         __cpp_static_call_operator       C++23         C++031782Attributes on Lambda-Expressions                                               C++23         C++111783Attributes on Structured Bindings             __cpp_structured_bindings        C++26         C++031784Packs in Structured Bindings                  __cpp_structured_bindings        C++26         C++031785Structured binding declaration as a condition __cpp_structured_bindings        C++26         C++981786Static assert with user-generated message     __cpp_static_assert >= 202306L   C++26         C++111787Pack Indexing                                 __cpp_pack_indexing              C++26         C++031788``= delete ("should have a reason");``        __cpp_deleted_function           C++26         C++031789Variadic Friends                              __cpp_variadic_friend            C++26         C++031790Trivial Relocatability                        __cpp_trivial_relocatability     C++26         C++031791--------------------------------------------- -------------------------------- ------------- -------------1792Designated initializers (N494)                                                 C99           C891793``_Complex`` (N693)                                                            C99           C89, C++1794``_Bool`` (N815)                                                               C99           C891795Variable-length arrays (N683)                                                  C99           C89, C++1796Flexible array members                                                         C99           C89, C++1797static and type quals in arrays                                                C99           C891798``long long`` (N601)                                                           C99           C891799Hexadecimal floating constants (N308)                                          C99           C891800Compound literals (N716)                                                       C99           C89, C++1801``//`` comments (N644)                                                         C99           C891802Mixed declarations and code (N740)                                             C99           C891803init-statement in for (N740)                                                   C99           C891804Variadic macros (N707)                                                         C99           C891805Empty macro arguments (N570)                                                   C99           C891806Trailing comma in enum declaration                                             C99           C891807Implicit ``return 0`` in ``main``                                              C99           C891808``__func__`` (N611)                                                            C99           C891809``_Generic`` (N1441)                                                           C11           C89, C++1810``_Static_assert`` (N1330)                                                     C11           C89, C++1811``_Atomic`` (N1485)                                                            C11           C89, C++1812``_Thread_local`` (N1364)                                                      C11           C89, C++1813Array & element qualification (N2607)                                          C23           C891814Attributes (N2335)                                                             C23           C891815``#embed`` (N3017)                                                             C23           C89, C++1816Enum with fixed underlying type (N3030)                                        C23           C891817``#warning`` (N2686)                                                           C23           C891818``_BitInt`` (N3035)                                                            C23           C89, C++1819Binary literals (N2549)                                                        C23           C891820Unnamed parameters in a function definition                                    C23           C891821Free positioning of labels (N2508)                                             C23           C891822``#elifdef`` (N2645)                                                           C23           C891823``__has_include`` (N2799)                                                      C23           C891824Octal literals prefixed with ``0o`` or ``0O``                                  C2y           C89, C++1825``_Countof`` (N3369, N3469)                                                    C2y           C891826``_Generic`` with a type operand (N3260)                                       C2y           C89, C++1827``++``/``--`` on ``_Complex`` value (N3259)                                    C2y           C89, C++1828``__COUNTER__`` (N3457)                                                        C2y           C89, C++1829============================================= ================================ ============= =============1830 1831Builtin type aliases1832====================1833 1834Clang provides a few builtin aliases to improve the throughput of certain metaprogramming facilities.1835 1836__builtin_common_reference1837--------------------------1838 1839.. code-block:: c++1840 1841  template <template <class, class, template <class> class, template <class> class> class BasicCommonReferenceT,1842            template <class... Args> CommonTypeT,1843            template <class> HasTypeMember,1844            class HasNoTypeMember,1845            class... Ts>1846  using __builtin_common_reference = ...;1847 1848This alias is used for implementing ``std::common_reference``. If ``std::common_reference`` should contain a ``type``1849member, it is an alias to ``HasTypeMember<TheCommonReference>``. Otherwse it is an alias to ``HasNoTypeMember``. The1850``CommonTypeT`` is usually ``std::common_type_t``. ``BasicCommonReferenceT`` is usually an alias template to1851``basic_common_reference<T, U, TX, UX>::type``.1852 1853__builtin_common_type1854---------------------1855 1856.. code-block:: c++1857 1858  template <template <class... Args> class BaseTemplate,1859            template <class TypeMember> class HasTypeMember,1860            class HasNoTypeMember,1861            class... Ts>1862  using __builtin_common_type = ...;1863 1864This alias is used for implementing ``std::common_type``. If ``std::common_type`` should contain a ``type`` member,1865it is an alias to ``HasTypeMember<TheCommonType>``. Otherwise it is an alias to ``HasNoTypeMember``. The1866``BaseTemplate`` is usually ``std::common_type``. ``Ts`` are the arguments to ``std::common_type``.1867 1868__type_pack_element1869-------------------1870 1871.. code-block:: c++1872 1873  template <std::size_t Index, class... Ts>1874  using __type_pack_element = ...;1875 1876This alias returns the type at ``Index`` in the parameter pack ``Ts``.1877 1878__make_integer_seq1879------------------1880 1881.. code-block:: c++1882 1883  template <template <class IntSeqT, IntSeqT... Ints> class IntSeq, class T, T N>1884  using __make_integer_seq = ...;1885 1886This alias returns ``IntSeq`` instantiated with ``IntSeqT = T``and ``Ints`` being the pack ``0, ..., N - 1``.1887 1888__builtin_dedup_pack1889--------------------1890 1891.. code-block:: c++1892 1893  template <class... Ts>1894  using __builtin_dedup_pack = ...;1895 1896This alias takes a template parameter pack ``Ts`` and produces a new unexpanded pack containing the unique types1897from ``Ts``, with the order of the first occurrence of each type preserved.1898It is useful in template metaprogramming to normalize type lists.1899 1900The resulting pack can be expanded in contexts like template argument lists or base specifiers.1901 1902**Example of Use**:1903 1904.. code-block:: c++1905 1906  template <typename...> struct TypeList;1907 1908  // The resulting type is TypeList<int, double, char>1909  template <typename ...ExtraTypes>1910  using MyTypeList = TypeList<__builtin_dedup_pack<int, double, int, char, double, ExtraTypes...>...>;1911 1912**Limitations**:1913 1914* This builtin can only be used inside a template.1915* The resulting pack is currently only supported for expansion in template argument lists and base specifiers.1916* This builtin cannot be assigned to a template template parameter.1917 1918 1919Type Trait Primitives1920=====================1921 1922Type trait primitives are special builtin constant expressions that can be used1923by the standard C++ library to facilitate or simplify the implementation of1924user-facing type traits in the ``<type_traits>`` header.1925 1926They are not intended to be used directly by user code because they are1927implementation-defined and subject to change -- as such they're tied closely to1928the supported set of system headers, currently:1929 1930* LLVM's own libc++1931* GNU libstdc++1932* The Microsoft standard C++ library1933 1934Clang supports the `GNU C++ type traits1935<https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the1936`Microsoft Visual C++ type traits1937<https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_,1938as well as nearly all of the1939`Embarcadero C++ type traits1940<http://docwiki.embarcadero.com/RADStudio/Rio/en/Type_Trait_Functions_(C%2B%2B11)_Index>`_.1941 1942The following type trait primitives are supported by Clang. Those traits marked1943(C++) provide implementations for type traits specified by the C++ standard;1944``__X(...)`` has the same semantics and constraints as the corresponding1945``std::X_t<...>`` or ``std::X_v<...>`` type trait.1946 1947* ``__array_rank(type)`` (Embarcadero):1948  Returns the number of levels of array in the type ``type``:1949  ``0`` if ``type`` is not an array type, and1950  ``__array_rank(element) + 1`` if ``type`` is an array of ``element``.1951* ``__array_extent(type, dim)`` (Embarcadero):1952  The ``dim``'th array bound in the type ``type``, or ``0`` if1953  ``dim >= __array_rank(type)``.1954* ``__builtin_is_implicit_lifetime`` (C++, GNU, Microsoft)1955* ``__builtin_is_virtual_base_of`` (C++, GNU, Microsoft)1956* ``__can_pass_in_regs`` (C++)1957  Returns whether a class can be passed in registers under the current1958  ABI. This type can only be applied to unqualified class types.1959  This is not a portable type trait.1960* ``__has_nothrow_assign`` (GNU, Microsoft, Embarcadero):1961  Deprecated, use ``__is_nothrow_assignable`` instead.1962* ``__has_nothrow_move_assign`` (GNU, Microsoft):1963  Deprecated, use ``__is_nothrow_assignable`` instead.1964* ``__has_nothrow_copy`` (GNU, Microsoft):1965  Deprecated, use ``__is_nothrow_constructible`` instead.1966* ``__has_nothrow_constructor`` (GNU, Microsoft):1967  Deprecated, use ``__is_nothrow_constructible`` instead.1968* ``__has_trivial_assign`` (GNU, Microsoft, Embarcadero):1969  Deprecated, use ``__is_trivially_assignable`` instead.1970* ``__has_trivial_move_assign`` (GNU, Microsoft):1971  Deprecated, use ``__is_trivially_assignable`` instead.1972* ``__has_trivial_copy`` (GNU, Microsoft):1973  Deprecated, use ``__is_trivially_copyable`` instead.1974* ``__has_trivial_constructor`` (GNU, Microsoft):1975  Deprecated, use ``__is_trivially_constructible`` instead.1976* ``__has_trivial_move_constructor`` (GNU, Microsoft):1977  Deprecated, use ``__is_trivially_constructible`` instead.1978* ``__has_trivial_destructor`` (GNU, Microsoft, Embarcadero):1979  Deprecated, use ``__is_trivially_destructible`` instead.1980* ``__has_unique_object_representations`` (C++, GNU)1981* ``__has_virtual_destructor`` (C++, GNU, Microsoft, Embarcadero)1982* ``__is_abstract`` (C++, GNU, Microsoft, Embarcadero)1983* ``__is_aggregate`` (C++, GNU, Microsoft)1984* ``__is_arithmetic`` (C++, Embarcadero)1985* ``__is_array`` (C++, Embarcadero)1986* ``__is_assignable`` (C++, MSVC 2015)1987* ``__is_base_of`` (C++, GNU, Microsoft, Embarcadero)1988* ``__is_bounded_array`` (C++, GNU, Microsoft, Embarcadero)1989* ``__is_class`` (C++, GNU, Microsoft, Embarcadero)1990* ``__is_complete_type(type)`` (Embarcadero):1991  Return ``true`` if ``type`` is a complete type.1992  Warning: this trait is dangerous because it can return different values at1993  different points in the same program.1994* ``__is_compound`` (C++, Embarcadero)1995* ``__is_const`` (C++, Embarcadero)1996* ``__is_constructible`` (C++, MSVC 2013)1997* ``__is_convertible`` (C++, Embarcadero)1998* ``__is_nothrow_convertible`` (C++, GNU)1999* ``__is_convertible_to`` (Microsoft):2000  Synonym for ``__is_convertible``.2001* ``__is_destructible`` (C++, MSVC 2013)2002* ``__is_empty`` (C++, GNU, Microsoft, Embarcadero)2003* ``__is_enum`` (C++, GNU, Microsoft, Embarcadero)2004* ``__is_final`` (C++, GNU, Microsoft)2005* ``__is_floating_point`` (C++, Embarcadero)2006* ``__is_function`` (C++, Embarcadero)2007* ``__is_fundamental`` (C++, Embarcadero)2008* ``__is_integral`` (C++, Embarcadero)2009* ``__is_interface_class`` (Microsoft):2010  Returns ``false``, even for types defined with ``__interface``.2011* ``__is_layout_compatible`` (C++, GNU, Microsoft)2012* ``__is_literal`` (Clang):2013  Synonym for ``__is_literal_type``.2014* ``__is_literal_type`` (C++, GNU, Microsoft):2015  Note, the corresponding standard trait was deprecated in C++172016  and removed in C++20.2017* ``__is_lvalue_reference`` (C++, Embarcadero)2018* ``__is_member_object_pointer`` (C++, Embarcadero)2019* ``__is_member_function_pointer`` (C++, Embarcadero)2020* ``__is_member_pointer`` (C++, Embarcadero)2021* ``__is_nothrow_assignable`` (C++, MSVC 2013)2022* ``__is_nothrow_constructible`` (C++, MSVC 2013)2023* ``__is_nothrow_destructible`` (C++, MSVC 2013)2024* ``__is_object`` (C++, Embarcadero)2025* ``__is_pod`` (C++, GNU, Microsoft, Embarcadero):2026  Note, the corresponding standard trait was deprecated in C++20.2027* ``__is_pointer`` (C++, Embarcadero)2028* ``__is_pointer_interconvertible_base_of`` (C++, GNU, Microsoft)2029* ``__is_polymorphic`` (C++, GNU, Microsoft, Embarcadero)2030* ``__is_reference`` (C++, Embarcadero)2031* ``__is_rvalue_reference`` (C++, Embarcadero)2032* ``__is_same`` (C++, Embarcadero)2033* ``__is_same_as`` (GCC): Synonym for ``__is_same``.2034* ``__is_scalar`` (C++, Embarcadero)2035* ``__is_scoped_enum`` (C++, GNU, Microsoft, Embarcadero)2036* ``__is_sealed`` (Microsoft):2037  Synonym for ``__is_final``.2038* ``__is_signed`` (C++, Embarcadero):2039  Returns false for enumeration types, and returns true for floating-point2040  types. Note, before Clang 10, returned true for enumeration types if the2041  underlying type was signed, and returned false for floating-point types.2042* ``__is_standard_layout`` (C++, GNU, Microsoft, Embarcadero)2043* ``__is_trivial`` (C++, GNU, Microsoft, Embarcadero)2044* ``__is_trivially_assignable`` (C++, GNU, Microsoft)2045* ``__is_trivially_constructible`` (C++, GNU, Microsoft)2046* ``__is_trivially_copyable`` (C++, GNU, Microsoft)2047* ``__is_trivially_destructible`` (C++, MSVC 2013)2048* ``__is_trivially_relocatable`` (Clang) (Deprecated,2049  use ``__builtin_is_cpp_trivially_relocatable`` instead).2050  Returns true if moving an object2051  of the given type, and then destroying the source object, is known to be2052  functionally equivalent to copying the underlying bytes and then dropping the2053  source object on the floor. This is true of trivial types,2054  C++26 relocatable types, and types which2055  were made trivially relocatable via the ``clang::trivial_abi`` attribute.2056  This trait is deprecated and should be replaced by2057  ``__builtin_is_cpp_trivially_relocatable``. Note, however, that it is generally2058  unsafe to relocate a C++-relocatable type with ``memcpy`` or ``memmove``;2059  use ``__builtin_trivially_relocate``.2060* ``__builtin_is_cpp_trivially_relocatable`` (C++): Returns true if an object2061  is trivially relocatable, as defined by the C++26 standard [meta.unary.prop].2062  Note that when relocating the caller code should ensure that if the object is polymorphic,2063  the dynamic type is of the most derived type. Padding bytes should not be copied.2064* ``__builtin_is_replaceable`` (C++): Returns true if an object2065  is replaceable, as defined by the C++26 standard [meta.unary.prop].2066* ``__is_trivially_equality_comparable`` (Clang): Returns true if comparing two2067  objects of the provided type is known to be equivalent to comparing their2068  object representations. Note that types containing padding bytes are never2069  trivially equality comparable.2070* ``__is_unbounded_array`` (C++, GNU, Microsoft, Embarcadero)2071* ``__is_union`` (C++, GNU, Microsoft, Embarcadero)2072* ``__is_unsigned`` (C++, Embarcadero):2073  Returns false for enumeration types. Note, before Clang 13, returned true for2074  enumeration types if the underlying type was unsigned.2075* ``__is_void`` (C++, Embarcadero)2076* ``__is_volatile`` (C++, Embarcadero)2077* ``__reference_binds_to_temporary(T, U)`` (Clang):  Determines whether a2078  reference of type ``T`` bound to an expression of type ``U`` would bind to a2079  materialized temporary object. If ``T`` is not a reference type, the result2080  is false. Note this trait will also return false when the initialization of2081  ``T`` from ``U`` is ill-formed.2082  Deprecated, use ``__reference_constructs_from_temporary``.2083* ``__reference_constructs_from_temporary(T, U)`` (C++)2084  Returns true if a reference ``T`` can be direct-initialized from a temporary of type2085  a non-cv-qualified ``U``.2086* ``__reference_converts_from_temporary(T, U)`` (C++)2087    Returns true if a reference ``T`` can be copy-initialized from a temporary of type2088    a non-cv-qualified ``U``.2089* ``__underlying_type`` (C++, GNU, Microsoft)2090* ``__builtin_lt_synthesizes_from_spaceship``, ``__builtin_gt_synthesizes_from_spaceship``,2091  ``__builtin_le_synthesizes_from_spaceship``, ``__builtin_ge_synthesizes_from_spaceship`` (Clang):2092  These builtins can be used to determine whether the corresponding operator is synthesized from a spaceship operator.2093 2094In addition, the following expression traits are supported:2095 2096* ``__is_lvalue_expr(e)`` (Embarcadero):2097  Returns true if ``e`` is an lvalue expression.2098  Deprecated, use ``__is_lvalue_reference(decltype((e)))`` instead.2099* ``__is_rvalue_expr(e)`` (Embarcadero):2100  Returns true if ``e`` is a prvalue expression.2101  Deprecated, use ``!__is_reference(decltype((e)))`` instead.2102 2103There are multiple ways to detect support for a type trait ``__X`` in the2104compiler, depending on the oldest version of Clang you wish to support.2105 2106* From Clang 10 onwards, ``__has_builtin(__X)`` can be used.2107* From Clang 6 onwards, ``!__is_identifier(__X)`` can be used.2108* From Clang 3 onwards, ``__has_feature(X)`` can be used, but only supports2109  the following traits:2110 2111  * ``__has_nothrow_assign``2112  * ``__has_nothrow_copy``2113  * ``__has_nothrow_constructor``2114  * ``__has_trivial_assign``2115  * ``__has_trivial_copy``2116  * ``__has_trivial_constructor``2117  * ``__has_trivial_destructor``2118  * ``__has_virtual_destructor``2119  * ``__is_abstract``2120  * ``__is_base_of``2121  * ``__is_class``2122  * ``__is_constructible``2123  * ``__is_convertible_to``2124  * ``__is_empty``2125  * ``__is_enum``2126  * ``__is_final``2127  * ``__is_literal``2128  * ``__is_standard_layout``2129  * ``__is_pod``2130  * ``__is_polymorphic``2131  * ``__is_sealed``2132  * ``__is_trivial``2133  * ``__is_trivially_assignable``2134  * ``__is_trivially_constructible``2135  * ``__is_trivially_copyable``2136  * ``__is_union``2137  * ``__underlying_type``2138 2139A simplistic usage example as might be seen in standard C++ headers follows:2140 2141.. code-block:: c++2142 2143  #if __has_builtin(__is_convertible_to)2144  template<typename From, typename To>2145  struct is_convertible_to {2146    static const bool value = __is_convertible_to(From, To);2147  };2148  #else2149  // Emulate type trait for compatibility with other compilers.2150  #endif2151 2152 2153.. _builtin_structured_binding_size-doc:2154 2155__builtin_structured_binding_size (C++)2156---------------------------------------2157 2158The ``__builtin_structured_binding_size(T)`` type trait returns2159the *structured binding size* ([dcl.struct.bind]) of type ``T``2160 2161This is equivalent to the size of the pack ``p`` in ``auto&& [...p] = declval<T&>();``.2162If the argument cannot be decomposed, ``__builtin_structured_binding_size(T)``2163is not a valid expression (``__builtin_structured_binding_size`` is SFINAE-friendly).2164 2165builtin arrays, builtin SIMD vectors,2166builtin complex types, *tuple-like* types, and decomposable class types2167are decomposable types.2168 2169A type is considered a valid *tuple-like* if ``std::tuple_size_v<T>`` is a valid expression,2170even if there is no valid ``std::tuple_element`` specialization or suitable2171``get`` function for that type.2172 2173.. code-block:: c++2174 2175  template<std::size_t Idx, typename T>2176  requires (Idx < __builtin_structured_binding_size(T))2177  decltype(auto) constexpr get_binding(T&& obj) {2178      auto && [...p] = std::forward<T>(obj);2179      return p...[Idx];2180  }2181  struct S { int a = 0, b = 42; };2182  static_assert(__builtin_structured_binding_size(S) == 2);2183  static_assert(get_binding<1>(S{}) == 42);2184 2185 2186Blocks2187======2188 2189The syntax and high-level language feature description is in2190:doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for2191the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.2192 2193Query for this feature with ``__has_extension(blocks)``.2194 2195ASM Goto with Output Constraints2196================================2197 2198Outputs may be used along any branches from the ``asm goto`` whether the2199branches are taken or not.2200 2201Query for this feature with ``__has_extension(gnu_asm_goto_with_outputs)``.2202 2203Prior to clang-16, the output may only be used safely when the indirect2204branches are not taken.  Query for this difference with2205``__has_extension(gnu_asm_goto_with_outputs_full)``.2206 2207When using tied-outputs (i.e., outputs that are inputs and outputs, not just2208outputs) with the `+r` constraint, there is a hidden input that's created2209before the label, so numeric references to operands must account for that.2210 2211.. code-block:: c++2212 2213  int foo(int x) {2214      // %0 and %1 both refer to x2215      // %l2 refers to err2216      asm goto("# %0 %1 %l2" : "+r"(x) : : : err);2217      return x;2218    err:2219      return -1;2220  }2221 2222This was changed to match GCC in clang-13; for better portability, symbolic2223references can be used instead of numeric references.2224 2225.. code-block:: c++2226 2227  int foo(int x) {2228      asm goto("# %[x] %l[err]" : [x]"+r"(x) : : : err);2229      return x;2230    err:2231      return -1;2232  }2233 2234ASM Goto versus Branch Target Enforcement2235=========================================2236 2237Some target architectures implement branch target enforcement, by requiring2238indirect (register-controlled) branch instructions to jump only to locations2239marked by a special instruction (such as AArch64 ``bti``).2240 2241The assembler code inside an ``asm goto`` statement is expected not to use a2242branch instruction of that kind to transfer control to any of its destination2243labels. Therefore, using a label in an ``asm goto`` statement does not cause2244clang to put a ``bti`` or equivalent instruction at the label.2245 2246Constexpr strings in GNU ASM statements2247=======================================2248 2249In C++11 mode (and greater), Clang supports specifying the template,2250constraints, and clobber strings with a parenthesized constant expression2251producing an object with the following member functions2252 2253.. code-block:: c++2254 2255  constexpr const char* data() const;2256  constexpr size_t size() const;2257 2258such as ``std::string``, ``std::string_view``, ``std::vector<char>``.2259This mechanism follows the same rules as ``static_assert`` messages in2260C++26, see ``[dcl.pre]/p12``.2261 2262Query for this feature with ``__has_extension(gnu_asm_constexpr_strings)``.2263 2264.. code-block:: c++2265 2266   int foo() {2267      asm((std::string_view("nop")) ::: (std::string_view("memory")));2268   }2269 2270 2271Objective-C Features2272====================2273 2274Related result types2275--------------------2276 2277According to Cocoa conventions, Objective-C methods with certain names2278("``init``", "``alloc``", etc.) always return objects that are an instance of2279the receiving class's type.  Such methods are said to have a "related result2280type", meaning that a message send to one of these methods will have the same2281static type as an instance of the receiver class.  For example, given the2282following classes:2283 2284.. code-block:: objc2285 2286  @interface NSObject2287  + (id)alloc;2288  - (id)init;2289  @end2290 2291  @interface NSArray : NSObject2292  @end2293 2294and this common initialization pattern2295 2296.. code-block:: objc2297 2298  NSArray *array = [[NSArray alloc] init];2299 2300the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because2301``alloc`` implicitly has a related result type.  Similarly, the type of the2302expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a2303related result type and its receiver is known to have the type ``NSArray *``.2304If neither ``alloc`` nor ``init`` had a related result type, the expressions2305would have had type ``id``, as declared in the method signature.2306 2307A method with a related result type can be declared by using the type2308``instancetype`` as its result type.  ``instancetype`` is a contextual keyword2309that is only permitted in the result type of an Objective-C method, e.g.2310 2311.. code-block:: objc2312 2313  @interface A2314  + (instancetype)constructAnA;2315  @end2316 2317The related result type can also be inferred for some methods.  To determine2318whether a method has an inferred related result type, the first word in the2319camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,2320and the method will have a related result type if its return type is compatible2321with the type of its class and if:2322 2323* the first word is "``alloc``" or "``new``", and the method is a class method,2324  or2325 2326* the first word is "``autorelease``", "``init``", "``retain``", or "``self``",2327  and the method is an instance method.2328 2329If a method with a related result type is overridden by a subclass method, the2330subclass method must also return a type that is compatible with the subclass2331type.  For example:2332 2333.. code-block:: objc2334 2335  @interface NSString : NSObject2336  - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString2337  @end2338 2339Related result types only affect the type of a message send or property access2340via the given method.  In all other respects, a method with a related result2341type is treated the same way as method that returns ``id``.2342 2343Use ``__has_feature(objc_instancetype)`` to determine whether the2344``instancetype`` contextual keyword is available.2345 2346Automatic reference counting2347----------------------------2348 2349Clang provides support for :doc:`automated reference counting2350<AutomaticReferenceCounting>` in Objective-C, which eliminates the need2351for manual ``retain``/``release``/``autorelease`` message sends.  There are three2352feature macros associated with automatic reference counting:2353``__has_feature(objc_arc)`` indicates the availability of automated reference2354counting in general, while ``__has_feature(objc_arc_weak)`` indicates that2355automated reference counting also includes support for ``__weak`` pointers to2356Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs2357are allowed to have fields that are pointers to Objective-C objects managed by2358automatic reference counting.2359 2360.. _objc-weak:2361 2362Weak references2363---------------2364 2365Clang supports ARC-style weak and unsafe references in Objective-C even2366outside of ARC mode.  Weak references must be explicitly enabled with2367the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))``2368to test whether they are enabled.  Unsafe references are enabled2369unconditionally.  ARC-style weak and unsafe references cannot be used2370when Objective-C garbage collection is enabled.2371 2372Except as noted below, the language rules for the ``__weak`` and2373``__unsafe_unretained`` qualifiers (and the ``weak`` and2374``unsafe_unretained`` property attributes) are just as laid out2375in the :doc:`ARC specification <AutomaticReferenceCounting>`.2376In particular, note that some classes do not support forming weak2377references to their instances, and note that special care must be2378taken when storing weak references in memory where initialization2379and deinitialization are outside the responsibility of the compiler2380(such as in ``malloc``-ed memory).2381 2382Loading from a ``__weak`` variable always implicitly retains the2383loaded value.  In non-ARC modes, this retain is normally balanced2384by an implicit autorelease.  This autorelease can be suppressed2385by performing the load in the receiver position of a ``-retain``2386message send (e.g., ``[weakReference retain]``); note that this performs2387only a single retain (the retain done when primitively loading from2388the weak reference).2389 2390For the most part, ``__unsafe_unretained`` in non-ARC modes is just the2391default behavior of variables and therefore is not needed.  However,2392it does have an effect on the semantics of block captures: normally,2393copying a block which captures an Objective-C object or block pointer2394causes the captured pointer to be retained or copied, respectively,2395but that behavior is suppressed when the captured variable is qualified2396with ``__unsafe_unretained``.2397 2398Note that the ``__weak`` qualifier formerly meant the GC qualifier in2399all non-ARC modes and was silently ignored outside of GC modes.  It now2400means the ARC-style qualifier in all non-GC modes and is no longer2401allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``.2402It is expected that ``-fobjc-weak`` will eventually be enabled by default2403in all non-GC Objective-C modes.2404 2405.. _objc-fixed-enum:2406 2407Enumerations with a fixed underlying type2408-----------------------------------------2409 2410Clang provides support for C++11 enumerations with a fixed underlying type2411within Objective-C and C `prior to C23 <https://open-std.org/JTC1/SC22/WG14/www/docs/n3030.htm>`_.  For example, one can write an enumeration type as:2412 2413.. code-block:: c++2414 2415  typedef enum : unsigned char { Red, Green, Blue } Color;2416 2417This specifies that the underlying type, which is used to store the enumeration2418value, is ``unsigned char``.2419 2420Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed2421underlying types is available in Objective-C.2422 2423Use ``__has_extension(c_fixed_enum)`` to determine whether support for fixed2424underlying types is available in C prior to C23. This will also report ``true`` in C232425and later modes as the functionality is available even if it's not an extension in2426those modes.2427 2428Use ``__has_feature(c_fixed_enum)`` to determine whether support for fixed2429underlying types is available in C23 and later.2430 2431Enumerations with no enumerators2432--------------------------------2433 2434Clang provides support for Microsoft extensions to support enumerations with no enumerators.2435 2436.. code-block:: c++2437 2438  typedef enum empty { } A;2439 2440 2441Interoperability with C++11 lambdas2442-----------------------------------2443 2444Clang provides interoperability between C++11 lambdas and blocks-based APIs, by2445permitting a lambda to be implicitly converted to a block pointer with the2446corresponding signature.  For example, consider an API such as ``NSArray``'s2447array-sorting method:2448 2449.. code-block:: objc2450 2451  - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;2452 2453``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult2454(^)(id, id)``, and parameters of this type are generally provided with block2455literals as arguments.  However, one can also use a C++11 lambda so long as it2456provides the same signature (in this case, accepting two parameters of type2457``id`` and returning an ``NSComparisonResult``):2458 2459.. code-block:: objc2460 2461  NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",2462                     @"String 02"];2463  const NSStringCompareOptions comparisonOptions2464    = NSCaseInsensitiveSearch | NSNumericSearch |2465      NSWidthInsensitiveSearch | NSForcedOrderingSearch;2466  NSLocale *currentLocale = [NSLocale currentLocale];2467  NSArray *sorted2468    = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {2469               NSRange string1Range = NSMakeRange(0, [s1 length]);2470               return [s1 compare:s2 options:comparisonOptions2471               range:string1Range locale:currentLocale];2472       }];2473  NSLog(@"sorted: %@", sorted);2474 2475This code relies on an implicit conversion from the type of the lambda2476expression (an unnamed, local class type called the *closure type*) to the2477corresponding block pointer type.  The conversion itself is expressed by a2478conversion operator in that closure type that produces a block pointer with the2479same signature as the lambda itself, e.g.,2480 2481.. code-block:: objc2482 2483  operator NSComparisonResult (^)(id, id)() const;2484 2485This conversion function returns a new block that simply forwards the two2486parameters to the lambda object (which it captures by copy), then returns the2487result.  The returned block is first copied (with ``Block_copy``) and then2488autoreleased.  As an optimization, if a lambda expression is immediately2489converted to a block pointer (as in the first example, above), then the block2490is not copied and autoreleased: rather, it is given the same lifetime as a2491block literal written at that point in the program, which avoids the overhead2492of copying a block to the heap in the common case.2493 2494The conversion from a lambda to a block pointer is only available in2495Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory2496management (autorelease).2497 2498Object Literals and Subscripting2499--------------------------------2500 2501Clang provides support for :doc:`Object Literals and Subscripting2502<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C2503programming patterns, makes programs more concise, and improves the safety of2504container creation.  There are several feature macros associated with object2505literals and subscripting: ``__has_feature(objc_array_literals)`` tests the2506availability of array literals; ``__has_feature(objc_dictionary_literals)``2507tests the availability of dictionary literals;2508``__has_feature(objc_subscripting)`` tests the availability of object2509subscripting.2510 2511Objective-C Autosynthesis of Properties2512---------------------------------------2513 2514Clang provides support for autosynthesis of declared properties.  Using this2515feature, clang provides default synthesis of those properties not declared2516@dynamic and not having user-provided backing getter and setter methods.2517``__has_feature(objc_default_synthesize_properties)`` checks for availability2518of this feature in version of clang being used.2519 2520.. _langext-objc-retain-release:2521 2522Objective-C retaining behavior attributes2523-----------------------------------------2524 2525In Objective-C, functions and methods are generally assumed to follow the2526`Cocoa Memory Management2527<https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_2528conventions for ownership of object arguments and2529return values. However, there are exceptions, and so Clang provides attributes2530to allow these exceptions to be documented. These are used by ARC and the2531`static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be2532better described using the ``objc_method_family`` attribute instead.2533 2534**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,2535``ns_returns_autoreleased``, ``cf_returns_retained``, and2536``cf_returns_not_retained`` attributes can be placed on methods and functions2537that return Objective-C or CoreFoundation objects. They are commonly placed at2538the end of a function prototype or method declaration:2539 2540.. code-block:: objc2541 2542  id foo() __attribute__((ns_returns_retained));2543 2544  - (NSString *)bar:(int)x __attribute__((ns_returns_retained));2545 2546The ``*_returns_retained`` attributes specify that the returned object has a +12547retain count.  The ``*_returns_not_retained`` attributes specify that the return2548object has a +0 retain count, even if the normal convention for its selector2549would be +1.  ``ns_returns_autoreleased`` specifies that the returned object is2550+0, but is guaranteed to live at least as long as the next flush of an2551autorelease pool.2552 2553**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on2554a parameter declaration; they specify that the argument is expected to have a2555+1 retain count, which will be balanced in some way by the function or method.2556The ``ns_consumes_self`` attribute can only be placed on an Objective-C2557method; it specifies that the method expects its ``self`` parameter to have a2558+1 retain count, which it will balance in some way.2559 2560.. code-block:: objc2561 2562  void foo(__attribute__((ns_consumed)) NSString *string);2563 2564  - (void) bar __attribute__((ns_consumes_self));2565  - (void) baz:(id) __attribute__((ns_consumed)) x;2566 2567Further examples of these attributes are available in the static analyzer's2568`list of annotations for analysis <analyzer/user-docs/Annotations.html#cocoa-mem>`__.2569 2570Query for these features with ``__has_attribute(ns_consumed)``,2571``__has_attribute(ns_returns_retained)``, etc.2572 2573Objective-C @available2574----------------------2575 2576It is possible to use the newest SDK but still build a program that can run on2577older versions of macOS and iOS by passing ``-mmacos-version-min=`` /2578``-miphoneos-version-min=``.2579 2580Before LLVM 5.0, when calling a function that exists only in the OS that's2581newer than the target OS (as determined by the minimum deployment version),2582programmers had to carefully check if the function exists at runtime, using2583null checks for weakly-linked C functions, ``+class`` for Objective-C classes,2584and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for2585Objective-C methods.  If such a check was missed, the program would compile2586fine, run fine on newer systems, but crash on older systems.2587 2588As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes2589<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together2590with the new ``@available()`` keyword to assist with this issue.2591When a method that's introduced in the OS newer than the target OS is called, a2592-Wunguarded-availability warning is emitted if that call is not guarded:2593 2594.. code-block:: objc2595 2596  void my_fun(NSSomeClass* var) {2597    // If fancyNewMethod was added in e.g., macOS 10.12, but the code is2598    // built with -mmacos-version-min=10.11, then this unconditional call2599    // will emit a -Wunguarded-availability warning:2600    [var fancyNewMethod];2601  }2602 2603To fix the warning and to avoid the crash on macOS 10.11, wrap it in2604``if(@available())``:2605 2606.. code-block:: objc2607 2608  void my_fun(NSSomeClass* var) {2609    if (@available(macOS 10.12, *)) {2610      [var fancyNewMethod];2611    } else {2612      // Put fallback behavior for old macOS versions (and for non-mac2613      // platforms) here.2614    }2615  }2616 2617The ``*`` is required and means that platforms not explicitly listed will take2618the true branch, and the compiler will emit ``-Wunguarded-availability``2619warnings for unlisted platforms based on those platform's deployment target.2620More than one platform can be listed in ``@available()``:2621 2622.. code-block:: objc2623 2624  void my_fun(NSSomeClass* var) {2625    if (@available(macOS 10.12, iOS 10, *)) {2626      [var fancyNewMethod];2627    }2628  }2629 2630If the caller of ``my_fun()`` already checks that ``my_fun()`` is only called2631on 10.12, then add an `availability attribute2632<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it,2633which will also suppress the warning and require that calls to my_fun() are2634checked:2635 2636.. code-block:: objc2637 2638  API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) {2639    [var fancyNewMethod];  // Now ok.2640  }2641 2642``@available()`` is only available in Objective-C code.  To use the feature2643in C and C++ code, use the ``__builtin_available()`` spelling instead.2644 2645If existing code uses null checks or ``-respondsToSelector:``, it should2646be changed to use ``@available()`` (or ``__builtin_available``) instead.2647 2648``-Wunguarded-availability`` is disabled by default, but2649``-Wunguarded-availability-new``, which only emits this warning for APIs2650that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and2651tvOS >= 11, is enabled by default.2652 2653.. _langext-overloading:2654 2655Objective-C++ ABI: protocol-qualifier mangling of parameters2656------------------------------------------------------------2657 2658Starting with LLVM 3.4, Clang produces a new mangling for parameters whose2659type is a qualified-``id`` (e.g., ``id<Foo>``).  This mangling allows such2660parameters to be differentiated from those with the regular unqualified ``id``2661type.2662 2663This was a non-backward compatible mangling change to the ABI.  This change2664allows proper overloading, and also prevents mangling conflicts with template2665parameters of protocol-qualified type.2666 2667Query the presence of this new mangling with2668``__has_feature(objc_protocol_qualifier_mangling)``.2669 2670Initializer lists for complex numbers in C2671==========================================2672 2673clang supports an extension which allows the following in C:2674 2675.. code-block:: c++2676 2677  #include <math.h>2678  #include <complex.h>2679  complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)2680 2681This construct is useful because there is no way to separately initialize the2682real and imaginary parts of a complex variable in standard C, given that clang2683does not support ``_Imaginary``.  (Clang also supports the ``__real__`` and2684``__imag__`` extensions from gcc, which help in some cases, but are not usable2685in static initializers.)2686 2687Note that this extension does not allow eliding the braces; the meaning of the2688following two lines is different:2689 2690.. code-block:: c++2691 2692  complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)2693  complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)2694 2695This extension also works in C++ mode, as far as that goes, but does not apply2696to the C++ ``std::complex``.  (In C++11, list initialization allows the same2697syntax to be used with ``std::complex`` with the same meaning.)2698 2699For GCC compatibility, ``__builtin_complex(re, im)`` can also be used to2700construct a complex number from the given real and imaginary components.2701 2702OpenCL Features2703===============2704 2705Clang supports internal OpenCL extensions documented below.2706 2707``__cl_clang_bitfields``2708--------------------------------2709 2710With this extension it is possible to enable bitfields in structs2711or unions using the OpenCL extension pragma mechanism detailed in2712`the OpenCL Extension Specification, section 1.22713<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.2714 2715Use of bitfields in OpenCL kernels can result in reduced portability as struct2716layout is not guaranteed to be consistent when compiled by different compilers.2717If structs with bitfields are used as kernel function parameters, it can result2718in incorrect functionality when the layout is different between the host and2719device code.2720 2721**Example of Use**:2722 2723.. code-block:: c++2724 2725  #pragma OPENCL EXTENSION __cl_clang_bitfields : enable2726  struct with_bitfield {2727    unsigned int i : 5; // compiled - no diagnostic generated2728  };2729 2730  #pragma OPENCL EXTENSION __cl_clang_bitfields : disable2731  struct without_bitfield {2732    unsigned int i : 5; // error - bitfields are not supported2733  };2734 2735``__cl_clang_function_pointers``2736--------------------------------2737 2738With this extension it is possible to enable various language features that2739are relying on function pointers using regular OpenCL extension pragma2740mechanism detailed in `the OpenCL Extension Specification,2741section 1.22742<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.2743 2744In C++ for OpenCL this also enables:2745 2746- Use of member function pointers;2747 2748- Unrestricted use of references to functions;2749 2750- Virtual member functions.2751 2752Such functionality is not conformant and does not guarantee to compile2753correctly in any circumstances. It can be used if:2754 2755- the kernel source does not contain call expressions to (member-) function2756  pointers, or virtual functions. For example, this extension can be used in2757  metaprogramming algorithms to be able to specify/detect types generically.2758 2759- the generated kernel binary does not contain indirect calls because they2760  are eliminated using compiler optimizations e.g., devirtualization.2761 2762- the selected target supports the function pointer like functionality e.g.2763  most CPU targets.2764 2765**Example of Use**:2766 2767.. code-block:: c++2768 2769  #pragma OPENCL EXTENSION __cl_clang_function_pointers : enable2770  void foo()2771  {2772    void (*fp)(); // compiled - no diagnostic generated2773  }2774 2775  #pragma OPENCL EXTENSION __cl_clang_function_pointers : disable2776  void bar()2777  {2778    void (*fp)(); // error - pointers to function are not allowed2779  }2780 2781``__cl_clang_variadic_functions``2782---------------------------------2783 2784With this extension it is possible to enable variadic arguments in functions2785using regular OpenCL extension pragma mechanism detailed in `the OpenCL2786Extension Specification, section 1.22787<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.2788 2789This is not conformant behavior and it can only be used portably when the2790functions with variadic prototypes do not get generated in binary e.g., the2791variadic prototype is used to specify a function type with any number of2792arguments in metaprogramming algorithms in C++ for OpenCL.2793 2794This extension can also be used when the kernel code is intended for targets2795supporting the variadic arguments e.g., majority of CPU targets.2796 2797**Example of Use**:2798 2799.. code-block:: c++2800 2801  #pragma OPENCL EXTENSION __cl_clang_variadic_functions : enable2802  void foo(int a, ...); // compiled - no diagnostic generated2803 2804  #pragma OPENCL EXTENSION __cl_clang_variadic_functions : disable2805  void bar(int a, ...); // error - variadic prototype is not allowed2806 2807``__cl_clang_non_portable_kernel_param_types``2808----------------------------------------------2809 2810With this extension it is possible to enable the use of some restricted types2811in kernel parameters specified in `C++ for OpenCL v1.0 s2.42812<https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html#kernel_function>`_.2813The restrictions can be relaxed using regular OpenCL extension pragma mechanism2814detailed in `the OpenCL Extension Specification, section 1.22815<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.2816 2817This is not a conformant behavior and it can only be used when the2818kernel arguments are not accessed on the host side or the data layout/size2819between the host and device is known to be compatible.2820 2821**Example of Use**:2822 2823.. code-block:: c++2824 2825  // Plain Old Data type.2826  struct Pod {2827    int a;2828    int b;2829  };2830 2831  // Not POD type because of the constructor.2832  // Standard layout type because there is only one access control.2833  struct OnlySL {2834    int a;2835    int b;2836    OnlySL() : a(0), b(0) {}2837  };2838 2839  // Not standard layout type because of two different access controls.2840  struct NotSL {2841    int a;2842  private:2843    int b;2844  };2845 2846  #pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : enable2847  kernel void kernel_main(2848    Pod a,2849 2850    OnlySL b,2851    global NotSL *c,2852    global OnlySL *d2853  );2854  #pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : disable2855 2856Remove address space builtin function2857-------------------------------------2858 2859``__remove_address_space`` allows to derive types in C++ for OpenCL2860that have address space qualifiers removed. This utility only affects2861address space qualifiers, therefore, other type qualifiers such as2862``const`` or ``volatile`` remain unchanged.2863 2864**Example of Use**:2865 2866.. code-block:: c++2867 2868  template<typename T>2869  void foo(T *par){2870    T var1; // error - local function variable with global address space2871    __private T var2; // error - conflicting address space qualifiers2872    __private __remove_address_space<T>::type var3; // var3 is __private int2873  }2874 2875  void bar(){2876    __global int* ptr;2877    foo(ptr);2878  }2879 2880Legacy 1.x atomics with generic address space2881---------------------------------------------2882 2883Clang allows the use of atomic functions from the OpenCL 1.x standards2884with the generic address space pointer in C++ for OpenCL mode.2885 2886This is a non-portable feature and might not be supported by all2887targets.2888 2889**Example of Use**:2890 2891.. code-block:: c++2892 2893  void foo(__generic volatile unsigned int* a) {2894    atomic_add(a, 1);2895  }2896 2897WebAssembly Features2898====================2899 2900Clang supports the WebAssembly features documented below. For further2901information related to the semantics of the builtins, please refer to the `WebAssembly Specification <https://webassembly.github.io/spec/core/>`_.2902In this section, when we refer to reference types, we are referring to2903WebAssembly reference types, not C++ reference types unless stated2904otherwise.2905 2906``__builtin_wasm_table_set``2907----------------------------2908 2909This builtin function stores a value in a WebAssembly table.2910It takes three arguments.2911The first argument is the table to store a value into, the second2912argument is the index to which to store the value into, and the2913third argument is a value of reference type to store in the table.2914It returns nothing.2915 2916.. code-block:: c++2917 2918  static __externref_t table[0];2919  extern __externref_t JSObj;2920 2921  void store(int index) {2922    __builtin_wasm_table_set(table, index, JSObj);2923  }2924 2925``__builtin_wasm_table_get``2926----------------------------2927 2928This builtin function is the counterpart to ``__builtin_wasm_table_set``2929and loads a value from a WebAssembly table of reference typed values.2930It takes 2 arguments.2931The first argument is a table of reference typed values and the2932second argument is an index from which to load the value. It returns2933the loaded reference typed value.2934 2935.. code-block:: c++2936 2937  static __externref_t table[0];2938 2939  __externref_t load(int index) {2940    __externref_t Obj = __builtin_wasm_table_get(table, index);2941    return Obj;2942  }2943 2944``__builtin_wasm_table_size``2945-----------------------------2946 2947This builtin function returns the size of the WebAssembly table.2948Takes the table as an argument and returns an unsigned integer (``size_t``)2949with the current table size.2950 2951.. code-block:: c++2952 2953  typedef void (*__funcref funcref_t)();2954  static funcref_t table[0];2955 2956  size_t getSize() {2957    return __builtin_wasm_table_size(table);2958  }2959 2960``__builtin_wasm_table_grow``2961-----------------------------2962 2963This builtin function grows the WebAssembly table by a certain amount.2964Currently, as all WebAssembly tables created in C/C++ are zero-sized,2965this always needs to be called to grow the table.2966 2967It takes three arguments. The first argument is the WebAssembly table2968to grow. The second argument is the reference typed value to store in2969the new table entries (the initialization value), and the third argument2970is the amount to grow the table by. It returns the previous table size2971or -1. It will return -1 if not enough space could be allocated.2972 2973.. code-block:: c++2974 2975  typedef void (*__funcref funcref_t)();2976  static funcref_t table[0];2977 2978  // grow returns the new table size or -1 on error.2979  int grow(funcref_t fn, int delta) {2980    int prevSize = __builtin_wasm_table_grow(table, fn, delta);2981    if (prevSize == -1)2982      return -1;2983    return prevSize + delta;2984  }2985 2986``__builtin_wasm_table_fill``2987-----------------------------2988 2989This builtin function sets all the entries of a WebAssembly table to a given2990reference typed value. It takes four arguments. The first argument is2991the WebAssembly table, the second argument is the index that starts the2992range, the third argument is the value to set in the new entries, and2993the fourth and the last argument is the size of the range. It returns2994nothing.2995 2996.. code-block:: c++2997 2998  static __externref_t table[0];2999 3000  // resets a table by setting all of its entries to a given value.3001  void reset(__externref_t Obj) {3002    int Size = __builtin_wasm_table_size(table);3003    __builtin_wasm_table_fill(table, 0, Obj, Size);3004  }3005 3006``__builtin_wasm_table_copy``3007-----------------------------3008 3009This builtin function copies elements from a source WebAssembly table3010to a possibly overlapping destination region. It takes five arguments.3011The first argument is the destination WebAssembly table, and the second3012argument is the source WebAssembly table. The third argument is the3013destination index from where the copy starts, the fourth argument is the3014source index from where the copy starts, and the fifth and last argument3015is the number of elements to copy. It returns nothing.3016 3017.. code-block:: c++3018 3019  static __externref_t tableSrc[0];3020  static __externref_t tableDst[0];3021 3022  // Copy nelem elements from [src, src + nelem - 1] in tableSrc to3023  // [dst, dst + nelem - 1] in tableDst3024  void copy(int dst, int src, int nelem) {3025    __builtin_wasm_table_copy(tableDst, tableSrc, dst, src, nelem);3026  }3027 3028 3029Builtin Functions3030=================3031 3032Clang supports a number of builtin library functions with the same syntax as3033GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,3034``__builtin_choose_expr``, ``__builtin_types_compatible_p``,3035``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc.  In addition to3036the GCC builtins, Clang supports a number of builtins that GCC does not, which3037are listed here.3038 3039Please note that Clang does not and will not support all of the GCC builtins3040for vector operations.  Instead of using builtins, you should use the functions3041defined in target-specific header files like ``<xmmintrin.h>``, which define3042portable wrappers for these.  Many of the Clang versions of these functions are3043implemented directly in terms of :ref:`extended vector support3044<langext-vectors>` instead of builtins, in order to reduce the number of3045builtins that we need to implement.3046 3047``__builtin_alloca``3048--------------------3049 3050``__builtin_alloca`` is used to dynamically allocate memory on the stack. Memory3051is automatically freed upon function termination.3052 3053**Syntax**:3054 3055.. code-block:: c++3056 3057  __builtin_alloca(size_t n)3058 3059**Example of Use**:3060 3061.. code-block:: c++3062 3063  void init(float* data, size_t nbelems);3064  void process(float* data, size_t nbelems);3065  int foo(size_t n) {3066    auto mem = (float*)__builtin_alloca(n * sizeof(float));3067    init(mem, n);3068    process(mem, n);3069    /* mem is automatically freed at this point */3070  }3071 3072**Description**:3073 3074``__builtin_alloca`` is meant to be used to allocate a dynamic amount of memory3075on the stack. This amount is subject to stack allocation limits.3076 3077Query for this feature with ``__has_builtin(__builtin_alloca)``.3078 3079``__builtin_alloca_with_align``3080-------------------------------3081 3082``__builtin_alloca_with_align`` is used to dynamically allocate memory on the3083stack while controlling its alignment. Memory is automatically freed upon3084function termination.3085 3086 3087**Syntax**:3088 3089.. code-block:: c++3090 3091  __builtin_alloca_with_align(size_t n, size_t align)3092 3093**Example of Use**:3094 3095.. code-block:: c++3096 3097  void init(float* data, size_t nbelems);3098  void process(float* data, size_t nbelems);3099  int foo(size_t n) {3100    auto mem = (float*)__builtin_alloca_with_align(3101                        n * sizeof(float),3102                        CHAR_BIT * alignof(float));3103    init(mem, n);3104    process(mem, n);3105    /* mem is automatically freed at this point */3106  }3107 3108**Description**:3109 3110``__builtin_alloca_with_align`` is meant to be used to allocate a dynamic amount of memory3111on the stack. It is similar to ``__builtin_alloca`` but accepts a second3112argument whose value is the alignment constraint, as a power of 2 in *bits*.3113 3114Query for this feature with ``__has_builtin(__builtin_alloca_with_align)``.3115 3116.. _langext-__builtin_assume:3117 3118``__builtin_assume``3119--------------------3120 3121``__builtin_assume`` is used to provide the optimizer with a boolean3122invariant that is defined to be true.3123 3124**Syntax**:3125 3126.. code-block:: c++3127 3128    __builtin_assume(bool)3129 3130**Example of Use**:3131 3132.. code-block:: c++3133 3134  int foo(int x) {3135      __builtin_assume(x != 0);3136      // The optimizer may short-circuit this check using the invariant.3137      if (x == 0)3138            return do_something();3139      return do_something_else();3140  }3141 3142**Description**:3143 3144The boolean argument to this function is defined to be true. The optimizer may3145analyze the form of the expression provided as the argument and deduce from3146that information used to optimize the program. If the condition is violated3147during execution, the behavior is undefined. The argument itself is never3148evaluated, so any side effects of the expression will be discarded.3149 3150Query for this feature with ``__has_builtin(__builtin_assume)``.3151 3152.. _langext-__builtin_assume_separate_storage:3153 3154``__builtin_assume_separate_storage``3155-------------------------------------3156 3157``__builtin_assume_separate_storage`` is used to provide the optimizer with the3158knowledge that its two arguments point to separately allocated objects.3159 3160**Syntax**:3161 3162.. code-block:: c++3163 3164    __builtin_assume_separate_storage(const volatile void *, const volatile void *)3165 3166**Example of Use**:3167 3168.. code-block:: c++3169 3170  int foo(int *x, int *y) {3171      __builtin_assume_separate_storage(x, y);3172      *x = 0;3173      *y = 1;3174      // The optimizer may optimize this to return 0 without reloading from *x.3175      return *x;3176  }3177 3178**Description**:3179 3180The arguments to this function are assumed to point into separately allocated3181storage (either different variable definitions or different dynamic storage3182allocations). The optimizer may use this fact to aid in alias analysis. If the3183arguments point into the same storage, the behavior is undefined. Note that the3184definition of "storage" here refers to the outermost enclosing allocation of any3185particular object (so for example, it's never correct to call this function3186passing the addresses of fields in the same struct, elements of the same array,3187etc.).3188 3189Query for this feature with ``__has_builtin(__builtin_assume_separate_storage)``.3190 3191``__builtin_assume_dereferenceable``3192-------------------------------------3193 3194``__builtin_assume_dereferenceable`` is used to provide the optimizer with the3195knowledge that the pointer argument P is dereferenceable up to at least the3196specified number of bytes.3197 3198**Syntax**:3199 3200.. code-block:: c++3201 3202    __builtin_assume_dereferenceable(const void *, size_t)3203 3204**Example of Use**:3205 3206.. code-block:: c++3207 3208  int foo(int *x, int y) {3209      __builtin_assume_dereferenceable(x, sizeof(int));3210      int z = 0;3211      if (y == 1) {3212        // The optimizer may execute the load of x unconditionally due to3213        // __builtin_assume_dereferenceable guaranteeing sizeof(int) bytes can3214        // be loaded speculatively without trapping.3215        z = *x;3216      }3217      return z;3218  }3219 3220**Description**:3221 3222The arguments to this function provide a start pointer ``P`` and a size ``S``.3223``S`` must be at least 1 and a constant. The optimizer may assume that ``S``3224bytes are dereferenceable starting at ``P``. Note that this does not necessarily3225imply that ``P`` is non-null as ``nullptr`` can be dereferenced in some cases.3226The assumption also does not imply that ``P`` is not dereferenceable past ``S``3227bytes.3228 3229 3230Query for this feature with ``__has_builtin(__builtin_assume_dereferenceable)``.3231 3232 3233``__builtin_offsetof``3234----------------------3235 3236``__builtin_offsetof`` is used to implement the ``offsetof`` macro, which3237calculates the offset (in bytes) to a given member of the given type.3238 3239**Syntax**:3240 3241.. code-block:: c++3242 3243    __builtin_offsetof(type-name, member-designator)3244 3245**Example of Use**:3246 3247.. code-block:: c++3248 3249  struct S {3250    char c;3251    int i;3252    struct T {3253      float f[2];3254    } t;3255  };3256 3257  const int offset_to_i = __builtin_offsetof(struct S, i);3258  const int ext1 = __builtin_offsetof(struct U { int i; }, i); // C extension3259  const int offset_to_subobject = __builtin_offsetof(struct S, t.f[1]);3260 3261**Description**:3262 3263This builtin is usable in an integer constant expression which returns a value3264of type ``size_t``. The value returned is the offset in bytes to the subobject3265designated by the member-designator from the beginning of an object of type3266``type-name``. Clang extends the required standard functionality in the3267following way:3268 3269* In C language modes, the first argument may be the definition of a new type.3270  Any type declared this way is scoped to the nearest scope containing the call3271  to the builtin.3272 3273Query for this feature with ``__has_builtin(__builtin_offsetof)``.3274 3275``__builtin_get_vtable_pointer``3276--------------------------------3277 3278``__builtin_get_vtable_pointer`` loads and authenticates the primary vtable3279pointer from an instance of a polymorphic C++ class. This builtin is needed3280for directly loading the vtable pointer when on platforms using3281:doc:`PointerAuthentication`.3282 3283**Syntax**:3284 3285.. code-block:: c++3286 3287  __builtin_get_vtable_pointer(PolymorphicClass*)3288 3289**Example of Use**:3290 3291.. code-block:: c++3292 3293  struct PolymorphicClass {3294    virtual ~PolymorphicClass();3295  };3296 3297  PolymorphicClass anInstance;3298  const void* vtablePointer = __builtin_get_vtable_pointer(&anInstance);3299 3300**Description**:3301 3302The ``__builtin_get_vtable_pointer`` builtin loads the primary vtable3303pointer from a polymorphic C++ type. If the target platform authenticates3304vtable pointers, this builtin will perform the authentication and produce3305the underlying raw pointer. The object being queried must be polymorphic,3306and so must also be a complete type.3307 3308Query for this feature with ``__has_builtin(__builtin_get_vtable_pointer)``.3309 3310``__builtin_call_with_static_chain``3311------------------------------------3312 3313``__builtin_call_with_static_chain`` is used to perform a static call while3314updating the static chain register.3315 3316**Syntax**:3317 3318.. code-block:: c++3319 3320  T __builtin_call_with_static_chain(T expr, void* ptr)3321 3322**Example of Use**:3323 3324.. code-block:: c++3325 3326  auto v = __builtin_call_with_static_chain(foo(3), foo);3327 3328**Description**:3329 3330This builtin returns ``expr`` after checking that ``expr`` is a non-member3331static call expression. The call to that expression is made while using ``ptr``3332as a function pointer stored in a dedicated register to implement *static chain*3333calling convention, as used by some language to implement closures or nested3334functions.3335 3336Query for this feature with ``__has_builtin(__builtin_call_with_static_chain)``.3337 3338``__builtin_readcyclecounter``3339------------------------------3340 3341``__builtin_readcyclecounter`` is used to access the cycle counter register (or3342a similar low-latency, high-accuracy clock) on those targets that support it.3343 3344**Syntax**:3345 3346.. code-block:: c++3347 3348  __builtin_readcyclecounter()3349 3350**Example of Use**:3351 3352.. code-block:: c++3353 3354  unsigned long long t0 = __builtin_readcyclecounter();3355  do_something();3356  unsigned long long t1 = __builtin_readcyclecounter();3357  unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow3358 3359**Description**:3360 3361The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,3362which may be either global or process/thread-specific depending on the target.3363As the backing counters often overflow quickly (on the order of seconds) this3364should only be used for timing small intervals.  When not supported by the3365target, the return value is always zero.  This builtin takes no arguments and3366produces an unsigned long long result.3367 3368Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note3369that even if present, its use may depend on run-time privilege or other OS3370controlled state.3371 3372``__builtin_readsteadycounter``3373-------------------------------3374 3375``__builtin_readsteadycounter`` is used to access the fixed frequency counter3376register (or a similar steady-rate clock) on those targets that support it.3377The function is similar to ``__builtin_readcyclecounter`` above except that the3378frequency is fixed, making it suitable for measuring elapsed time.3379 3380**Syntax**:3381 3382.. code-block:: c++3383 3384  __builtin_readsteadycounter()3385 3386**Example of Use**:3387 3388.. code-block:: c++3389 3390  unsigned long long t0 = __builtin_readsteadycounter();3391  do_something();3392  unsigned long long t1 = __builtin_readsteadycounter();3393  unsigned long long secs_to_do_something = (t1 - t0) / tick_rate;3394 3395**Description**:3396 3397The ``__builtin_readsteadycounter()`` builtin returns the frequency counter value.3398When not supported by the target, the return value is always zero. This builtin3399takes no arguments and produces an unsigned long long result. The builtin does3400not guarantee any particular frequency, only that it is stable. Knowledge of the3401counter's true frequency will need to be provided by the user.3402 3403Query for this feature with ``__has_builtin(__builtin_readsteadycounter)``.3404 3405``__builtin_cpu_supports``3406--------------------------3407 3408**Syntax**:3409 3410.. code-block:: c++3411 3412  int __builtin_cpu_supports(const char *features);3413 3414**Example of Use:**:3415 3416.. code-block:: c++3417 3418  if (__builtin_cpu_supports("sve"))3419    sve_code();3420 3421**Description**:3422 3423The ``__builtin_cpu_supports`` function detects if the run-time CPU supports3424features specified in string argument. It returns a positive integer if all3425features are supported and 0 otherwise. Feature names are target specific. On3426AArch64, features are combined using ``+`` like this3427``__builtin_cpu_supports("flagm+sha3+lse+rcpc2+fcma+memtag+bti+sme2")``.3428If a feature name is not supported, Clang will issue a warning and replace3429builtin by the constant 0.3430 3431Query for this feature with ``__has_builtin(__builtin_cpu_supports)``.3432 3433``__builtin_dump_struct``3434-------------------------3435 3436**Syntax**:3437 3438.. code-block:: c++3439 3440    __builtin_dump_struct(&some_struct, some_printf_func, args...);3441 3442**Examples**:3443 3444.. code-block:: c++3445 3446    struct S {3447      int x, y;3448      float f;3449      struct T {3450        int i;3451      } t;3452    };3453 3454    void func(struct S *s) {3455      __builtin_dump_struct(s, printf);3456    }3457 3458Example output:3459 3460.. code-block:: none3461 3462    struct S {3463      int x = 1003464      int y = 423465      float f = 3.1415933466      struct T t = {3467        int i = 19973468      }3469    }3470 3471.. code-block:: c++3472 3473    #include <string>3474    struct T { int a, b; };3475    constexpr void constexpr_sprintf(std::string &out, const char *format,3476                                     auto ...args) {3477      // ...3478    }3479    constexpr std::string dump_struct(auto &x) {3480      std::string s;3481      __builtin_dump_struct(&x, constexpr_sprintf, s);3482      return s;3483    }3484    static_assert(dump_struct(T{1, 2}) == R"(struct T {3485      int a = 13486      int b = 23487    }3488    )");3489 3490**Description**:3491 3492The ``__builtin_dump_struct`` function is used to print the fields of a simple3493structure and their values for debugging purposes. The first argument of the3494builtin should be a pointer to a complete record type to dump. The second argument ``f``3495should be some callable expression, and can be a function object or an overload3496set. The builtin calls ``f``, passing any further arguments ``args...``3497followed by a ``printf``-compatible format string and the corresponding3498arguments. ``f`` may be called more than once, and ``f`` and ``args`` will be3499evaluated once per call. In C++, ``f`` may be a template or overload set and3500resolve to different functions for each call.3501 3502In the format string, a suitable format specifier will be used for builtin3503types that Clang knows how to format. This includes standard builtin types, as3504well as aggregate structures, ``void*`` (printed with ``%p``), and ``const3505char*`` (printed with ``%s``). A ``*%p`` specifier will be used for a field3506that Clang doesn't know how to format, and the corresponding argument will be a3507pointer to the field. This allows a C++ templated formatting function to detect3508this case and implement custom formatting. A ``*`` will otherwise not precede a3509format specifier.3510 3511This builtin does not return a value.3512 3513This builtin can be used in constant expressions.3514 3515Query for this feature with ``__has_builtin(__builtin_dump_struct)``3516 3517.. _langext-__builtin_shufflevector:3518 3519``__builtin_shufflevector``3520---------------------------3521 3522``__builtin_shufflevector`` is used to express generic vector3523permutation/shuffle/swizzle operations.  This builtin is also very important3524for the implementation of various target-specific header files like3525``<xmmintrin.h>``. This builtin can be used within constant expressions.3526 3527**Syntax**:3528 3529.. code-block:: c++3530 3531  __builtin_shufflevector(vec1, vec2, index1, index2, ...)3532 3533**Examples**:3534 3535.. code-block:: c++3536 3537  // identity operation - return 4-element vector v1.3538  __builtin_shufflevector(v1, v1, 0, 1, 2, 3)3539 3540  // "Splat" element 0 of V1 into a 4-element result.3541  __builtin_shufflevector(V1, V1, 0, 0, 0, 0)3542 3543  // Reverse 4-element vector V1.3544  __builtin_shufflevector(V1, V1, 3, 2, 1, 0)3545 3546  // Concatenate every other element of 4-element vectors V1 and V2.3547  __builtin_shufflevector(V1, V2, 0, 2, 4, 6)3548 3549  // Concatenate every other element of 8-element vectors V1 and V2.3550  __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)3551 3552  // Shuffle v1 with some elements being undefined. Not allowed in constexpr.3553  __builtin_shufflevector(v1, v1, 3, -1, 1, -1)3554 3555**Description**:3556 3557The first two arguments to ``__builtin_shufflevector`` are vectors that have3558the same element type.  The remaining arguments are a list of integers that3559specify the elements indices of the first two vectors that should be extracted3560and returned in a new vector.  These element indices are numbered sequentially3561starting with the first vector, continuing into the second vector.  Thus, if3562``vec1`` is a 4-element vector, index 5 would refer to the second element of3563``vec2``. An index of -1 can be used to indicate that the corresponding element3564in the returned vector is a don't care and can be optimized by the backend.3565Values of -1 are not supported in constant expressions.3566 3567The result of ``__builtin_shufflevector`` is a vector with the same element3568type as ``vec1``/``vec2`` but that has an element count equal to the number of3569indices specified.3570 3571Query for this feature with ``__has_builtin(__builtin_shufflevector)``.3572 3573.. _langext-__builtin_convertvector:3574 3575``__builtin_convertvector``3576---------------------------3577 3578``__builtin_convertvector`` is used to express generic vector3579type-conversion operations. The input vector and the output vector3580type must have the same number of elements. This builtin can be used within3581constant expressions.3582 3583**Syntax**:3584 3585.. code-block:: c++3586 3587  __builtin_convertvector(src_vec, dst_vec_type)3588 3589**Examples**:3590 3591.. code-block:: c++3592 3593  typedef double vector4double __attribute__((__vector_size__(32)));3594  typedef float  vector4float  __attribute__((__vector_size__(16)));3595  typedef short  vector4short  __attribute__((__vector_size__(8)));3596  vector4float vf; vector4short vs;3597 3598  // convert from a vector of 4 floats to a vector of 4 doubles.3599  __builtin_convertvector(vf, vector4double)3600  // equivalent to:3601  (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }3602 3603  // convert from a vector of 4 shorts to a vector of 4 floats.3604  __builtin_convertvector(vs, vector4float)3605  // equivalent to:3606  (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] }3607 3608**Description**:3609 3610The first argument to ``__builtin_convertvector`` is a vector, and the second3611argument is a vector type with the same number of elements as the first3612argument.3613 3614The result of ``__builtin_convertvector`` is a vector with the same element3615type as the second argument, with a value defined in terms of the action of a3616C-style cast applied to each element of the first argument.3617 3618Query for this feature with ``__has_builtin(__builtin_convertvector)``.3619 3620``__builtin_bitreverse``3621------------------------3622 3623* ``__builtin_bitreverse8``3624* ``__builtin_bitreverse16``3625* ``__builtin_bitreverse32``3626* ``__builtin_bitreverse64``3627 3628**Syntax**:3629 3630.. code-block:: c++3631 3632     __builtin_bitreverse32(x)3633 3634**Examples**:3635 3636.. code-block:: c++3637 3638      uint8_t rev_x = __builtin_bitreverse8(x);3639      uint16_t rev_x = __builtin_bitreverse16(x);3640      uint32_t rev_y = __builtin_bitreverse32(y);3641      uint64_t rev_z = __builtin_bitreverse64(z);3642 3643**Description**:3644 3645The '``__builtin_bitreverse``' family of builtins is used to reverse3646the bitpattern of an integer value; for example, ``0b10110110`` becomes3647``0b01101101``. These builtins can be used within constant expressions.3648 3649``__builtin_rotateleft``3650------------------------3651 3652* ``__builtin_rotateleft8``3653* ``__builtin_rotateleft16``3654* ``__builtin_rotateleft32``3655* ``__builtin_rotateleft64``3656 3657**Syntax**:3658 3659.. code-block:: c++3660 3661     __builtin_rotateleft32(x, y)3662 3663**Examples**:3664 3665.. code-block:: c++3666 3667      uint8_t rot_x = __builtin_rotateleft8(x, y);3668      uint16_t rot_x = __builtin_rotateleft16(x, y);3669      uint32_t rot_x = __builtin_rotateleft32(x, y);3670      uint64_t rot_x = __builtin_rotateleft64(x, y);3671 3672**Description**:3673 3674The '``__builtin_rotateleft``' family of builtins is used to rotate3675the bits in the first argument by the amount in the second argument.3676For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``.3677The shift value is treated as an unsigned amount modulo the size of3678the arguments. Both arguments and the result have the bitwidth specified3679by the name of the builtin. These builtins can be used within constant3680expressions.3681 3682``__builtin_rotateright``3683-------------------------3684 3685* ``__builtin_rotateright8``3686* ``__builtin_rotateright16``3687* ``__builtin_rotateright32``3688* ``__builtin_rotateright64``3689 3690**Syntax**:3691 3692.. code-block:: c++3693 3694     __builtin_rotateright32(x, y)3695 3696**Examples**:3697 3698.. code-block:: c++3699 3700      uint8_t rot_x = __builtin_rotateright8(x, y);3701      uint16_t rot_x = __builtin_rotateright16(x, y);3702      uint32_t rot_x = __builtin_rotateright32(x, y);3703      uint64_t rot_x = __builtin_rotateright64(x, y);3704 3705**Description**:3706 3707The '``__builtin_rotateright``' family of builtins is used to rotate3708the bits in the first argument by the amount in the second argument.3709For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``.3710The shift value is treated as an unsigned amount modulo the size of3711the arguments. Both arguments and the result have the bitwidth specified3712by the name of the builtin. These builtins can be used within constant3713expressions.3714 3715``__builtin_unreachable``3716-------------------------3717 3718``__builtin_unreachable`` is used to indicate that a specific point in the3719program cannot be reached, even if the compiler might otherwise think it can.3720This is useful to improve optimization and eliminates certain warnings.  For3721example, without the ``__builtin_unreachable`` in the example below, the3722compiler assumes that the inline asm can fall through and prints a "function3723declared '``noreturn``' should not return" warning.3724 3725**Syntax**:3726 3727.. code-block:: c++3728 3729    __builtin_unreachable()3730 3731**Example of use**:3732 3733.. code-block:: c++3734 3735  void myabort(void) __attribute__((noreturn));3736  void myabort(void) {3737    asm("int3");3738    __builtin_unreachable();3739  }3740 3741**Description**:3742 3743The ``__builtin_unreachable()`` builtin has completely undefined behavior.3744Since it has undefined behavior, it is a statement that it is never reached and3745the optimizer can take advantage of this to produce better code.  This builtin3746takes no arguments and produces a void result.3747 3748Query for this feature with ``__has_builtin(__builtin_unreachable)``.3749 3750``__builtin_unpredictable``3751---------------------------3752 3753``__builtin_unpredictable`` is used to indicate that a branch condition is3754unpredictable by hardware mechanisms such as branch prediction logic.3755 3756**Syntax**:3757 3758.. code-block:: c++3759 3760    __builtin_unpredictable(long long)3761 3762**Example of use**:3763 3764.. code-block:: c++3765 3766  if (__builtin_unpredictable(x > 0)) {3767     foo();3768  }3769 3770**Description**:3771 3772The ``__builtin_unpredictable()`` builtin is expected to be used with control3773flow conditions such as in ``if`` and ``switch`` statements.3774 3775Query for this feature with ``__has_builtin(__builtin_unpredictable)``.3776 3777 3778``__builtin_expect``3779--------------------3780 3781``__builtin_expect`` is used to indicate that the value of an expression is3782anticipated to be the same as a statically known result.3783 3784**Syntax**:3785 3786.. code-block:: c++3787 3788    long __builtin_expect(long expr, long val)3789 3790**Example of use**:3791 3792.. code-block:: c++3793 3794  if (__builtin_expect(x, 0)) {3795     bar();3796  }3797 3798**Description**:3799 3800The ``__builtin_expect()`` builtin is typically used with control flow3801conditions such as in ``if`` and ``switch`` statements to help branch3802prediction. It means that its first argument ``expr`` is expected to take the3803value of its second argument ``val``. It always returns ``expr``.3804 3805Query for this feature with ``__has_builtin(__builtin_expect)``.3806 3807``__builtin_expect_with_probability``3808-------------------------------------3809 3810``__builtin_expect_with_probability`` is similar to ``__builtin_expect`` but it3811takes a probability as third argument.3812 3813**Syntax**:3814 3815.. code-block:: c++3816 3817    long __builtin_expect_with_probability(long expr, long val, double p)3818 3819**Example of use**:3820 3821.. code-block:: c++3822 3823  if (__builtin_expect_with_probability(x, 0, .3)) {3824     bar();3825  }3826 3827**Description**:3828 3829The ``__builtin_expect_with_probability()`` builtin is typically used with3830control flow conditions such as in ``if`` and ``switch`` statements to help3831branch prediction. It means that its first argument ``expr`` is expected to take3832the value of its second argument ``val`` with probability ``p``. ``p`` must be3833within ``[0.0 ; 1.0]`` bounds. This builtin always returns the value of ``expr``.3834 3835Query for this feature with ``__has_builtin(__builtin_expect_with_probability)``.3836 3837``__builtin_prefetch``3838----------------------3839 3840``__builtin_prefetch`` is used to communicate with the cache handler to bring3841data into the cache before it gets used.3842 3843**Syntax**:3844 3845.. code-block:: c++3846 3847    void __builtin_prefetch(const void *addr, int rw=0, int locality=3)3848 3849**Example of use**:3850 3851.. code-block:: c++3852 3853    __builtin_prefetch(a + i);3854 3855**Description**:3856 3857The ``__builtin_prefetch(addr, rw, locality)`` builtin is expected to be used to3858avoid cache misses when the developer has a good understanding of which data3859are going to be used next. ``addr`` is the address that needs to be brought into3860the cache. ``rw`` indicates the expected access mode: ``0`` for *read* and ``1``3861for *write*. In case of *read write* access, ``1`` is to be used. ``locality``3862indicates the expected persistence of data in cache, from ``0`` which means that3863data can be discarded from cache after its next use to ``3`` which means that3864data is going to be reused a lot once in cache. ``1`` and ``2`` provide3865intermediate behavior between these two extremes.3866 3867Query for this feature with ``__has_builtin(__builtin_prefetch)``.3868 3869``__sync_swap``3870---------------3871 3872``__sync_swap`` is used to atomically swap integers or pointers in memory.3873 3874**Syntax**:3875 3876.. code-block:: c++3877 3878  type __sync_swap(type *ptr, type value, ...)3879 3880**Example of Use**:3881 3882.. code-block:: c++3883 3884  int old_value = __sync_swap(&value, new_value);3885 3886**Description**:3887 3888The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of3889atomic intrinsics to allow code to atomically swap the current value with the3890new value.  More importantly, it helps developers write more efficient and3891correct code by avoiding expensive loops around3892``__sync_bool_compare_and_swap()`` or relying on the platform specific3893implementation details of ``__sync_lock_test_and_set()``.  The3894``__sync_swap()`` builtin is a full barrier.3895 3896``__builtin_addressof``3897-----------------------3898 3899``__builtin_addressof`` performs the functionality of the built-in ``&``3900operator, ignoring any ``operator&`` overload.  This is useful in constant3901expressions in C++11, where there is no other way to take the address of an3902object that overloads ``operator&``. Clang automatically adds3903``[[clang::lifetimebound]]`` to the parameter of ``__builtin_addressof``.3904 3905**Example of use**:3906 3907.. code-block:: c++3908 3909  template<typename T> constexpr T *addressof(T &value) {3910    return __builtin_addressof(value);3911  }3912 3913``__builtin_function_start``3914-----------------------------3915 3916``__builtin_function_start`` returns the address of a function body.3917 3918**Syntax**:3919 3920.. code-block:: c++3921 3922  void *__builtin_function_start(function)3923 3924**Example of use**:3925 3926.. code-block:: c++3927 3928  void a() {}3929  void *p = __builtin_function_start(a);3930 3931  class A {3932  public:3933    void a(int n);3934    void a();3935  };3936 3937  void A::a(int n) {}3938  void A::a() {}3939 3940  void *pa1 = __builtin_function_start((void(A::*)(int)) &A::a);3941  void *pa2 = __builtin_function_start((void(A::*)()) &A::a);3942 3943**Description**:3944 3945The ``__builtin_function_start`` builtin accepts an argument that can be3946constant-evaluated to a function, and returns the address of the function3947body.  This builtin is not supported on all targets.3948 3949The returned pointer may differ from the normally taken function address3950and is not safe to call.  For example, with ``-fsanitize=cfi``, taking a3951function address produces a callable pointer to a CFI jump table, while3952``__builtin_function_start`` returns an address that fails3953:doc:`cfi-icall<ControlFlowIntegrity>` checks.3954 3955``__builtin_operator_new`` and ``__builtin_operator_delete``3956------------------------------------------------------------3957 3958A call to ``__builtin_operator_new(args)`` is exactly the same as a call to3959``::operator new(args)``, except that it allows certain optimizations3960that the C++ standard does not permit for a direct function call to3961``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and3962merging allocations), and that the call is required to resolve to a3963`replaceable global allocation function3964<https://en.cppreference.com/w/cpp/memory/new/operator_new>`_.3965 3966Likewise, ``__builtin_operator_delete`` is exactly the same as a call to3967``::operator delete(args)``, except that it permits optimizations3968and that the call is required to resolve to a3969`replaceable global deallocation function3970<https://en.cppreference.com/w/cpp/memory/new/operator_delete>`_.3971 3972These builtins are intended for use in the implementation of ``std::allocator``3973and other similar allocation libraries, and are only available in C++.3974 3975Query for this feature with ``__has_builtin(__builtin_operator_new)`` or3976``__has_builtin(__builtin_operator_delete)``:3977 3978  * If the value is at least ``201802L``, the builtins behave as described above.3979 3980  * If the value is non-zero, the builtins may not support calling arbitrary3981    replaceable global (de)allocation functions, but do support calling at least3982    ``::operator new(size_t)`` and ``::operator delete(void*)``.3983 3984 3985``__builtin_trivially_relocate``3986-----------------------------------3987 3988**Syntax**:3989 3990.. code-block:: c3991 3992  T* __builtin_trivially_relocate(T* dest, T* src, size_t count)3993 3994Trivially relocates ``count`` objects of relocatable, complete type ``T``3995from ``src`` to ``dest`` and returns ``dest``.3996This builtin is used to implement ``std::trivially_relocate``.3997 3998``__builtin_invoke``3999--------------------4000 4001**Syntax**:4002 4003.. code-block:: c++4004 4005  template <class Callee, class... Args>4006  decltype(auto) __builtin_invoke(Callee&& callee, Args&&... args);4007 4008``__builtin_invoke`` is equivalent to ``std::invoke``.4009 4010``__builtin_preserve_access_index``4011-----------------------------------4012 4013``__builtin_preserve_access_index`` specifies a code section where4014array subscript access and structure/union member access are relocatable4015under bpf compile-once run-everywhere framework. Debuginfo (typically4016with ``-g``) is needed, otherwise, the compiler will exit with an error.4017The return type for the intrinsic is the same as the type of the4018argument.4019 4020**Syntax**:4021 4022.. code-block:: c4023 4024  type __builtin_preserve_access_index(type arg)4025 4026**Example of Use**:4027 4028.. code-block:: c4029 4030  struct t {4031    int i;4032    int j;4033    union {4034      int a;4035      int b;4036    } c[4];4037  };4038  struct t *v = ...;4039  int *pb =__builtin_preserve_access_index(&v->c[3].b);4040  __builtin_preserve_access_index(v->j);4041 4042``__builtin_debugtrap``4043-----------------------4044 4045``__builtin_debugtrap`` causes the program to stop its execution in such a way that a debugger can catch it.4046 4047**Syntax**:4048 4049.. code-block:: c++4050 4051    __builtin_debugtrap()4052 4053**Description**4054 4055``__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.4056 4057Query for this feature with ``__has_builtin(__builtin_debugtrap)``.4058 4059 4060``__builtin_trap``4061------------------4062 4063``__builtin_trap`` causes the program to stop its execution abnormally.4064 4065**Syntax**:4066 4067.. code-block:: c++4068 4069    __builtin_trap()4070 4071**Description**4072 4073``__builtin_trap`` is lowered to the ` ``llvm.trap`` <https://llvm.org/docs/LangRef.html#llvm-trap-intrinsic>`_ builtin.4074 4075Query for this feature with ``__has_builtin(__builtin_trap)``.4076 4077``__builtin_arm_trap``4078----------------------4079 4080``__builtin_arm_trap`` is an AArch64 extension to ``__builtin_trap`` which also accepts a compile-time constant value, encoded directly into the trap instruction for later inspection.4081 4082**Syntax**:4083 4084.. code-block:: c++4085 4086    __builtin_arm_trap(const unsigned short payload)4087 4088**Description**4089 4090``__builtin_arm_trap`` is lowered to the ``llvm.aarch64.break`` builtin, and then to ``brk #payload``.4091 4092``__builtin_verbose_trap``4093--------------------------4094 4095``__builtin_verbose_trap`` causes the program to stop its execution abnormally4096and shows a human-readable description of the reason for the termination when a4097debugger is attached or in a symbolicated crash log.4098 4099**Syntax**:4100 4101.. code-block:: c++4102 4103    __builtin_verbose_trap(const char *category, const char *reason)4104 4105**Description**4106 4107``__builtin_verbose_trap`` is lowered to the ` ``llvm.trap`` <https://llvm.org/docs/LangRef.html#llvm-trap-intrinsic>`_ builtin.4108Additionally, clang emits debugging information that represents an artificial4109inline frame whose name encodes the category and reason strings passed to the builtin,4110prefixed by a "magic" prefix.4111 4112For example, consider the following code:4113 4114.. code-block:: c++4115 4116    void foo(int* p) {4117      if (p == nullptr)4118        __builtin_verbose_trap("check null", "Argument must not be null!");4119    }4120 4121The debugging information would look as if it were produced for the following code:4122 4123.. code-block:: c++4124 4125    __attribute__((always_inline))4126    inline void "__clang_trap_msg$check null$Argument must not be null!"() {4127      __builtin_trap();4128    }4129 4130    void foo(int* p) {4131      if (p == nullptr)4132        "__clang_trap_msg$check null$Argument must not be null!"();4133    }4134 4135However, the generated code would not actually contain a call to the artificial4136function — it only exists in the debugging information.4137 4138Query for this feature with ``__has_builtin(__builtin_verbose_trap)``. Note that4139users need to enable debug information to enable this feature. A call to this4140builtin is equivalent to a call to ``__builtin_trap`` if debug information isn't4141enabled.4142 4143The optimizer can merge calls to trap with different messages, which degrades4144the debugging experience.4145 4146``__builtin_allow_runtime_check``4147---------------------------------4148 4149``__builtin_allow_runtime_check`` returns true if the check at the current4150program location should be executed. It is expected to be used to implement4151``assert`` like checks which can be safely removed by the optimizer.4152 4153**Syntax**:4154 4155.. code-block:: c++4156 4157    bool __builtin_allow_runtime_check(const char* kind)4158 4159**Example of use**:4160 4161.. code-block:: c++4162 4163  if (__builtin_allow_runtime_check("mycheck") && !ExpensiveCheck()) {4164     abort();4165  }4166 4167**Description**4168 4169``__builtin_allow_runtime_check`` is lowered to the `llvm.allow.runtime.check4170<https://llvm.org/docs/LangRef.html#llvm-allow-runtime-check-intrinsic>`_4171intrinsic.4172 4173The ``__builtin_allow_runtime_check()`` can be used within control structures4174like ``if`` to guard expensive runtime checks. The return value is determined4175by the following compiler options and may differ per call site:4176 4177* ``-mllvm -lower-allow-check-percentile-cutoff-hot=N``: Disable checks in hot4178  code marked by the profile summary with a hotness cutoff in the range4179  ``[0, 999999]`` (a larger N disables more checks).4180* ``-mllvm -lower-allow-check-random-rate=P``: Keep a check with probability P,4181  a floating point number in the range ``[0.0, 1.0]``.4182* If both options are specified, a check is disabled if either condition is satisfied.4183* If neither is specified, all checks are allowed.4184 4185Parameter ``kind``, currently unused, is a string literal specifying the check4186kind. Future compiler versions may use this to allow for more granular control,4187such as applying different hotness cutoffs to different check kinds.4188 4189Query for this feature with ``__has_builtin(__builtin_allow_runtime_check)``.4190 4191``__builtin_nondeterministic_value``4192------------------------------------4193 4194``__builtin_nondeterministic_value`` returns a valid nondeterministic value of the same type as the provided argument.4195 4196**Syntax**:4197 4198.. code-block:: c++4199 4200    type __builtin_nondeterministic_value(type x)4201 4202**Examples**:4203 4204.. code-block:: c++4205 4206    int x = __builtin_nondeterministic_value(x);4207    float y = __builtin_nondeterministic_value(y);4208    __m256i a = __builtin_nondeterministic_value(a);4209 4210**Description**4211 4212Each call to ``__builtin_nondeterministic_value`` returns a valid value of the type given by the argument.4213 4214The types currently supported are: integer types, floating-point types, vector types.4215 4216Query for this feature with ``__has_builtin(__builtin_nondeterministic_value)``.4217 4218``__builtin_sycl_unique_stable_name``4219-------------------------------------4220 4221``__builtin_sycl_unique_stable_name()`` is a builtin that takes a type and4222produces a string literal containing a unique name for the type that is stable4223across split compilations, mainly to support SYCL/Data Parallel C++ language.4224 4225In cases where the split compilation needs to share a unique token for a type4226across the boundary (such as in an offloading situation), this name can be used4227for lookup purposes, such as in the SYCL Integration Header.4228 4229The value of this builtin is computed entirely at compile time, so it can be4230used in constant expressions. This value encodes lambda functions based on a4231stable numbering order in which they appear in their local declaration contexts.4232Once this builtin is evaluated in a constexpr context, it is erroneous to use4233it in an instantiation which changes its value.4234 4235In order to produce the unique name, the current implementation of the builtin4236uses Itanium mangling even if the host compilation uses a different name4237mangling scheme at runtime. The mangler marks all the lambdas required to name4238the SYCL kernel and emits a stable local ordering of the respective lambdas.4239The resulting pattern is demanglable.  When non-lambda types are passed to the4240builtin, the mangler emits their usual pattern without any special treatment.4241 4242**Syntax**:4243 4244.. code-block:: c4245 4246  // Computes a unique stable name for the given type.4247  constexpr const char * __builtin_sycl_unique_stable_name( type-id );4248 4249``__builtin_popcountg``4250-----------------------4251 4252``__builtin_popcountg`` returns the number of 1 bits in the argument. The4253argument can be of any unsigned integer type or fixed boolean vector.4254 4255**Syntax**:4256 4257.. code-block:: c++4258 4259  int __builtin_popcountg(type x)4260 4261**Examples**:4262 4263.. code-block:: c++4264 4265  unsigned int x = 1;4266  int x_pop = __builtin_popcountg(x);4267 4268  unsigned long y = 3;4269  int y_pop = __builtin_popcountg(y);4270 4271  unsigned _BitInt(128) z = 7;4272  int z_pop = __builtin_popcountg(z);4273 4274**Description**:4275 4276``__builtin_popcountg`` is meant to be a type-generic alternative to the4277``__builtin_popcount{,l,ll}`` builtins, with support for other integer types,4278such as ``unsigned __int128`` and C23 ``unsigned _BitInt(N)``.4279 4280``__builtin_clzg`` and ``__builtin_ctzg``4281-----------------------------------------4282 4283``__builtin_clzg`` (respectively ``__builtin_ctzg``) returns the number of4284leading (respectively trailing) 0 bits in the first argument. The first argument4285can be of any unsigned integer type or fixed boolean vector.4286 4287For boolean vectors, these builtins interpret the vector like a bit-field where4288the ith element of the vector is bit i of the bit-field, counting from the4289least significant end. ``__builtin_clzg`` returns the number of zero elements at4290the end of the vector, while ``__builtin_ctzg`` returns the number of zero4291elements at the start of the vector.4292 4293If the first argument is 0 and an optional second argument of ``int`` type is4294provided, then the second argument is returned. If the first argument is 0, but4295only one argument is provided, then the behavior is undefined.4296 4297**Syntax**:4298 4299.. code-block:: c++4300 4301  int __builtin_clzg(type x[, int fallback])4302  int __builtin_ctzg(type x[, int fallback])4303 4304**Examples**:4305 4306.. code-block:: c++4307 4308  unsigned int x = 1;4309  int x_lz = __builtin_clzg(x);4310  int x_tz = __builtin_ctzg(x);4311 4312  unsigned long y = 2;4313  int y_lz = __builtin_clzg(y);4314  int y_tz = __builtin_ctzg(y);4315 4316  unsigned _BitInt(128) z = 4;4317  int z_lz = __builtin_clzg(z);4318  int z_tz = __builtin_ctzg(z);4319 4320**Description**:4321 4322``__builtin_clzg`` (respectively ``__builtin_ctzg``) is meant to be a4323type-generic alternative to the ``__builtin_clz{,l,ll}`` (respectively4324``__builtin_ctz{,l,ll}``) builtins, with support for other integer types, such4325as ``unsigned __int128`` and C23 ``unsigned _BitInt(N)``.4326 4327``__builtin_counted_by_ref``4328----------------------------4329 4330``__builtin_counted_by_ref`` returns a pointer to the count field from the4331``counted_by`` attribute.4332 4333The argument must be a flexible array member. If the argument isn't a flexible4334array member or doesn't have the ``counted_by`` attribute, the builtin returns4335``(void *)0``.4336 4337**Syntax**:4338 4339.. code-block:: c4340 4341  T *__builtin_counted_by_ref(void *array)4342 4343**Examples**:4344 4345.. code-block:: c4346 4347  #define alloc(P, FAM, COUNT) ({                                 \4348     size_t __ignored_assignment;                                 \4349     typeof(P) __p = NULL;                                        \4350     __p = malloc(MAX(sizeof(*__p),                               \4351                      sizeof(*__p) + sizeof(*__p->FAM) * COUNT)); \4352                                                                  \4353     *_Generic(                                                   \4354       __builtin_counted_by_ref(__p->FAM),                        \4355         void *: &__ignored_assignment,                           \4356         default: __builtin_counted_by_ref(__p->FAM)) = COUNT;    \4357                                                                  \4358     __p;                                                         \4359  })4360 4361**Description**:4362 4363The ``__builtin_counted_by_ref`` builtin allows the programmer to prevent a4364common error associated with the ``counted_by`` attribute. When using the4365``counted_by`` attribute, the ``count`` field **must** be set before the4366flexible array member can be accessed. Otherwise, the sanitizers may view such4367accesses as false positives. For instance, it's not uncommon for programmers to4368initialize the flexible array before setting the ``count`` field:4369 4370.. code-block:: c4371 4372  struct s {4373    int dummy;4374    short count;4375    long array[] __attribute__((counted_by(count)));4376  };4377 4378  struct s *ptr = malloc(sizeof(struct s) + sizeof(long) * COUNT);4379 4380  for (int i = 0; i < COUNT; ++i)4381    ptr->array[i] = i;4382 4383  ptr->count = COUNT;4384 4385Enforcing the rule that ``ptr->count = COUNT;`` must occur after every4386allocation of a struct with a flexible array member with the ``counted_by``4387attribute is prone to failure in large code bases. This builtin mitigates this4388for allocators (like in Linux) that are implemented in a way where the counter4389assignment can happen automatically.4390 4391**Note:** The value returned by ``__builtin_counted_by_ref`` cannot be assigned4392to a variable, have its address taken, or passed into or returned from a4393function, because doing so violates bounds safety conventions.4394 4395Multiprecision Arithmetic Builtins4396----------------------------------4397 4398Clang provides a set of builtins which expose multiprecision arithmetic in a4399manner amenable to C. They all have the following form:4400 4401.. code-block:: c4402 4403  unsigned x = ..., y = ..., carryin = ..., carryout;4404  unsigned sum = __builtin_addc(x, y, carryin, &carryout);4405 4406Thus one can form a multiprecision addition chain in the following manner:4407 4408.. code-block:: c4409 4410  unsigned *x, *y, *z, carryin=0, carryout;4411  z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);4412  carryin = carryout;4413  z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);4414  carryin = carryout;4415  z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);4416  carryin = carryout;4417  z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);4418 4419The complete list of builtins are:4420 4421.. code-block:: c4422 4423  unsigned char      __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);4424  unsigned short     __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);4425  unsigned           __builtin_addc  (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);4426  unsigned long      __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);4427  unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);4428  unsigned char      __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);4429  unsigned short     __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);4430  unsigned           __builtin_subc  (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);4431  unsigned long      __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);4432  unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);4433 4434Checked Arithmetic Builtins4435---------------------------4436 4437Clang provides a set of builtins that implement checked arithmetic for security4438critical applications in a manner that is fast and easily expressible in C. As4439an example of their usage:4440 4441.. code-block:: c4442 4443  errorcode_t security_critical_application(...) {4444    unsigned x, y, result;4445    ...4446    if (__builtin_mul_overflow(x, y, &result))4447      return kErrorCodeHackers;4448    ...4449    use_multiply(result);4450    ...4451  }4452 4453Clang provides the following checked arithmetic builtins:4454 4455.. code-block:: c4456 4457  bool __builtin_add_overflow   (type1 x, type2 y, type3 *sum);4458  bool __builtin_sub_overflow   (type1 x, type2 y, type3 *diff);4459  bool __builtin_mul_overflow   (type1 x, type2 y, type3 *prod);4460  bool __builtin_uadd_overflow  (unsigned x, unsigned y, unsigned *sum);4461  bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);4462  bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);4463  bool __builtin_usub_overflow  (unsigned x, unsigned y, unsigned *diff);4464  bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);4465  bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);4466  bool __builtin_umul_overflow  (unsigned x, unsigned y, unsigned *prod);4467  bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);4468  bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);4469  bool __builtin_sadd_overflow  (int x, int y, int *sum);4470  bool __builtin_saddl_overflow (long x, long y, long *sum);4471  bool __builtin_saddll_overflow(long long x, long long y, long long *sum);4472  bool __builtin_ssub_overflow  (int x, int y, int *diff);4473  bool __builtin_ssubl_overflow (long x, long y, long *diff);4474  bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);4475  bool __builtin_smul_overflow  (int x, int y, int *prod);4476  bool __builtin_smull_overflow (long x, long y, long *prod);4477  bool __builtin_smulll_overflow(long long x, long long y, long long *prod);4478 4479Each builtin performs the specified mathematical operation on the4480first two arguments and stores the result in the third argument.  If4481possible, the result will be equal to mathematically-correct result4482and the builtin will return 0.  Otherwise, the builtin will return44831 and the result will be equal to the unique value that is equivalent4484to the mathematically-correct result modulo two raised to the *k*4485power, where *k* is the number of bits in the result type.  The4486behavior of these builtins is well-defined for all argument values.4487 4488The first three builtins work generically for operands of any integer type,4489including boolean types.  The operands need not have the same type as each4490other, or as the result.  The other builtins may implicitly promote or4491convert their operands before performing the operation.4492 4493Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc.4494 4495Floating point builtins4496---------------------------------------4497 4498``__builtin_isfpclass``4499-----------------------4500 4501``__builtin_isfpclass`` is used to test if the specified floating-point values4502fall into one of the specified floating-point classes.4503 4504**Syntax**:4505 4506.. code-block:: c++4507 4508    int __builtin_isfpclass(fp_type expr, int mask)4509    int_vector __builtin_isfpclass(fp_vector expr, int mask)4510 4511**Example of use**:4512 4513.. code-block:: c++4514 4515  if (__builtin_isfpclass(x, 448)) {4516     // `x` is positive finite value4517         ...4518  }4519 4520**Description**:4521 4522The ``__builtin_isfpclass()`` builtin is a generalization of functions ``isnan``,4523``isinf``, ``isfinite`` and some others defined by the C standard. It tests if4524the floating-point value, specified by the first argument, falls into any of data4525classes, specified by the second argument. The latter is an integer constant4526bitmask expression, in which each data class is represented by a bit4527using the encoding:4528 4529========== =================== ======================4530Mask value Data class          Macro4531========== =================== ======================45320x0001     Signaling NaN       __FPCLASS_SNAN45330x0002     Quiet NaN           __FPCLASS_QNAN45340x0004     Negative infinity   __FPCLASS_NEGINF45350x0008     Negative normal     __FPCLASS_NEGNORMAL45360x0010     Negative subnormal  __FPCLASS_NEGSUBNORMAL45370x0020     Negative zero       __FPCLASS_NEGZERO45380x0040     Positive zero       __FPCLASS_POSZERO45390x0080     Positive subnormal  __FPCLASS_POSSUBNORMAL45400x0100     Positive normal     __FPCLASS_POSNORMAL45410x0200     Positive infinity   __FPCLASS_POSINF4542========== =================== ======================4543 4544For convenience preprocessor defines macros for these values. The function4545returns 1 if ``expr`` falls into one of the specified data classes, 0 otherwise.4546 4547In the example above the mask value 448 (0x1C0) contains the bits selecting4548positive zero, positive subnormal and positive normal classes.4549``__builtin_isfpclass(x, 448)`` would return true only if ``x`` if of any of4550these data classes. Using suitable mask value, the function can implement any of4551the standard classification functions, for example, ``__builtin_isfpclass(x, 3)``4552is identical to ``isnan``,``__builtin_isfpclass(x, 504)`` - to ``isfinite``4553and so on.4554 4555If the first argument is a vector, the function is equivalent to the set of4556scalar calls of ``__builtin_isfpclass`` applied to the input elementwise.4557 4558The result of ``__builtin_isfpclass`` is a boolean value, if the first argument4559is a scalar, or an integer vector with the same element count as the first4560argument. The element type in this vector has the same bit length as the4561element of the first argument type.4562 4563This function never raises floating-point exceptions and does not canonicalize4564its input. The floating-point argument is not promoted, its data class is4565determined based on its representation in its actual semantic type.4566 4567``__builtin_canonicalize``4568--------------------------4569 4570.. code-block:: c4571 4572   double __builtin_canonicalize(double);4573   float __builtin_canonicalizef(float);4574   long double __builtin_canonicalizel(long double);4575 4576Returns the platform specific canonical encoding of a floating point4577number. This canonicalization is useful for implementing certain4578numeric primitives such as frexp. See `LLVM canonicalize intrinsic4579<https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for4580more information on the semantics.4581 4582``__builtin_flt_rounds`` and ``__builtin_set_flt_rounds``4583---------------------------------------------------------4584 4585.. code-block:: c4586 4587   int __builtin_flt_rounds();4588   void __builtin_set_flt_rounds(int);4589 4590Returns and sets current floating point rounding mode. The encoding of returned4591values and input parameters is same as the result of FLT_ROUNDS, specified by C4592standard:4593- ``0``  - toward zero4594- ``1``  - to nearest, ties to even4595- ``2``  - toward positive infinity4596- ``3``  - toward negative infinity4597- ``4``  - to nearest, ties away from zero4598The effect of passing some other value to ``__builtin_flt_rounds`` is4599implementation-defined. ``__builtin_set_flt_rounds`` is currently only supported4600to work on x86, x86_64, powerpc, powerpc64, Arm and AArch64 targets. These builtins4601read and modify the floating-point environment, which is not always allowed and may4602have unexpected behavior. Please see the section on `Accessing the floating point environment <https://clang.llvm.org/docs/UsersManual.html#accessing-the-floating-point-environment>`_ for more information.4603 4604String builtins4605---------------4606 4607Clang provides constant expression evaluation support for builtins forms of4608the following functions from the C standard library headers4609``<string.h>`` and ``<wchar.h>``:4610 4611* ``memchr``4612* ``memcmp`` (and its deprecated BSD / POSIX alias ``bcmp``)4613* ``strchr``4614* ``strcmp``4615* ``strlen``4616* ``strncmp``4617* ``wcschr``4618* ``wcscmp``4619* ``wcslen``4620* ``wcsncmp``4621* ``wmemchr``4622* ``wmemcmp``4623 4624In each case, the builtin form has the name of the C library function prefixed4625by ``__builtin_``. Example:4626 4627.. code-block:: c4628 4629  void *p = __builtin_memchr("foobar", 'b', 5);4630 4631In addition to the above, one further builtin is provided:4632 4633.. code-block:: c4634 4635  char *__builtin_char_memchr(const char *haystack, int needle, size_t size);4636 4637``__builtin_char_memchr(a, b, c)`` is identical to4638``(char*)__builtin_memchr(a, b, c)`` except that its use is permitted within4639constant expressions in C++11 onwards (where a cast from ``void*`` to ``char*``4640is disallowed in general).4641 4642Constant evaluation support for the ``__builtin_mem*`` functions is provided4643only for arrays of ``char``, ``signed char``, ``unsigned char``, or ``char8_t``,4644despite these functions accepting an argument of type ``const void*``.4645 4646Support for constant expression evaluation for the above builtins can be detected4647with ``__has_feature(cxx_constexpr_string_builtins)``.4648 4649Variadic function builtins4650--------------------------4651 4652Clang provides several builtins for working with variadic functions from the C4653standard library ``<stdarg.h>`` header:4654 4655* ``__builtin_va_list``4656 4657A predefined typedef for the target-specific ``va_list`` type. It is undefined4658behavior to use a byte-wise copy of this type produced by calling ``memcpy``,4659``memmove``, or similar. Valid explicit copies are only produced by calling4660``va_copy`` or ``__builtin_va_copy``.4661 4662* ``void __builtin_va_start(__builtin_va_list list, <parameter-name>)``4663 4664A builtin function for the target-specific ``va_start`` function-like macro.4665The ``parameter-name`` argument is the name of the parameter preceding the4666ellipsis (``...``) in the function signature. Alternatively, in C23 mode or4667later, it may be the integer literal ``0`` if there is no parameter preceding4668the ellipsis. This function initializes the given ``__builtin_va_list`` object.4669It is undefined behavior to call this function on an already initialized4670``__builtin_va_list`` object.4671 4672* ``void __builtin_c23_va_start(__builtin_va_list list, ...)``4673 4674A builtin function for the target-specific ``va_start`` function-like macro,4675available only in C23 and later. The builtin accepts zero or one argument for4676the ellipsis (``...``). If such an argument is provided, it should be the name4677of the parameter preceding the ellipsis, which is used for compatibility with4678C versions before C23. It is an error to provide two or more variadic arguments.4679This function initializes the given ``__builtin_va_list`` object. It is4680undefined behavior to call this function on an already initialized4681``__builtin_va_list`` object.4682 4683* ``void __builtin_va_end(__builtin_va_list list)``4684 4685A builtin function for the target-specific ``va_end`` function-like macro. This4686function finalizes the given ``__builtin_va_list`` object such that it is no4687longer usable unless re-initialized with a call to ``__builtin_va_start`` or4688``__builtin_va_copy``. It is undefined behavior to call this function with a4689``list`` that has not been initialized by either ``__builtin_va_start`` or4690``__builtin_va_copy``.4691 4692* ``<type-name> __builtin_va_arg(__builtin_va_list list, <type-name>)``4693 4694A builtin function for the target-specific ``va_arg`` function-like macro. This4695function returns the value of the next variadic argument to the call. It is4696undefined behavior to call this builtin when there is no next variadic argument4697to retrieve or if the next variadic argument does not have a type compatible4698with the given ``type-name``. The return type of the function is the4699``type-name`` given as the second argument. It is undefined behavior to call4700this function with a ``list`` that has not been initialized by either4701``__builtin_va_start`` or ``__builtin_va_copy``.4702 4703* ``void __builtin_va_copy(__builtin_va_list dest, __builtin_va_list src)``4704 4705A builtin function for the target-specific ``va_copy`` function-like macro.4706This function initializes ``dest`` as a copy of ``src``. It is undefined4707behavior to call this function with an already initialized ``dest`` argument.4708 4709Memory builtins4710---------------4711 4712Clang provides constant expression evaluation support for builtin forms of the4713following functions from the C standard library headers4714``<string.h>`` and ``<wchar.h>``:4715 4716* ``memcpy``4717* ``memmove``4718* ``wmemcpy``4719* ``wmemmove``4720 4721In each case, the builtin form has the name of the C library function prefixed4722by ``__builtin_``.4723 4724Constant evaluation support is only provided when the source and destination4725are pointers to arrays with the same trivially copyable element type, and the4726given size is an exact multiple of the element size that is no greater than4727the number of elements accessible through the source and destination operands.4728 4729Guaranteed inlined copy4730^^^^^^^^^^^^^^^^^^^^^^^4731 4732.. code-block:: c4733 4734  void __builtin_memcpy_inline(void *dst, const void *src, size_t size);4735 4736 4737``__builtin_memcpy_inline`` has been designed as a building block for efficient4738``memcpy`` implementations. It is identical to ``__builtin_memcpy`` but also4739guarantees not to call any external functions. See LLVM IR `llvm.memcpy.inline4740<https://llvm.org/docs/LangRef.html#llvm-memcpy-inline-intrinsic>`_ intrinsic4741for more information.4742 4743This is useful to implement a custom version of ``memcpy``, implement a4744``libc`` memcpy or work around the absence of a ``libc``.4745 4746Note that the `size` argument must be a compile time constant.4747 4748Note that this intrinsic cannot yet be called in a ``constexpr`` context.4749 4750Guaranteed inlined memset4751^^^^^^^^^^^^^^^^^^^^^^^^^4752 4753.. code-block:: c4754 4755  void __builtin_memset_inline(void *dst, int value, size_t size);4756 4757 4758``__builtin_memset_inline`` has been designed as a building block for efficient4759``memset`` implementations. It is identical to ``__builtin_memset`` but also4760guarantees not to call any external functions. See LLVM IR `llvm.memset.inline4761<https://llvm.org/docs/LangRef.html#llvm-memset-inline-intrinsic>`_ intrinsic4762for more information.4763 4764This is useful to implement a custom version of ``memset``, implement a4765``libc`` memset or work around the absence of a ``libc``.4766 4767Note that the `size` argument must be a compile time constant.4768 4769Note that this intrinsic cannot yet be called in a ``constexpr`` context.4770 4771``__is_bitwise_cloneable``4772--------------------------4773 4774A type trait is used to check whether a type can be safely copied by memcpy.4775 4776**Syntax**:4777 4778.. code-block:: c++4779 4780  bool __is_bitwise_cloneable(Type)4781 4782**Description**:4783 4784Objects of bitwise cloneable types can be bitwise copied by memcpy/memmove. The4785Clang compiler warrants that this behavior is well defined, and won't be4786broken by compiler optimizations and sanitizers.4787 4788For implicit-lifetime types, the lifetime of the new object is implicitly4789started after the copy. For other types (e.g., classes with virtual methods),4790the lifetime isn't started, and using the object results in undefined behavior4791according to the C++ Standard.4792 4793This builtin can be used in constant expressions.4794 4795Atomic Min/Max builtins with memory ordering4796--------------------------------------------4797 4798There are two atomic builtins with min/max in-memory comparison and swap.4799The syntax and semantics are similar to GCC-compatible __atomic_* builtins.4800 4801* ``__atomic_fetch_min``4802* ``__atomic_fetch_max``4803 4804The builtins work with signed and unsigned integers and require to specify memory ordering.4805The return value is the original value that was stored in memory before comparison.4806 4807Example:4808 4809.. code-block:: c4810 4811  unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED);4812 4813The third argument is one of the memory ordering specifiers ``__ATOMIC_RELAXED``,4814``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, ``__ATOMIC_RELEASE``,4815``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics.4816 4817In terms of acquire-release ordering barriers these two operations are always4818considered as operations with *load-store* semantics, even when the original value4819is not actually modified after comparison.4820 4821.. _langext-__c11_atomic:4822 4823__c11_atomic builtins4824---------------------4825 4826Clang provides a set of builtins which are intended to be used to implement4827C11's ``<stdatomic.h>`` header.  These builtins provide the semantics of the4828``_explicit`` form of the corresponding C11 operation, and are named with a4829``__c11_`` prefix.  The supported operations, and the differences from4830the corresponding C11 operations, are:4831 4832* ``__c11_atomic_init``4833* ``__c11_atomic_thread_fence``4834* ``__c11_atomic_signal_fence``4835* ``__c11_atomic_is_lock_free`` (The argument is the size of the4836  ``_Atomic(...)`` object, instead of its address)4837* ``__c11_atomic_store``4838* ``__c11_atomic_load``4839* ``__c11_atomic_exchange``4840* ``__c11_atomic_compare_exchange_strong``4841* ``__c11_atomic_compare_exchange_weak``4842* ``__c11_atomic_fetch_add``4843* ``__c11_atomic_fetch_sub``4844* ``__c11_atomic_fetch_and``4845* ``__c11_atomic_fetch_or``4846* ``__c11_atomic_fetch_xor``4847* ``__c11_atomic_fetch_nand`` (Nand is not presented in ``<stdatomic.h>``)4848* ``__c11_atomic_fetch_max``4849* ``__c11_atomic_fetch_min``4850 4851The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``,4852``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are4853provided, with values corresponding to the enumerators of C11's4854``memory_order`` enumeration.4855 4856(Note that Clang additionally provides GCC-compatible ``__atomic_*``4857builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.04858atomic builtins are an explicit form of the corresponding OpenCL 2.04859builtin function, and are named with a ``__opencl_`` prefix. The macros4860``__OPENCL_MEMORY_SCOPE_WORK_ITEM``, ``__OPENCL_MEMORY_SCOPE_WORK_GROUP``,4861``__OPENCL_MEMORY_SCOPE_DEVICE``, ``__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES``,4862and ``__OPENCL_MEMORY_SCOPE_SUB_GROUP`` are provided, with values4863corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.)4864 4865__scoped_atomic builtins4866------------------------4867 4868Clang provides a set of atomics taking a memory scope argument. These atomics4869are identical to the standard GNU / GCC atomic builtins but taking an extra4870memory scope argument. These are designed to be a generic alternative to the4871``__opencl_atomic_*`` builtin functions for targets that support atomic memory4872scopes.4873 4874Clang provides two additional __scoped_atomic builtins:4875 4876* ``__scoped_atomic_uinc_wrap``4877* ``__scoped_atomic_udec_wrap``4878 4879See LLVM IR `atomicrmw <https://llvm.org/docs/LangRef.html#atomicrmw-instruction>`_4880instruction for the semantics of uinc_wrap and udec_wrap.4881 4882Atomic memory scopes are designed to assist optimizations for systems with4883several levels of memory hierarchy like GPUs. The following memory scopes are4884currently supported:4885 4886* ``__MEMORY_SCOPE_SYSTEM``4887* ``__MEMORY_SCOPE_DEVICE``4888* ``__MEMORY_SCOPE_WRKGRP``4889* ``__MEMORY_SCOPE_CLUSTR``4890* ``__MEMORY_SCOPE_WVFRNT``4891* ``__MEMORY_SCOPE_SINGLE``4892 4893This controls whether or not the atomic operation is ordered with respect to the4894whole system, the current device, an OpenCL workgroup, wavefront, or just a4895single thread. If these are used on a target that does not support atomic4896scopes, then they will behave exactly as the standard GNU atomic builtins.4897 4898Low-level ARM exclusive memory builtins4899---------------------------------------4900 4901Clang provides overloaded builtins giving direct access to the three key ARM4902instructions for implementing atomic operations.4903 4904.. code-block:: c4905 4906  T __builtin_arm_ldrex(const volatile T *addr);4907  T __builtin_arm_ldaex(const volatile T *addr);4908  int __builtin_arm_strex(T val, volatile T *addr);4909  int __builtin_arm_stlex(T val, volatile T *addr);4910  void __builtin_arm_clrex(void);4911 4912The types ``T`` currently supported are:4913 4914* Integer types with width at most 64 bits (or 128 bits on AArch64).4915* Floating-point types4916* Pointer types.4917 4918Note that the compiler does not guarantee it will not insert stores which clear4919the exclusive monitor in between an ``ldrex`` type operation and its paired4920``strex``. In practice this is only usually a risk when the extra store is on4921the same cache line as the variable being modified and Clang will only insert4922stack stores on its own, so it is best not to use these operations on variables4923with automatic storage duration.4924 4925Also, loads and stores may be implicit in code written between the ``ldrex`` and4926``strex``. Clang will not necessarily mitigate the effects of these either, so4927care should be exercised.4928 4929For these reasons the higher level atomic primitives should be preferred where4930possible.4931 4932Non-temporal load/store builtins4933--------------------------------4934 4935Clang provides overloaded builtins allowing generation of non-temporal memory4936accesses.4937 4938.. code-block:: c4939 4940  T __builtin_nontemporal_load(T *addr);4941  void __builtin_nontemporal_store(T value, T *addr);4942 4943The types ``T`` currently supported are:4944 4945* Integer types.4946* Floating-point types.4947* Vector types.4948 4949Note that the compiler does not guarantee that non-temporal loads or stores4950will be used.4951 4952C++ Coroutines support builtins4953--------------------------------4954 4955.. warning::4956  This is a work in progress. Compatibility across Clang/LLVM releases is not4957  guaranteed.4958 4959Clang provides experimental builtins to support C++ Coroutines as defined by4960https://wg21.link/P0057. The following four are intended to be used by the4961standard library to implement the ``std::coroutine_handle`` type.4962 4963**Syntax**:4964 4965.. code-block:: c4966 4967  void  __builtin_coro_resume(void *addr);4968  void  __builtin_coro_destroy(void *addr);4969  bool  __builtin_coro_done(void *addr);4970  void *__builtin_coro_promise(void *addr, int alignment, bool from_promise)4971 4972**Example of use**:4973 4974.. code-block:: c++4975 4976  template <> struct coroutine_handle<void> {4977    void resume() const { __builtin_coro_resume(ptr); }4978    void destroy() const { __builtin_coro_destroy(ptr); }4979    bool done() const { return __builtin_coro_done(ptr); }4980    // ...4981  protected:4982    void *ptr;4983  };4984 4985  template <typename Promise> struct coroutine_handle : coroutine_handle<> {4986    // ...4987    Promise &promise() const {4988      return *reinterpret_cast<Promise *>(4989        __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false));4990    }4991    static coroutine_handle from_promise(Promise &promise) {4992      coroutine_handle p;4993      p.ptr = __builtin_coro_promise(&promise, alignof(Promise),4994                                                      /*from-promise=*/true);4995      return p;4996    }4997  };4998 4999 5000Other coroutine builtins are either for internal clang use or for use during5001development of the coroutine feature. See `Coroutines in LLVM5002<https://llvm.org/docs/Coroutines.html#intrinsics>`_ for5003more information on their semantics. Note that builtins matching the intrinsics5004that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc,5005llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to5006an appropriate value during the emission.5007 5008**Syntax**:5009 5010.. code-block:: c5011 5012  size_t __builtin_coro_size()5013  void  *__builtin_coro_frame()5014  void  *__builtin_coro_free(void *coro_frame)5015 5016  void  *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts)5017  bool   __builtin_coro_alloc()5018  void  *__builtin_coro_begin(void *memory)5019  void   __builtin_coro_end(void *coro_frame, bool unwind)5020  char   __builtin_coro_suspend(bool final)5021 5022Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM5023automatically will insert one if the first argument to `llvm.coro.suspend` is5024token `none`. If a user calls `__builtin_suspend`, clang will insert `token none`5025as the first argument to the intrinsic.5026 5027Source location builtins5028------------------------5029 5030Clang provides builtins to support C++ standard library implementation5031of ``std::source_location`` as specified in C++20.  With the exception5032of ``__builtin_COLUMN``, ``__builtin_FILE_NAME`` and ``__builtin_FUNCSIG``,5033these builtins are also implemented by GCC.5034 5035**Syntax**:5036 5037.. code-block:: c5038 5039  const char *__builtin_FILE();5040  const char *__builtin_FILE_NAME(); // Clang only5041  const char *__builtin_FUNCTION();5042  const char *__builtin_FUNCSIG(); // Microsoft5043  unsigned    __builtin_LINE();5044  unsigned    __builtin_COLUMN(); // Clang only5045  const std::source_location::__impl *__builtin_source_location();5046 5047**Example of use**:5048 5049.. code-block:: c++5050 5051  void my_assert(bool pred, int line = __builtin_LINE(), // Captures line of caller5052                 const char* file = __builtin_FILE(),5053                 const char* function = __builtin_FUNCTION()) {5054    if (pred) return;5055    printf("%s:%d assertion failed in function %s\n", file, line, function);5056    std::abort();5057  }5058 5059  struct MyAggregateType {5060    int x;5061    int line = __builtin_LINE(); // captures line where aggregate initialization occurs5062  };5063  static_assert(MyAggregateType{42}.line == __LINE__);5064 5065  struct MyClassType {5066    int line = __builtin_LINE(); // captures line of the constructor used during initialization5067    constexpr MyClassType(int) { assert(line == __LINE__); }5068  };5069 5070**Description**:5071 5072The builtins ``__builtin_LINE``, ``__builtin_FUNCTION``, ``__builtin_FUNCSIG``,5073``__builtin_FILE`` and ``__builtin_FILE_NAME`` return the values, at the5074"invocation point", for ``__LINE__``, ``__FUNCTION__``, ``__FUNCSIG__``,5075``__FILE__`` and ``__FILE_NAME__`` respectively. ``__builtin_COLUMN`` similarly5076returns the column, though there is no corresponding macro. These builtins are5077constant expressions.5078 5079When the builtins appear as part of a default function argument the invocation5080point is the location of the caller. When the builtins appear as part of a5081default member initializer, the invocation point is the location of the5082constructor or aggregate initialization used to create the object. Otherwise5083the invocation point is the same as the location of the builtin.5084 5085When the invocation point of ``__builtin_FUNCTION`` is not a function scope, the5086empty string is returned.5087 5088The builtin ``__builtin_COLUMN`` returns the offset from the start of the line,5089beginning from column 1. `This may differ from other implementations.5090<https://eel.is/c++draft/support.srcloc#tab:support.srcloc.current-row-3-column-2-sentence-2>`_5091 5092The builtin ``__builtin_source_location`` returns a pointer to constant static5093data of type ``std::source_location::__impl``. This type must have already been5094defined, and must contain exactly four fields: ``const char *_M_file_name``,5095``const char *_M_function_name``, ``<any-integral-type> _M_line``, and5096``<any-integral-type> _M_column``. The fields will be populated in the same5097manner as the above four builtins, except that ``_M_function_name`` is populated5098with ``__PRETTY_FUNCTION__`` rather than ``__FUNCTION__``.5099 5100 5101Alignment builtins5102------------------5103Clang provides builtins to support checking and adjusting alignment of5104pointers and integers.5105These builtins can be used to avoid relying on implementation-defined behavior5106of arithmetic on integers derived from pointers.5107Additionally, these builtins retain type information and, unlike bitwise5108arithmetic, they can perform semantic checking on the alignment value.5109 5110**Syntax**:5111 5112.. code-block:: c5113 5114  Type __builtin_align_up(Type value, size_t alignment);5115  Type __builtin_align_down(Type value, size_t alignment);5116  bool __builtin_is_aligned(Type value, size_t alignment);5117 5118 5119**Example of use**:5120 5121.. code-block:: c++5122 5123  char* global_alloc_buffer;5124  void* my_aligned_allocator(size_t alloc_size, size_t alignment) {5125    char* result = __builtin_align_up(global_alloc_buffer, alignment);5126    // result now contains the value of global_alloc_buffer rounded up to the5127    // next multiple of alignment.5128    global_alloc_buffer = result + alloc_size;5129    return result;5130  }5131 5132  void* get_start_of_page(void* ptr) {5133    return __builtin_align_down(ptr, PAGE_SIZE);5134  }5135 5136  void example(char* buffer) {5137     if (__builtin_is_aligned(buffer, 64)) {5138       do_fast_aligned_copy(buffer);5139     } else {5140       do_unaligned_copy(buffer);5141     }5142  }5143 5144  // In addition to pointers, the builtins can also be used on integer types5145  // and are evaluatable inside constant expressions.5146  static_assert(__builtin_align_up(123, 64) == 128, "");5147  static_assert(__builtin_align_down(123u, 64) == 64u, "");5148  static_assert(!__builtin_is_aligned(123, 64), "");5149 5150 5151**Description**:5152 5153The builtins ``__builtin_align_up``, ``__builtin_align_down``, return their5154first argument aligned up/down to the next multiple of the second argument.5155If the value is already sufficiently aligned, it is returned unchanged.5156The builtin ``__builtin_is_aligned`` returns whether the first argument is5157aligned to a multiple of the second argument.5158All of these builtins expect the alignment to be expressed as a number of bytes.5159 5160These builtins can be used for all integer types as well as (non-function)5161pointer types. For pointer types, these builtins operate in terms of the integer5162address of the pointer and return a new pointer of the same type (including5163qualifiers such as ``const``) with an adjusted address.5164When aligning pointers up or down, the resulting value must be within the same5165underlying allocation or one past the end (see C17 6.5.6p8, C++ [expr.add]).5166This means that arbitrary integer values stored in pointer-type variables must5167not be passed to these builtins. For those use cases, the builtins can still be5168used, but the operation must be performed on the pointer cast to ``uintptr_t``.5169 5170If Clang can determine that the alignment is not a power of two at compile time,5171it will result in a compilation failure. If the alignment argument is not a5172power of two at run time, the behavior of these builtins is undefined.5173 5174Non-standard C++11 Attributes5175=============================5176 5177Clang's non-standard C++11 attributes live in the ``clang`` attribute5178namespace.5179 5180Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which5181are accepted with the ``__attribute__((foo))`` syntax are also accepted as5182``[[gnu::foo]]``. This only extends to attributes which are specified by GCC5183(see the list of `GCC function attributes5184<https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable5185attributes <https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and5186`GCC type attributes5187<https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC5188implementation, these attributes must appertain to the *declarator-id* in a5189declaration, which means they must go either at the start of the declaration or5190immediately after the name being declared.5191 5192For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and5193also applies the GNU ``noreturn`` attribute to ``f``.5194 5195Examples:5196.. code-block:: c++5197 5198  [[gnu::unused]] int a, f [[gnu::noreturn]] ();5199 5200Target-Specific Extensions5201==========================5202 5203Clang supports some language features conditionally on some targets.5204 5205AMDGPU Language Extensions5206--------------------------5207 5208__builtin_amdgcn_fence5209^^^^^^^^^^^^^^^^^^^^^^5210 5211``__builtin_amdgcn_fence`` emits a fence.5212 5213* ``unsigned`` atomic ordering, e.g., ``__ATOMIC_ACQUIRE``5214* ``const char *`` synchronization scope, e.g., ``workgroup``5215* Zero or more ``const char *`` address spaces names.5216 5217The address spaces arguments must be one of the following string literals:5218 5219* ``"local"``5220* ``"global"``5221 5222If one or more address space name are provided, the code generator will attempt5223to emit potentially faster instructions that order access to at least those5224address spaces.5225Emitting such instructions may not always be possible and the compiler is free5226to fence more aggressively.5227 5228If no address spaces names are provided, all address spaces are fenced.5229 5230.. code-block:: c++5231 5232  // Fence all address spaces.5233  __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup");5234  __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");5235 5236  // Fence only requested address spaces.5237  __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local")5238  __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local", "global")5239 5240__builtin_amdgcn_ballot_w{32,64}5241^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^5242 5243``__builtin_amdgcn_ballot_w{32,64}`` returns a bitmask that contains its5244boolean argument as a bit for every lane of the current wave that is currently5245active (i.e., that is converged with the executing thread), and a 0 bit for5246every lane that is not active.5247 5248The result is uniform, i.e., it is the same in every active thread of the wave.5249 5250__builtin_amdgcn_inverse_ballot_w{32,64}5251^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^5252 5253Given a wave-uniform bitmask, ``__builtin_amdgcn_inverse_ballot_w{32,64}(mask)``5254returns the bit at the position of the current lane. It is almost equivalent to5255``(mask & (1 << lane_id)) != 0``, except that its behavior is only defined if5256the given mask has the same value for all active lanes of the current wave.5257 5258ARM/AArch64 Language Extensions5259-------------------------------5260 5261Memory Barrier Intrinsics5262^^^^^^^^^^^^^^^^^^^^^^^^^5263Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined5264in the `Arm C Language Extensions5265<https://github.com/ARM-software/acle/releases>`_.5266Note that these intrinsics are implemented as motion barriers that block5267reordering of memory accesses and side effect instructions. Other instructions5268like simple arithmetic may be reordered around the intrinsic. If you expect to5269have no reordering at all, use inline assembly instead.5270 5271Pointer Authentication5272^^^^^^^^^^^^^^^^^^^^^^5273See :doc:`PointerAuthentication`.5274 5275X86/X86-64 Language Extensions5276------------------------------5277 5278The X86 backend has these language extensions:5279 5280Memory references to specified segments5281^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^5282 5283Annotating a pointer with address space #256 causes it to be code generated5284relative to the X86 GS segment register, address space #257 causes it to be5285relative to the X86 FS segment, and address space #258 causes it to be5286relative to the X86 SS segment.  Note that this is a very very low-level5287feature that should only be used if you know what you're doing (for example in5288an OS kernel).5289 5290Here is an example:5291 5292.. code-block:: c++5293 5294  #define GS_RELATIVE __attribute__((address_space(256)))5295  int foo(int GS_RELATIVE *P) {5296    return *P;5297  }5298 5299Which compiles to (on X86-32):5300 5301.. code-block:: gas5302 5303  _foo:5304          movl    4(%esp), %eax5305          movl    %gs:(%eax), %eax5306          ret5307 5308You can also use the GCC compatibility macros ``__seg_fs`` and ``__seg_gs`` for5309the same purpose. The preprocessor symbols ``__SEG_FS`` and ``__SEG_GS``5310indicate their support.5311 5312PowerPC Language Extensions5313---------------------------5314 5315Set the Floating Point Rounding Mode5316^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^5317PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set5318the floating point rounding mode. This function will use the least significant5319two bits of integer argument to set the floating point rounding mode.5320 5321.. code-block:: c++5322 5323  double __builtin_setrnd(int mode);5324 5325The effective values for mode are:5326 5327    - 0 - round to nearest5328    - 1 - round to zero5329    - 2 - round to +infinity5330    - 3 - round to -infinity5331 5332Note that the mode argument will modulo 4, so if the integer argument is greater5333than 3, it will only use the least significant two bits of the mode.5334Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``.5335 5336PowerPC cache builtins5337^^^^^^^^^^^^^^^^^^^^^^5338 5339The PowerPC architecture specifies instructions implementing cache operations.5340Clang provides builtins that give direct programmer access to these cache5341instructions.5342 5343Currently the following builtins are implemented in clang:5344 5345``__builtin_dcbf`` copies the contents of a modified block from the data cache5346to main memory and flushes the copy from the data cache.5347 5348**Syntax**:5349 5350.. code-block:: c5351 5352  void __dcbf(const void* addr); /* Data Cache Block Flush */5353 5354**Example of Use**:5355 5356.. code-block:: c5357 5358  int a = 1;5359  __builtin_dcbf (&a);5360 5361Extensions for Static Analysis5362==============================5363 5364Clang supports additional attributes that are useful for documenting program5365invariants and rules for static analysis tools, such as the `Clang Static5366Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented5367in the analyzer's `list of annotations for analysis5368<analyzer/user-docs/Annotations.html>`__.5369 5370 5371Extensions for Dynamic Analysis5372===============================5373 5374Use ``__has_feature(address_sanitizer)`` to check if the code is being built5375with :doc:`AddressSanitizer`.5376 5377Use ``__has_feature(thread_sanitizer)`` to check if the code is being built5378with :doc:`ThreadSanitizer`.5379 5380Use ``__has_feature(memory_sanitizer)`` to check if the code is being built5381with :doc:`MemorySanitizer`.5382 5383Use ``__has_feature(dataflow_sanitizer)`` to check if the code is being built5384with :doc:`DataFlowSanitizer`.5385 5386Use ``__has_feature(safe_stack)`` to check if the code is being built5387with :doc:`SafeStack`.5388 5389 5390Extensions for selectively disabling optimization5391=================================================5392 5393Clang provides a mechanism for selectively disabling optimizations in functions5394and methods.5395 5396To disable optimizations in a single function definition, the GNU-style or C++115397non-standard attribute ``optnone`` can be used.5398 5399.. code-block:: c++5400 5401  // The following functions will not be optimized.5402  // GNU-style attribute5403  __attribute__((optnone)) int foo() {5404    // ... code5405  }5406  // C++11 attribute5407  [[clang::optnone]] int bar() {5408    // ... code5409  }5410 5411To facilitate disabling optimization for a range of function definitions, a5412range-based pragma is provided. Its syntax is ``#pragma clang optimize``5413followed by ``off`` or ``on``.5414 5415All function definitions in the region between an ``off`` and the following5416``on`` will be decorated with the ``optnone`` attribute unless doing so would5417conflict with explicit attributes already present on the function (e.g., the5418ones that control inlining).5419 5420.. code-block:: c++5421 5422  #pragma clang optimize off5423  // This function will be decorated with optnone.5424  int foo() {5425    // ... code5426  }5427 5428  // optnone conflicts with always_inline, so bar() will not be decorated.5429  __attribute__((always_inline)) int bar() {5430    // ... code5431  }5432  #pragma clang optimize on5433 5434If no ``on`` is found to close an ``off`` region, the end of the region is the5435end of the compilation unit.5436 5437Note that a stray ``#pragma clang optimize on`` does not selectively enable5438additional optimizations when compiling at low optimization levels. This feature5439can only be used to selectively disable optimizations.5440 5441The pragma has an effect on functions only at the point of their definition; for5442function templates, this means that the state of the pragma at the point of an5443instantiation is not necessarily relevant. Consider the following example:5444 5445.. code-block:: c++5446 5447  template<typename T> T twice(T t) {5448    return 2 * t;5449  }5450 5451  #pragma clang optimize off5452  template<typename T> T thrice(T t) {5453    return 3 * t;5454  }5455 5456  int container(int a, int b) {5457    return twice(a) + thrice(b);5458  }5459  #pragma clang optimize on5460 5461In this example, the definition of the template function ``twice`` is outside5462the pragma region, whereas the definition of ``thrice`` is inside the region.5463The ``container`` function is also in the region and will not be optimized, but5464it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of5465these two instantiations, ``twice`` will be optimized (because its definition5466was outside the region) and ``thrice`` will not be optimized.5467 5468Clang also implements MSVC's range-based pragma,5469``#pragma optimize("[optimization-list]", on | off)``. At the moment, Clang only5470supports an empty optimization list, whereas MSVC supports the arguments, ``s``,5471``g``, ``t``, and ``y``. Currently, the implementation of ``pragma optimize`` behaves5472the same as ``#pragma clang optimize``. All functions5473between ``off`` and ``on`` will be decorated with the ``optnone`` attribute.5474 5475.. code-block:: c++5476 5477  #pragma optimize("", off)5478  // This function will be decorated with optnone.5479  void f1() {}5480 5481  #pragma optimize("", on)5482  // This function will be optimized with whatever was specified on5483  // the commandline.5484  void f2() {}5485 5486  // This will warn with Clang's current implementation.5487  #pragma optimize("g", on)5488  void f3() {}5489 5490For MSVC, an empty optimization list and ``off`` parameter will turn off5491all optimizations, ``s``, ``g``, ``t``, and ``y``. An empty optimization and5492``on`` parameter will reset the optimizations to the ones specified on the5493commandline.5494 5495.. list-table:: Parameters (unsupported by Clang)5496 5497   * - Parameter5498     - Type of optimization5499   * - g5500     - Deprecated5501   * - s or t5502     - Short or fast sequences of machine code5503   * - y5504     - Enable frame pointers5505 5506Extensions for loop hint optimizations5507======================================5508 5509The ``#pragma clang loop`` directive is used to specify hints for optimizing the5510subsequent for, while, do-while, or c++11 range-based for loop. The directive5511provides options for vectorization, interleaving, predication, unrolling and5512distribution. Loop hints can be specified before any loop and will be ignored if5513the optimization is not safe to apply.5514 5515There are loop hints that control transformations (e.g., vectorization, loop5516unrolling) and there are loop hints that set transformation options (e.g.5517``vectorize_width``, ``unroll_count``).  Pragmas setting transformation options5518imply the transformation is enabled, as if it were enabled via the corresponding5519transformation pragma (e.g., ``vectorize(enable)``). If the transformation is5520disabled  (e.g., ``vectorize(disable)``), that takes precedence over5521transformations option pragmas implying that transformation.5522 5523Vectorization, Interleaving, and Predication5524--------------------------------------------5525 5526A vectorized loop performs multiple iterations of the original loop5527in parallel using vector instructions. The instruction set of the target5528processor determines which vector instructions are available and their vector5529widths. This restricts the types of loops that can be vectorized. The vectorizer5530automatically determines if the loop is safe and profitable to vectorize. A5531vector instruction cost model is used to select the vector width.5532 5533Interleaving multiple loop iterations allows modern processors to further5534improve instruction-level parallelism (ILP) using advanced hardware features,5535such as multiple execution units and out-of-order execution. The vectorizer uses5536a cost model that depends on the register pressure and generated code size to5537select the interleaving count.5538 5539Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled5540by ``interleave(enable)``. This is useful when compiling with ``-Os`` to5541manually enable vectorization or interleaving.5542 5543.. code-block:: c++5544 5545  #pragma clang loop vectorize(enable)5546  #pragma clang loop interleave(enable)5547  for(...) {5548    ...5549  }5550 5551The vector width is specified by5552``vectorize_width(_value_[, fixed|scalable])``, where _value_ is a positive5553integer and the type of vectorization can be specified with an optional5554second parameter. The default for the second parameter is 'fixed' and5555refers to fixed width vectorization, whereas 'scalable' indicates the5556compiler should use scalable vectors instead. Another use of vectorize_width5557is ``vectorize_width(fixed|scalable)`` where the user can hint at the type5558of vectorization to use without specifying the exact width. In both variants5559of the pragma the vectorizer may decide to fall back on fixed width5560vectorization if the target does not support scalable vectors.5561 5562The interleave count is specified by ``interleave_count(_value_)``, where5563_value_ is a positive integer. This is useful for specifying the optimal5564width/count of the set of target architectures supported by your application.5565 5566.. code-block:: c++5567 5568  #pragma clang loop vectorize_width(2)5569  #pragma clang loop interleave_count(2)5570  for(...) {5571    ...5572  }5573 5574Specifying a width/count of 1 disables the optimization, and is equivalent to5575``vectorize(disable)`` or ``interleave(disable)``.5576 5577Vector predication is enabled by ``vectorize_predicate(enable)``, for example:5578 5579.. code-block:: c++5580 5581  #pragma clang loop vectorize(enable)5582  #pragma clang loop vectorize_predicate(enable)5583  for(...) {5584    ...5585  }5586 5587This predicates (masks) all instructions in the loop, which allows the scalar5588remainder loop (the tail) to be folded into the main vectorized loop. This5589might be more efficient when vector predication is efficiently supported by the5590target platform.5591 5592Loop Unrolling5593--------------5594 5595Unrolling a loop reduces the loop control overhead and exposes more5596opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling5597eliminates the loop and replaces it with an enumerated sequence of loop5598iterations. Full unrolling is only possible if the loop trip count is known at5599compile time. Partial unrolling replicates the loop body within the loop and5600reduces the trip count.5601 5602If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the5603loop if the trip count is known at compile time. If the fully unrolled code size5604is greater than an internal limit the loop will be partially unrolled up to this5605limit. If the trip count is not known at compile time the loop will be partially5606unrolled with a heuristically chosen unroll factor.5607 5608.. code-block:: c++5609 5610  #pragma clang loop unroll(enable)5611  for(...) {5612    ...5613  }5614 5615If ``unroll(full)`` is specified the unroller will attempt to fully unroll the5616loop if the trip count is known at compile time identically to5617``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled5618if the loop count is not known at compile time.5619 5620.. code-block:: c++5621 5622  #pragma clang loop unroll(full)5623  for(...) {5624    ...5625  }5626 5627The unroll count can be specified explicitly with ``unroll_count(_value_)`` where5628_value_ is a positive integer. If this value is greater than the trip count the5629loop will be fully unrolled. Otherwise the loop is partially unrolled subject5630to the same code size limit as with ``unroll(enable)``.5631 5632.. code-block:: c++5633 5634  #pragma clang loop unroll_count(8)5635  for(...) {5636    ...5637  }5638 5639Unrolling of a loop can be prevented by specifying ``unroll(disable)``.5640 5641Loop unroll parameters can be controlled by options5642`-mllvm -unroll-count=n` and `-mllvm -pragma-unroll-threshold=n`.5643 5644Loop Distribution5645-----------------5646 5647Loop Distribution allows splitting a loop into multiple loops.  This is5648beneficial for example when the entire loop cannot be vectorized but some of the5649resulting loops can.5650 5651If ``distribute(enable))`` is specified and the loop has memory dependencies5652that inhibit vectorization, the compiler will attempt to isolate the offending5653operations into a new loop.  This optimization is not enabled by default, only5654loops marked with the pragma are considered.5655 5656.. code-block:: c++5657 5658  #pragma clang loop distribute(enable)5659  for (i = 0; i < N; ++i) {5660    S1: A[i + 1] = A[i] + B[i];5661    S2: C[i] = D[i] * E[i];5662  }5663 5664This loop will be split into two loops between statements S1 and S2.  The5665second loop containing S2 will be vectorized.5666 5667Loop Distribution is currently not enabled by default in the optimizer because5668it can hurt performance in some cases.  For example, instruction-level5669parallelism could be reduced by sequentializing the execution of the5670statements S1 and S2 above.5671 5672If Loop Distribution is turned on globally with5673``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can5674be used the disable it on a per-loop basis.5675 5676Additional Information5677----------------------5678 5679For convenience multiple loop hints can be specified on a single line.5680 5681.. code-block:: c++5682 5683  #pragma clang loop vectorize_width(4) interleave_count(8)5684  for(...) {5685    ...5686  }5687 5688If an optimization cannot be applied any hints that apply to it will be ignored.5689For example, the hint ``vectorize_width(4)`` is ignored if the loop is not5690proven safe to vectorize. To identify and diagnose optimization issues use5691`-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the5692user guide for details.5693 5694Extensions to specify floating-point flags5695====================================================5696 5697The ``#pragma clang fp`` pragma allows floating-point options to be specified5698for a section of the source code. This pragma can only appear at file scope or5699at the start of a compound statement (excluding comments). When using within a5700compound statement, the pragma is active within the scope of the compound5701statement.5702 5703Currently, the following settings can be controlled with this pragma:5704 5705``#pragma clang fp reassociate`` allows control over the reassociation5706of floating point expressions. When enabled, this pragma allows the expression5707``x + (y + z)`` to be reassociated as ``(x + y) + z``.5708Reassociation can also occur across multiple statements.5709This pragma can be used to disable reassociation when it is otherwise5710enabled for the translation unit with the ``-fassociative-math`` flag.5711The pragma can take two values: ``on`` and ``off``.5712 5713.. code-block:: c++5714 5715  float f(float x, float y, float z)5716  {5717    // Enable floating point reassociation across statements5718    #pragma clang fp reassociate(on)5719    float t = x + y;5720    float v = t + z;5721  }5722 5723``#pragma clang fp reciprocal`` allows control over using reciprocal5724approximations in floating point expressions. When enabled, this5725pragma allows the expression ``x / y`` to be approximated as ``x *5726(1.0 / y)``.  This pragma can be used to disable reciprocal5727approximation when it is otherwise enabled for the translation unit5728with the ``-freciprocal-math`` flag or other fast-math options. The5729pragma can take two values: ``on`` and ``off``.5730 5731.. code-block:: c++5732 5733  float f(float x, float y)5734  {5735    // Enable floating point reciprocal approximation5736    #pragma clang fp reciprocal(on)5737    return x / y;5738  }5739 5740``#pragma clang fp contract`` specifies whether the compiler should5741contract a multiply and an addition (or subtraction) into a fused FMA5742operation when supported by the target.5743 5744The pragma can take three values: ``on``, ``fast`` and ``off``.  The ``on``5745option is identical to using ``#pragma STDC FP_CONTRACT(ON)`` and it allows5746fusion as specified the language standard.  The ``fast`` option allows fusion5747in cases when the language standard does not make this possible (e.g., across5748statements in C).5749 5750.. code-block:: c++5751 5752  for(...) {5753    #pragma clang fp contract(fast)5754    a = b[i] * c[i];5755    d[i] += a;5756  }5757 5758 5759The pragma can also be used with ``off`` which turns FP contraction off for a5760section of the code. This can be useful when fast contraction is otherwise5761enabled for the translation unit with the ``-ffp-contract=fast-honor-pragmas`` flag.5762Note that ``-ffp-contract=fast`` will override pragmas to fuse multiply and5763addition across statements regardless of any controlling pragmas.5764 5765``#pragma clang fp exceptions`` specifies floating point exception behavior. It5766may take one of the values: ``ignore``, ``maytrap`` or ``strict``. Meaning of5767these values is same as for `constrained floating point intrinsics <http://llvm.org/docs/LangRef.html#constrained-floating-point-intrinsics>`_.5768 5769.. code-block:: c++5770 5771  {5772    // Preserve floating point exceptions5773    #pragma clang fp exceptions(strict)5774    z = x + y;5775    if (fetestexcept(FE_OVERFLOW))5776      ...5777  }5778 5779A ``#pragma clang fp`` pragma may contain any number of options:5780 5781.. code-block:: c++5782 5783  void func(float *dest, float a, float b) {5784    #pragma clang fp exceptions(maytrap) contract(fast) reassociate(on)5785    ...5786  }5787 5788``#pragma clang fp eval_method`` allows floating-point behavior to be specified5789for a section of the source code. This pragma can appear at file or namespace5790scope, or at the start of a compound statement (excluding comments).5791The pragma is active within the scope of the compound statement.5792 5793When ``pragma clang fp eval_method(source)`` is enabled, the section of code5794governed by the pragma behaves as though the command-line option5795``-ffp-eval-method=source`` is enabled. Rounds intermediate results to5796source-defined precision.5797 5798When ``pragma clang fp eval_method(double)`` is enabled, the section of code5799governed by the pragma behaves as though the command-line option5800``-ffp-eval-method=double`` is enabled. Rounds intermediate results to5801``double`` precision.5802 5803When ``pragma clang fp eval_method(extended)`` is enabled, the section of code5804governed by the pragma behaves as though the command-line option5805``-ffp-eval-method=extended`` is enabled. Rounds intermediate results to5806target-dependent ``long double`` precision. In Win32 programming, for instance,5807the long double data type maps to the double, 64-bit precision data type.5808 5809The full syntax this pragma supports is5810``#pragma clang fp eval_method(source|double|extended)``.5811 5812.. code-block:: c++5813 5814  for(...) {5815    // The compiler will use long double as the floating-point evaluation5816    // method.5817    #pragma clang fp eval_method(extended)5818    a = b[i] * c[i] + e;5819  }5820 5821Note: ``math.h`` defines the typedefs ``float_t`` and ``double_t`` based on the active5822evaluation method at the point where the header is included, not where the5823typedefs are used.  Because of this, it is unwise to combine these typedefs with5824``#pragma clang fp eval_method``.  To catch obvious bugs, Clang will emit an5825error for any references to these typedefs within the scope of this pragma;5826however, this is not a fool-proof protection, and programmers must take care.5827 5828The ``#pragma float_control`` pragma allows precise floating-point5829semantics and floating-point exception behavior to be specified5830for a section of the source code. This pragma can only appear at file or5831namespace scope, within a language linkage specification or at the start of a5832compound statement (excluding comments). When used within a compound statement,5833the pragma is active within the scope of the compound statement.  This pragma5834is modeled after a Microsoft pragma with the same spelling and syntax.  For5835pragmas specified at file or namespace scope, or within a language linkage5836specification, a stack is supported so that the ``pragma float_control``5837settings can be pushed or popped.5838 5839When ``pragma float_control(precise, on)`` is enabled, the section of code5840governed by the pragma uses precise floating point semantics, effectively5841``-ffast-math`` is disabled and ``-ffp-contract=on``5842(fused multiply add) is enabled. This pragma enables ``-fmath-errno``.5843 5844When ``pragma float_control(precise, off)`` is enabled, unsafe-floating point5845optimizations are enabled in the section of code governed by the pragma.5846Effectively ``-ffast-math`` is enabled and ``-ffp-contract=fast``. This pragma5847disables ``-fmath-errno``.5848 5849When ``pragma float_control(except, on)`` is enabled, the section of code5850governed by the pragma behaves as though the command-line option5851``-ffp-exception-behavior=strict`` is enabled,5852when ``pragma float_control(except, off)`` is enabled, the section of code5853governed by the pragma behaves as though the command-line option5854``-ffp-exception-behavior=ignore`` is enabled.5855 5856The full syntax this pragma supports is5857``float_control(except|precise, on|off [, push])`` and5858``float_control(push|pop)``.5859The ``push`` and ``pop`` forms, including using ``push`` as the optional5860third argument, can only occur at file scope.5861 5862.. code-block:: c++5863 5864  for(...) {5865    // This block will be compiled with -fno-fast-math and -ffp-contract=on5866    #pragma float_control(precise, on)5867    a = b[i] * c[i] + e;5868  }5869 5870Extensions for controlling atomic code generation5871=================================================5872 5873The ``[[clang::atomic]]`` statement attribute enables users to control how5874atomic operations are lowered in LLVM IR by conveying additional metadata to5875the backend. The primary goal is to allow users to specify certain options,5876like whether the affected atomic operations might be used with specific types of memory or5877whether to ignore denormal mode correctness in floating-point operations,5878without affecting the correctness of code that does not rely on these properties.5879 5880In LLVM, lowering of atomic operations (e.g., ``atomicrmw``) can differ based5881on the target's capabilities. Some backends support native atomic instructions5882only for certain operation types or alignments, or only in specific memory5883regions. Likewise, floating-point atomic instructions may or may not respect5884IEEE denormal requirements. When the user is unconcerned about denormal-mode5885compliance (for performance reasons) or knows that certain atomic operations5886will not be performed on a particular type of memory, extra hints are needed to5887tell the backend how to proceed.5888 5889A classic example is an architecture where floating-point atomic add does not5890fully conform to IEEE denormal-mode handling. If the user does not mind ignoring5891that aspect, they would prefer to emit a faster hardware atomic instruction,5892rather than a fallback or CAS loop. Conversely, on certain GPUs (e.g., AMDGPU),5893memory accessed via PCIe may only support a subset of atomic operations. To ensure5894correct and efficient lowering, the compiler must know whether the user needs5895the atomic operations to work with that type of memory.5896 5897The allowed atomic attribute values are now ``remote_memory``, ``fine_grained_memory``,5898and ``ignore_denormal_mode``, each optionally prefixed with ``no_``. The meanings5899are as follows:5900 5901- ``remote_memory`` means atomic operations may be performed on remote5902  memory, i.e., memory accessed through off-chip interconnects (e.g., PCIe).5903  On ROCm platforms using HIP, remote memory refers to memory accessed via5904  PCIe and is subject to specific atomic operation support. See5905  `ROCm PCIe Atomics <https://rocm.docs.amd.com/en/latest/conceptual/5906  pcie-atomics.html>`_ for further details. Prefixing with ``no_remote_memory`` indicates that5907  atomic operations should not be performed on remote memory.5908- ``fine_grained_memory`` means atomic operations may be performed on fine-grained5909  memory, i.e., memory regions that support fine-grained coherence, where updates to5910  memory are visible to other parts of the system even while modifications are ongoing.5911  For example, in HIP, fine-grained coherence ensures that host and device share5912  up-to-date data without explicit synchronization (see5913  `HIP Definition <https://rocm.docs.amd.com/projects/HIP/en/docs-6.3.3/how-to/hip_runtime_api/memory_management/coherence_control.html#coherence-control>`_).5914  Similarly, OpenCL 2.0 provides fine-grained synchronization in shared virtual memory5915  allocations, allowing concurrent modifications by host and device (see5916  `OpenCL 2.0 Overview <https://www.intel.com/content/www/us/en/developer/articles/technical/opencl-20-shared-virtual-memory-overview.html>`_).5917  Prefixing with ``no_fine_grained_memory`` indicates that atomic operations should not5918  be performed on fine-grained memory.5919- ``ignore_denormal_mode`` means that atomic operations are allowed to ignore5920  correctness for denormal mode in floating-point operations, potentially improving5921  performance on architectures that handle denormals inefficiently. The negated form,5922  if specified as ``no_ignore_denormal_mode``, would enforce strict denormal mode5923  correctness.5924 5925Any unspecified option is inherited from the global defaults, which can be set5926by a compiler flag or the target's built-in defaults.5927 5928Within the same atomic attribute, duplicate and conflicting values are accepted,5929and the last of any conflicting values wins. Multiple atomic attributes are5930allowed for the same compound statement, and the last atomic attribute wins.5931 5932Without any atomic metadata, LLVM IR defaults to conservative settings for5933correctness: atomic operations enforce denormal mode correctness and are assumed5934to potentially use remote and fine-grained memory (i.e., the equivalent of5935``remote_memory``, ``fine_grained_memory``, and ``no_ignore_denormal_mode``).5936 5937The attribute may be applied only to a compound statement and looks like:5938 5939.. code-block:: c++5940 5941   [[clang::atomic(remote_memory, fine_grained_memory, ignore_denormal_mode)]]5942   {5943       // Atomic instructions in this block carry extra metadata reflecting5944       // these user-specified options.5945   }5946 5947A new compiler option now globally sets the defaults for these atomic-lowering5948options. The command-line format has changed to:5949 5950.. code-block:: console5951 5952   $ clang -fatomic-remote-memory -fno-atomic-fine-grained-memory -fatomic-ignore-denormal-mode file.cpp5953 5954Each option has a corresponding flag:5955``-fatomic-remote-memory`` / ``-fno-atomic-remote-memory``,5956``-fatomic-fine-grained-memory`` / ``-fno-atomic-fine-grained-memory``,5957and ``-fatomic-ignore-denormal-mode`` / ``-fno-atomic-ignore-denormal-mode``.5958 5959Code using the ``[[clang::atomic]]`` attribute can then selectively override5960the command-line defaults on a per-block basis. For instance:5961 5962.. code-block:: c++5963 5964   // Suppose the global defaults assume:5965   //   remote_memory, fine_grained_memory, and no_ignore_denormal_mode5966   // (for conservative correctness)5967 5968   void example() {5969       // Locally override the settings: disable remote_memory and enable5970       // fine_grained_memory.5971       [[clang::atomic(no_remote_memory, fine_grained_memory)]]5972       {5973           // In this block:5974           //   - Atomic operations are not performed on remote memory.5975           //   - Atomic operations are performed on fine-grained memory.5976           //   - The setting for denormal mode remains as the global default5977           //     (typically no_ignore_denormal_mode, enforcing strict denormal mode correctness).5978           // ...5979       }5980   }5981 5982Function bodies do not accept statement attributes, so this will not work:5983 5984.. code-block:: c++5985 5986   void func() [[clang::atomic(remote_memory)]] {  // Wrong: applies to function type5987   }5988 5989Use the attribute on a compound statement within the function:5990 5991.. code-block:: c++5992 5993   void func() {5994       [[clang::atomic(remote_memory)]]5995       {5996           // Atomic operations in this block carry the specified metadata.5997       }5998   }5999 6000The ``[[clang::atomic]]`` attribute affects only the code generation of atomic6001instructions within the annotated compound statement. Clang attaches target-specific6002metadata to those atomic instructions in the emitted LLVM IR to guide backend lowering.6003This metadata is fixed at the Clang code generation phase and is not modified by later6004LLVM passes (such as function inlining).6005 6006For example, consider:6007 6008.. code-block:: cpp6009 6010  inline void func() {6011    [[clang::atomic(remote_memory)]]6012    {6013      // Atomic instructions lowered with metadata.6014    }6015  }6016 6017  void foo() {6018    [[clang::atomic(no_remote_memory)]]6019    {6020      func(); // Inlined by LLVM, but the metadata from 'func()' remains unchanged.6021    }6022  }6023 6024Although current usage focuses on AMDGPU, the mechanism is general. Other6025backends can ignore or implement their own responses to these flags if desired.6026If a target does not understand or enforce these hints, the IR remains valid,6027and the resulting program is still correct (although potentially less optimized6028for that user's needs).6029 6030Specifying an attribute for multiple declarations (#pragma clang attribute)6031===========================================================================6032 6033The ``#pragma clang attribute`` directive can be used to apply an attribute to6034multiple declarations. The ``#pragma clang attribute push`` variation of the6035directive pushes a new "scope" of ``#pragma clang attribute`` that attributes6036can be added to. The ``#pragma clang attribute (...)`` variation adds an6037attribute to that scope, and the ``#pragma clang attribute pop`` variation pops6038the scope. You can also use ``#pragma clang attribute push (...)``, which is a6039shorthand for when you want to add one attribute to a new scope. Multiple push6040directives can be nested inside each other.6041 6042The attributes that are used in the ``#pragma clang attribute`` directives6043can be written using the GNU-style syntax:6044 6045.. code-block:: c++6046 6047  #pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function)6048 6049  void function(); // The function now has the annotate("custom") attribute6050 6051  #pragma clang attribute pop6052 6053The attributes can also be written using the C++11 style syntax:6054 6055.. code-block:: c++6056 6057  #pragma clang attribute push ([[noreturn]], apply_to = function)6058 6059  void function(); // The function now has the [[noreturn]] attribute6060 6061  #pragma clang attribute pop6062 6063The ``__declspec`` style syntax is also supported:6064 6065.. code-block:: c++6066 6067  #pragma clang attribute push (__declspec(dllexport), apply_to = function)6068 6069  void function(); // The function now has the __declspec(dllexport) attribute6070 6071  #pragma clang attribute pop6072 6073A single push directive can contain multiple attributes, however,6074only one syntax style can be used within a single directive:6075 6076.. code-block:: c++6077 6078  #pragma clang attribute push ([[noreturn, noinline]], apply_to = function)6079 6080  void function1(); // The function now has the [[noreturn]] and [[noinline]] attributes6081 6082  #pragma clang attribute pop6083 6084  #pragma clang attribute push (__attribute((noreturn, noinline)), apply_to = function)6085 6086  void function2(); // The function now has the __attribute((noreturn)) and __attribute((noinline)) attributes6087 6088  #pragma clang attribute pop6089 6090Because multiple push directives can be nested, if you're writing a macro that6091expands to ``_Pragma("clang attribute")`` it's good hygiene (though not6092required) to add a namespace to your push/pop directives. A pop directive with a6093namespace will pop the innermost push that has that same namespace. This will6094ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note6095that an ``pop`` without a namespace will pop the innermost ``push`` without a6096namespace. ``push``es with a namespace can only be popped by ``pop`` with the6097same namespace. For instance:6098 6099.. code-block:: c++6100 6101   #define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)")6102   #define ASSUME_NORETURN_END   _Pragma("clang attribute AssumeNoreturn.pop")6103 6104   #define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)")6105   #define ASSUME_UNAVAILABLE_END   _Pragma("clang attribute Unavailable.pop")6106 6107 6108   ASSUME_NORETURN_BEGIN6109   ASSUME_UNAVAILABLE_BEGIN6110   void function(); // function has [[noreturn]] and __attribute__((unavailable))6111   ASSUME_NORETURN_END6112   void other_function(); // function has __attribute__((unavailable))6113   ASSUME_UNAVAILABLE_END6114 6115Without the namespaces on the macros, ``other_function`` will be annotated with6116``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like6117a contrived example, but its very possible for this kind of situation to appear6118in real code if the pragmas are spread out across a large file. You can test if6119your version of clang supports namespaces on ``#pragma clang attribute`` with6120``__has_extension(pragma_clang_attribute_namespaces)``.6121 6122Subject Match Rules6123-------------------6124 6125The set of declarations that receive a single attribute from the attribute stack6126depends on the subject match rules that were specified in the pragma. Subject6127match rules are specified after the attribute. The compiler expects an6128identifier that corresponds to the subject set specifier. The ``apply_to``6129specifier is currently the only supported subject set specifier. It allows you6130to specify match rules that form a subset of the attribute's allowed subject6131set, i.e., the compiler doesn't require all of the attribute's subjects. For6132example, an attribute like ``[[nodiscard]]`` whose subject set includes6133``enum``, ``record`` and ``hasType(functionType)``, requires the presence of at6134least one of these rules after ``apply_to``:6135 6136.. code-block:: c++6137 6138  #pragma clang attribute push([[nodiscard]], apply_to = enum)6139 6140  enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]]6141 6142  struct Record1 { }; // The struct will *not* receive [[nodiscard]]6143 6144  #pragma clang attribute pop6145 6146  #pragma clang attribute push([[nodiscard]], apply_to = any(record, enum))6147 6148  enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]]6149 6150  struct Record2 { }; // The struct *will* receive [[nodiscard]]6151 6152  #pragma clang attribute pop6153 6154  // This is an error, since [[nodiscard]] can't be applied to namespaces:6155  #pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace))6156 6157  #pragma clang attribute pop6158 6159Multiple match rules can be specified using the ``any`` match rule, as shown6160in the example above. The ``any`` rule applies attributes to all declarations6161that are matched by at least one of the rules in the ``any``. It doesn't nest6162and can't be used inside the other match rules. Redundant match rules or rules6163that conflict with one another should not be used inside of ``any``. Failing to6164specify a rule within the ``any`` rule results in an error.6165 6166Clang supports the following match rules:6167 6168- ``function``: Can be used to apply attributes to functions. This includes C++6169  member functions, static functions, operators, and constructors/destructors.6170 6171- ``function(is_member)``: Can be used to apply attributes to C++ member6172  functions. This includes members like static functions, operators, and6173  constructors/destructors.6174 6175- ``hasType(functionType)``: Can be used to apply attributes to functions, C++6176  member functions, and variables/fields whose type is a function pointer. It6177  does not apply attributes to Objective-C methods or blocks.6178 6179- ``type_alias``: Can be used to apply attributes to ``typedef`` declarations6180  and C++11 type aliases.6181 6182- ``record``: Can be used to apply attributes to ``struct``, ``class``, and6183  ``union`` declarations.6184 6185- ``record(unless(is_union))``: Can be used to apply attributes only to6186  ``struct`` and ``class`` declarations.6187 6188- ``enum``: Can be used to apply attributes to enumeration declarations.6189 6190- ``enum_constant``: Can be used to apply attributes to enumerators.6191 6192- ``variable``: Can be used to apply attributes to variables, including6193  local variables, parameters, global variables, and static member variables.6194  It does not apply attributes to instance member variables or Objective-C6195  ivars.6196 6197- ``variable(is_thread_local)``: Can be used to apply attributes to thread-local6198  variables only.6199 6200- ``variable(is_global)``: Can be used to apply attributes to global variables6201  only.6202 6203- ``variable(is_local)``: Can be used to apply attributes to local variables6204  only.6205 6206- ``variable(is_parameter)``: Can be used to apply attributes to parameters6207  only.6208 6209- ``variable(unless(is_parameter))``: Can be used to apply attributes to all6210  the variables that are not parameters.6211 6212- ``field``: Can be used to apply attributes to non-static member variables6213  in a record. This includes Objective-C ivars.6214 6215- ``namespace``: Can be used to apply attributes to ``namespace`` declarations.6216 6217- ``objc_interface``: Can be used to apply attributes to ``@interface``6218  declarations.6219 6220- ``objc_protocol``: Can be used to apply attributes to ``@protocol``6221  declarations.6222 6223- ``objc_category``: Can be used to apply attributes to category declarations,6224  including class extensions.6225 6226- ``objc_method``: Can be used to apply attributes to Objective-C methods,6227  including instance and class methods. Implicit methods like implicit property6228  getters and setters do not receive the attribute.6229 6230- ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C6231  instance methods.6232 6233- ``objc_property``: Can be used to apply attributes to ``@property``6234  declarations.6235 6236- ``block``: Can be used to apply attributes to block declarations. This does6237  not include variables/fields of block pointer type.6238 6239The use of ``unless`` in match rules is currently restricted to a strict set of6240sub-rules that are used by the supported attributes. That means that even though6241``variable(unless(is_parameter))`` is a valid match rule,6242``variable(unless(is_thread_local))`` is not.6243 6244Supported Attributes6245--------------------6246 6247Not all attributes can be used with the ``#pragma clang attribute`` directive.6248Notably, statement attributes like ``[[fallthrough]]`` or type attributes6249like ``address_space`` aren't supported by this directive. You can determine6250whether or not an attribute is supported by the pragma by referring to the6251:doc:`individual documentation for that attribute <AttributeReference>`.6252 6253The attributes are applied to all matching declarations individually, even when6254the attribute is semantically incorrect. The attributes that aren't applied to6255any declaration are not verified semantically.6256 6257Specifying section names for global objects (#pragma clang section)6258===================================================================6259 6260The ``#pragma clang section`` directive provides a means to assign section-names6261to global variables, functions and static variables.6262 6263The section names can be specified as:6264 6265.. code-block:: c++6266 6267  #pragma clang section bss="myBSS" data="myData" rodata="myRodata" relro="myRelro" text="myText"6268 6269The section names can be reverted back to default name by supplying an empty6270string to the section kind, for example:6271 6272.. code-block:: c++6273 6274  #pragma clang section bss="" data="" text="" rodata="" relro=""6275 6276The ``#pragma clang section`` directive obeys the following rules:6277 6278* The pragma applies to all global variable, statics and function declarations6279  from the pragma to the end of the translation unit.6280 6281* The pragma clang section is enabled automatically, without need of any flags.6282 6283* This feature is only defined to work sensibly for ELF, Mach-O and COFF targets.6284 6285* If section name is specified through _attribute_((section("myname"))), then6286  the attribute name gains precedence.6287 6288* Global variables that are initialized to zero will be placed in the named6289  bss section, if one is present.6290 6291* The ``#pragma clang section`` directive does not try to infer section-kind6292  from the name. For example, naming a section "``.bss.mySec``" does NOT mean6293  it will be a bss section name.6294 6295* The decision about which section-kind applies to each global is taken in the back-end.6296  Once the section-kind is known, appropriate section name, as specified by the user using6297  ``#pragma clang section`` directive, is applied to that global.6298 6299Specifying Linker Options on ELF Targets6300========================================6301 6302The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets.6303The second parameter is the library name (without the traditional Unix prefix of6304``lib``).  This allows you to provide an implicit link of dependent libraries.6305 6306Evaluating Object Size6307======================6308 6309Clang supports the builtins ``__builtin_object_size`` and6310``__builtin_dynamic_object_size``. The semantics are compatible with GCC's6311builtins of the same names, but the details are slightly different.6312 6313.. code-block:: c6314 6315  size_t __builtin_[dynamic_]object_size(const void *ptr, int type)6316 6317Returns the number of accessible bytes ``n`` past ``ptr``. The value returned6318depends on ``type``, which is required to be an integer constant between 0 and63193:6320 6321* If ``type & 2 == 0``, the least ``n`` is returned such that accesses to6322  ``(const char*)ptr + n`` and beyond are known to be out of bounds. This is6323  ``(size_t)-1`` if no better bound is known.6324* If ``type & 2 == 2``, the greatest ``n`` is returned such that accesses to6325  ``(const char*)ptr + i`` are known to be in bounds, for 0 <= ``i`` < ``n``.6326  This is ``(size_t)0`` if no better bound is known.6327 6328.. code-block:: c6329 6330  char small[10], large[100];6331  bool cond;6332  // Returns 100: writes of more than 100 bytes are known to be out of bounds.6333  int n100 = __builtin_object_size(cond ? small : large, 0);6334  // Returns 10: writes of 10 or fewer bytes are known to be in bounds.6335  int n10 = __builtin_object_size(cond ? small : large, 2);6336 6337* If ``type & 1 == 0``, pointers are considered to be in bounds if they point6338  into the same storage as ``ptr`` -- that is, the same stack object, global6339  variable, or heap allocation.6340* If ``type & 1 == 1``, pointers are considered to be in bounds if they point6341  to the same subobject that ``ptr`` points to. If ``ptr`` points to an array6342  element, other elements of the same array, but not of enclosing arrays, are6343  considered in bounds.6344 6345.. code-block:: c6346 6347  struct X { char a, b, c; } x;6348  static_assert(__builtin_object_size(&x, 0) == 3);6349  static_assert(__builtin_object_size(&x.b, 0) == 2);6350  static_assert(__builtin_object_size(&x.b, 1) == 1);6351 6352.. code-block:: c6353 6354  char a[10][10][10];6355  static_assert(__builtin_object_size(&a, 1) == 1000);6356  static_assert(__builtin_object_size(&a[1], 1) == 900);6357  static_assert(__builtin_object_size(&a[1][1], 1) == 90);6358  static_assert(__builtin_object_size(&a[1][1][1], 1) == 9);6359 6360The values returned by this builtin are a best effort conservative approximation6361of the correct answers. When ``type & 2 == 0``, the true value is less than or6362equal to the value returned by the builtin, and when ``type & 2 == 1``, the true6363value is greater than or equal to the value returned by the builtin.6364 6365For ``__builtin_object_size``, the value is determined entirely at compile time.6366With optimization enabled, better results will be produced, especially when the6367call to ``__builtin_object_size`` is in a different function from the formation6368of the pointer. Unlike in GCC, enabling optimization in Clang does not allow6369more information about subobjects to be determined, so the ``type & 1 == 1``6370case will often give imprecise results when used across a function call boundary6371even when optimization is enabled.6372 6373`The pass_object_size and pass_dynamic_object_size attributes <https://clang.llvm.org/docs/AttributeReference.html#pass-object-size-pass-dynamic-object-size>`_6374can be used to invisibly pass the object size for a pointer parameter alongside6375the pointer in a function call. This allows more precise object sizes to be6376determined both when building without optimizations and in the ``type & 1 == 1``6377case.6378 6379For ``__builtin_dynamic_object_size``, the result is not limited to being a6380compile time constant. Instead, a small amount of runtime evaluation is6381permitted to determine the size of the object, in order to give a more precise6382result. ``__builtin_dynamic_object_size`` is meant to be used as a drop-in6383replacement for ``__builtin_object_size`` in libraries that support it. For6384instance, here is a program that ``__builtin_dynamic_object_size`` will make6385safer:6386 6387.. code-block:: c6388 6389  void copy_into_buffer(size_t size) {6390    char* buffer = malloc(size);6391    strlcpy(buffer, "some string", strlen("some string"));6392    // Previous line preprocesses to:6393    // __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buffer, 0))6394  }6395 6396Since the size of ``buffer`` can't be known at compile time, Clang will fold6397``__builtin_object_size(buffer, 0)`` into ``-1``. However, if this was written6398as ``__builtin_dynamic_object_size(buffer, 0)``, Clang will fold it into6399``size``, providing some extra runtime safety.6400 6401Deprecating Macros6402==================6403 6404Clang supports the pragma ``#pragma clang deprecated``, which can be used to6405provide deprecation warnings for macro uses. For example:6406 6407.. code-block:: c6408 6409   #define MIN(x, y) x < y ? x : y6410   #pragma clang deprecated(MIN, "use std::min instead")6411 6412   int min(int a, int b) {6413     return MIN(a, b); // warning: MIN is deprecated: use std::min instead6414   }6415 6416``#pragma clang deprecated`` should be preferred for this purpose over6417``#pragma GCC warning`` because the warning can be controlled with6418``-Wdeprecated``.6419 6420Restricted Expansion Macros6421===========================6422 6423Clang supports the pragma ``#pragma clang restrict_expansion``, which can be6424used restrict macro expansion in headers. This can be valuable when providing6425headers with ABI stability requirements. Any expansion of the annotated macro6426processed by the preprocessor after the ``#pragma`` annotation will log a6427warning. Redefining the macro or undefining the macro will not be diagnosed, nor6428will expansion of the macro within the main source file. For example:6429 6430.. code-block:: c6431 6432   #define TARGET_ARM 16433   #pragma clang restrict_expansion(TARGET_ARM, "<reason>")6434 6435   /// Foo.h6436   struct Foo {6437   #if TARGET_ARM // warning: TARGET_ARM is marked unsafe in headers: <reason>6438     uint32_t X;6439   #else6440     uint64_t X;6441   #endif6442   };6443 6444   /// main.c6445   #include "foo.h"6446   #if TARGET_ARM // No warning in main source file6447   X_TYPE uint32_t6448   #else6449   X_TYPE uint64_t6450   #endif6451 6452This warning is controlled by ``-Wpedantic-macros``.6453 6454Final Macros6455============6456 6457Clang supports the pragma ``#pragma clang final``, which can be used to6458mark macros as final, meaning they cannot be undef'd or re-defined. For example:6459 6460.. code-block:: c6461 6462   #define FINAL_MACRO 16463   #pragma clang final(FINAL_MACRO)6464 6465   #define FINAL_MACRO // warning: FINAL_MACRO is marked final and should not be redefined6466   #undef FINAL_MACRO  // warning: FINAL_MACRO is marked final and should not be undefined6467 6468This is useful for enforcing system-provided macros that should not be altered6469in user headers or code. This is controlled by ``-Wpedantic-macros``. Final6470macros will always warn on redefinition, including situations with identical6471bodies and in system headers.6472 6473Line Control6474============6475 6476Clang supports an extension for source line control, which takes the6477form of a preprocessor directive starting with an unsigned integral6478constant. In addition to the standard ``#line`` directive, this form6479allows control of an include stack and header file type, which is used6480in issuing diagnostics. These lines are emitted in preprocessed6481output.6482 6483.. code-block:: c6484 6485   # <line:number> <filename:string> <header-type:numbers>6486 6487The filename is optional, and if unspecified indicates no change in6488source filename. The header-type is an optional, whitespace-delimited,6489sequence of magic numbers as follows.6490 6491* ``1:`` Push the current source file name onto the include stack and6492  enter a new file.6493 6494* ``2``: Pop the include stack and return to the specified file. If6495  the filename is ``""``, the name popped from the include stack is6496  used. Otherwise there is no requirement that the specified filename6497  matches the current source when originally pushed.6498 6499* ``3``: Enter a system-header region. System headers often contain6500  implementation-specific source that would normally emit a diagnostic.6501 6502* ``4``: Enter an implicit ``extern "C"`` region. This is not required on6503  modern systems where system headers are C++-aware.6504 6505At most a single ``1`` or ``2`` can be present, and values must be in6506ascending order.6507 6508Examples are:6509 6510.. code-block:: c6511 6512   # 57 // Advance (or return) to line 57 of the current source file6513   # 57 "frob" // Set to line 57 of "frob"6514   # 1 "foo.h" 1 // Enter "foo.h" at line 16515   # 59 "main.c" 2 // Leave current include and return to "main.c"6516   # 1 "/usr/include/stdio.h" 1 3 // Enter a system header6517   # 60 "" 2 // return to "main.c"6518   # 1 "/usr/ancient/header.h" 1 4 // Enter an implicit extern "C" header6519 6520Intrinsics Support within Constant Expressions6521==============================================6522 6523The following builtin intrinsics can be used in constant expressions:6524 6525* ``__builtin_addcb``6526* ``__builtin_addcs``6527* ``__builtin_addc``6528* ``__builtin_addcl``6529* ``__builtin_addcll``6530* ``__builtin_bitreverse8``6531* ``__builtin_bitreverse16``6532* ``__builtin_bitreverse32``6533* ``__builtin_bitreverse64``6534* ``__builtin_bswap16``6535* ``__builtin_bswap32``6536* ``__builtin_bswap64``6537* ``__builtin_clrsb``6538* ``__builtin_clrsbl``6539* ``__builtin_clrsbll``6540* ``__builtin_clz``6541* ``__builtin_clzl``6542* ``__builtin_clzll``6543* ``__builtin_clzs``6544* ``__builtin_clzg``6545* ``__builtin_ctz``6546* ``__builtin_ctzl``6547* ``__builtin_ctzll``6548* ``__builtin_ctzs``6549* ``__builtin_ctzg``6550* ``__builtin_ffs``6551* ``__builtin_ffsl``6552* ``__builtin_ffsll``6553* ``__builtin_fmax``6554* ``__builtin_fmin``6555* ``__builtin_fpclassify``6556* ``__builtin_inf``6557* ``__builtin_isinf``6558* ``__builtin_isinf_sign``6559* ``__builtin_isfinite``6560* ``__builtin_isnan``6561* ``__builtin_isnormal``6562* ``__builtin_nan``6563* ``__builtin_nans``6564* ``__builtin_parity``6565* ``__builtin_parityl``6566* ``__builtin_parityll``6567* ``__builtin_popcount``6568* ``__builtin_popcountl``6569* ``__builtin_popcountll``6570* ``__builtin_popcountg``6571* ``__builtin_rotateleft8``6572* ``__builtin_rotateleft16``6573* ``__builtin_rotateleft32``6574* ``__builtin_rotateleft64``6575* ``__builtin_rotateright8``6576* ``__builtin_rotateright16``6577* ``__builtin_rotateright32``6578* ``__builtin_rotateright64``6579* ``__builtin_subcb``6580* ``__builtin_subcs``6581* ``__builtin_subc``6582* ``__builtin_subcl``6583* ``__builtin_subcll``6584 6585The following x86-specific intrinsics can be used in constant expressions:6586 6587* ``_addcarry_u32``6588* ``_addcarry_u64``6589* ``_bit_scan_forward``6590* ``_bit_scan_reverse``6591* ``__bsfd``6592* ``__bsfq``6593* ``__bsrd``6594* ``__bsrq``6595* ``__bswap``6596* ``__bswapd``6597* ``__bswap64``6598* ``__bswapq``6599* ``_castf32_u32``6600* ``_castf64_u64``6601* ``_castu32_f32``6602* ``_castu64_f64``6603* ``__lzcnt16``6604* ``__lzcnt``6605* ``__lzcnt64``6606* ``_mm_popcnt_u32``6607* ``_mm_popcnt_u64``6608* ``_popcnt32``6609* ``_popcnt64``6610* ``__popcntd``6611* ``__popcntq``6612* ``__popcnt16``6613* ``__popcnt``6614* ``__popcnt64``6615* ``__rolb``6616* ``__rolw``6617* ``__rold``6618* ``__rolq``6619* ``__rorb``6620* ``__rorw``6621* ``__rord``6622* ``__rorq``6623* ``_rotl``6624* ``_rotr``6625* ``_rotwl``6626* ``_rotwr``6627* ``_lrotl``6628* ``_lrotr``6629* ``_subborrow_u32``6630* ``_subborrow_u64``6631 6632Debugging the Compiler6633======================6634 6635Clang supports a number of pragma directives that help debugging the compiler itself.6636Syntax is the following: `#pragma clang __debug <command> <arguments>`.6637Note, all of debugging pragmas are subject to change.6638 6639`dump`6640------6641Accepts either a single identifier or an expression. When a single identifier is passed,6642the lookup results for the identifier are printed to `stderr`. When an expression is passed,6643the AST for the expression is printed to `stderr`. The expression is an unevaluated operand,6644so things like overload resolution and template instantiations are performed,6645but the expression has no runtime effects.6646Type- and value-dependent expressions are not supported yet.6647 6648This facility is designed to aid with testing name lookup machinery.6649 6650Predefined Macros6651=================6652 6653`__GCC_DESTRUCTIVE_SIZE` and `__GCC_CONSTRUCTIVE_SIZE`6654------------------------------------------------------6655Specify the mimum offset between two objects to avoid false sharing and the6656maximum size of contiguous memory to promote true sharing, respectively. These6657macros are predefined in all C and C++ language modes, but can be redefined on6658the command line with ``-D`` to specify different values as needed or can be6659undefined on the command line with ``-U`` to disable support for the feature.6660 6661**Note: the values the macros expand to are not guaranteed to be stable. They6662are are affected by architectures and CPU tuning flags, can change between6663releases of Clang and will not match the values defined by other compilers such6664as GCC.**6665 6666Compiling different TUs depending on these flags (including use of6667``std::hardware_constructive_interference`` or6668``std::hardware_destructive_interference``)  with different compilers, macro6669definitions, or architecture flags will lead to ODR violations and should be6670avoided.6671 6672``#embed`` Parameters6673=====================6674 6675``clang::offset``6676-----------------6677The ``clang::offset`` embed parameter may appear zero or one time in the6678embed parameter sequence. Its preprocessor argument clause shall be present and6679have the form:6680 6681..code-block: text6682 6683  ( constant-expression )6684 6685and shall be an integer constant expression. The integer constant expression6686shall not evaluate to a value less than 0. The token ``defined`` shall not6687appear within the constant expression.6688 6689The offset will be used when reading the contents of the embedded resource to6690specify the starting offset to begin embedding from. The resources is treated6691as being empty if the specified offset is larger than the number of bytes in6692the resource. The offset will be applied *before* any ``limit`` parameters are6693applied.6694 6695Union and aggregate initialization in C6696=======================================6697 6698In C23 (N2900), when an object is initialized from initializer ``= {}``, all6699elements of arrays, all members of structs, and the first members of unions are6700empty-initialized recursively. In addition, all padding bits are initialized to6701zero.6702 6703Clang guarantees the following behaviors:6704 6705* ``1:`` Clang supports initializer ``= {}`` mentioned above in all C6706  standards.6707 6708* ``2:`` When unions are initialized from initializer ``= {}``, bytes outside6709  of the first members of unions are also initialized to zero.6710 6711* ``3:`` When unions, structures and arrays are initialized from initializer6712  ``= { initializer-list }``, all members not explicitly initialized in6713  the initializer list are empty-initialized recursively. In addition, all6714  padding bits are initialized to zero.6715 6716Currently, the above extension only applies to C source code, not C++.6717 6718 6719Empty Objects in C6720==================6721The declaration of a structure or union type which has no named members is6722undefined behavior (C23 and earlier) or implementation-defined behavior (C2y).6723Clang allows the declaration of a structure or union type with no named members6724in all C language modes. `sizeof` for such a type returns `0`, which is6725different behavior than in C++ (where the size of such an object is typically6726`1`).6727 6728 6729Qualified function types in C6730=============================6731Declaring a function with a qualified type in C is undefined behavior (C23 and6732earlier) or implementation-defined behavior (C2y). Clang allows a function type6733to be specified with the ``const`` and ``volatile`` qualifiers, but ignores the6734qualifications.6735 6736.. code-block:: c6737 6738   typedef int f(void);6739   const volatile f func; // Qualifier on function type has no effect.6740 6741 6742Note, Clang does not allow an ``_Atomic`` function type because6743of explicit constraints against atomically qualified (arrays and) function6744types.6745 6746 6747Underspecified Object Declarations in C6748=======================================6749 6750C23 introduced the notion of `underspecified object declarations <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3006.htm>`_6751(note, the final standards text is different from WG14 N3006 due to changes6752during national body comment review). When an object is declared with the6753``constexpr`` storage class specifier or has a deduced type (with the ``auto``6754specifier), it is said to be "underspecified". Underspecified declarations have6755different requirements than non-underspecified declarations. In particular, the6756identifier being declared cannot be used in its initialization. e.g.,6757 6758.. code-block:: c6759 6760  auto x = x; // Invalid6761  constexpr int y = y; // Invalid6762 6763The standard leaves it implementation-defined whether an underspecified6764declaration may introduce additional identifiers as part of the declaration.6765 6766Clang allows additional identifiers to be declared in the following cases:6767 6768* A compound literal may introduce a new type. e.g.,6769 6770.. code-block:: c6771 6772  auto x = (struct S { int x, y; }){ 1, 2 };      // Accepted by Clang6773  constexpr int i = (struct T { int x; }){ 1 }.x; // Accepted by Clang6774 6775* The type specifier for a ``constexpr`` declaration may define a new type.6776  e.g.,6777 6778.. code-block:: c6779 6780  constexpr struct S { int x; } s = { 1 }; // Accepted by Clang6781 6782* A function declarator may be declared with parameters, including parameters6783  which introduce a new type. e.g.,6784 6785.. code-block:: c6786 6787  constexpr int (*fp)(int x) = nullptr;              // Accepted by Clang6788  auto f = (void (*)(struct S { int x; } s))nullptr; // Accepted by Clang6789 6790* The initializer may contain a GNU statement expression which defines new6791  types or objects. e.g.,6792 6793.. code-block:: c6794 6795  constexpr int i = ({                              // Accepted by Clang6796    constexpr int x = 12;6797    constexpr struct S { int x; } s = { x };6798    s.x;6799  });6800  auto x = ({ struct S { int x; } s = { 0 }; s; }); // Accepted by Clang6801 6802Clang intentionally does not implement the changed scoping rules from C236803for underspecified declarations. Doing so would significantly complicate the6804implementation in order to get reasonable diagnostic behavior and also means6805Clang fails to reject some code that should be rejected. e.g.,6806 6807.. code-block:: c6808 6809  // This should be rejected because 'x' is not in scope within the initializer6810  // of an underspecified declaration. Clang accepts because it treats the scope6811  // of the identifier as beginning immediately after the declarator, same as with6812  // a non-underspecified declaration.6813  constexpr int x = sizeof(x);6814 6815  // Clang rejects this code with a diagnostic about using the variable within its6816  // own initializer rather than rejecting the code with an undeclared identifier6817  // diagnostic.6818  auto x = x;6819