1========================= 2Clang Language Extensions 3========================= 4 5.. contents:: 6 :local: 7 :depth: 1 8 9.. toctree:: 10 :hidden: 11 12 ObjectiveCLiterals 13 BlockLanguageSpec 14 Block-ABI-Apple 15 AutomaticReferenceCounting 16 17Introduction 18============ 19 20This document describes the language extensions provided by Clang. In addition 21to the language extensions listed here, Clang aims to support a broad range of 22GCC extensions. Please see the `GCC manual 23<https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on 24these extensions. 25 26.. _langext-feature_check: 27 28Feature Checking Macros 29======================= 30 31Language extensions can be very useful, but only if you know you can depend on 32them. In order to allow fine-grain features checks, we support three builtin 33function-like macros. This allows you to directly test for a feature in your 34code without having to resort to something like autoconf or fragile "compiler 35version checks". 36 37``__has_builtin`` 38----------------- 39 40This function-like macro takes a single identifier argument that is the name of 41a builtin function. It evaluates to 1 if the builtin is supported or 0 if not. 42It can be used like this: 43 44.. code-block:: c++ 45 46 #ifndef __has_builtin // Optional of course. 47 #define __has_builtin(x) 0 // Compatibility with non-clang compilers. 48 #endif 49 50 ... 51 #if __has_builtin(__builtin_trap) 52 __builtin_trap(); 53 #else 54 abort(); 55 #endif 56 ... 57 58.. _langext-__has_feature-__has_extension: 59 60``__has_feature`` and ``__has_extension`` 61----------------------------------------- 62 63These function-like macros take a single identifier argument that is the name 64of a feature. ``__has_feature`` evaluates to 1 if the feature is both 65supported by Clang and standardized in the current language standard or 0 if 66not (but see :ref:`below <langext-has-feature-back-compat>`), while 67``__has_extension`` evaluates to 1 if the feature is supported by Clang in the 68current language (either as a language extension or a standard language 69feature) or 0 if not. They can be used like this: 70 71.. code-block:: c++ 72 73 #ifndef __has_feature // Optional of course. 74 #define __has_feature(x) 0 // Compatibility with non-clang compilers. 75 #endif 76 #ifndef __has_extension 77 #define __has_extension __has_feature // Compatibility with pre-3.0 compilers. 78 #endif 79 80 ... 81 #if __has_feature(cxx_rvalue_references) 82 // This code will only be compiled with the -std=c++11 and -std=gnu++11 83 // options, because rvalue references are only standardized in C++11. 84 #endif 85 86 #if __has_extension(cxx_rvalue_references) 87 // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98 88 // and -std=gnu++98 options, because rvalue references are supported as a 89 // language extension in C++98. 90 #endif 91 92.. _langext-has-feature-back-compat: 93 94For backward compatibility, ``__has_feature`` can also be used to test 95for support for non-standardized features, i.e. features not prefixed ``c_``, 96``cxx_`` or ``objc_``. 97 98Another use of ``__has_feature`` is to check for compiler features not related 99to the language standard, such as e.g. :doc:`AddressSanitizer 100<AddressSanitizer>`. 101 102If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent 103to ``__has_feature``. 104 105The feature tag is described along with the language feature below. 106 107The feature name or extension name can also be specified with a preceding and 108following ``__`` (double underscore) to avoid interference from a macro with 109the same name. For instance, ``__cxx_rvalue_references__`` can be used instead 110of ``cxx_rvalue_references``. 111 112``__has_cpp_attribute`` 113----------------------- 114 115This function-like macro is available in C++2a by default, and is provided as an 116extension in earlier language standards. It takes a single argument that is the 117name of a double-square-bracket-style attribute. The argument can either be a 118single identifier or a scoped identifier. If the attribute is supported, a 119nonzero value is returned. If the attribute is a standards-based attribute, this 120macro returns a nonzero value based on the year and month in which the attribute 121was voted into the working draft. See `WG21 SD-6 122<https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_ 123for the list of values returned for standards-based attributes. If the attribute 124is not supported by the current compliation target, this macro evaluates to 0. 125It can be used like this: 126 127.. code-block:: c++ 128 129 #ifndef __has_cpp_attribute // For backwards compatibility 130 #define __has_cpp_attribute(x) 0 131 #endif 132 133 ... 134 #if __has_cpp_attribute(clang::fallthrough) 135 #define FALLTHROUGH [[clang::fallthrough]] 136 #else 137 #define FALLTHROUGH 138 #endif 139 ... 140 141The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are 142the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either 143of these namespaces can be specified with a preceding and following ``__`` 144(double underscore) to avoid interference from a macro with the same name. For 145instance, ``gnu::__const__`` can be used instead of ``gnu::const``. 146 147``__has_c_attribute`` 148--------------------- 149 150This function-like macro takes a single argument that is the name of an 151attribute exposed with the double square-bracket syntax in C mode. The argument 152can either be a single identifier or a scoped identifier. If the attribute is 153supported, a nonzero value is returned. If the attribute is not supported by the 154current compilation target, this macro evaluates to 0. It can be used like this: 155 156.. code-block:: c 157 158 #ifndef __has_c_attribute // Optional of course. 159 #define __has_c_attribute(x) 0 // Compatibility with non-clang compilers. 160 #endif 161 162 ... 163 #if __has_c_attribute(fallthrough) 164 #define FALLTHROUGH [[fallthrough]] 165 #else 166 #define FALLTHROUGH 167 #endif 168 ... 169 170The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are 171the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either 172of these namespaces can be specified with a preceding and following ``__`` 173(double underscore) to avoid interference from a macro with the same name. For 174instance, ``gnu::__const__`` can be used instead of ``gnu::const``. 175 176``__has_attribute`` 177------------------- 178 179This function-like macro takes a single identifier argument that is the name of 180a GNU-style attribute. It evaluates to 1 if the attribute is supported by the 181current compilation target, or 0 if not. It can be used like this: 182 183.. code-block:: c++ 184 185 #ifndef __has_attribute // Optional of course. 186 #define __has_attribute(x) 0 // Compatibility with non-clang compilers. 187 #endif 188 189 ... 190 #if __has_attribute(always_inline) 191 #define ALWAYS_INLINE __attribute__((always_inline)) 192 #else 193 #define ALWAYS_INLINE 194 #endif 195 ... 196 197The attribute name can also be specified with a preceding and following ``__`` 198(double underscore) to avoid interference from a macro with the same name. For 199instance, ``__always_inline__`` can be used instead of ``always_inline``. 200 201 202``__has_declspec_attribute`` 203---------------------------- 204 205This function-like macro takes a single identifier argument that is the name of 206an attribute implemented as a Microsoft-style ``__declspec`` attribute. It 207evaluates to 1 if the attribute is supported by the current compilation target, 208or 0 if not. It can be used like this: 209 210.. code-block:: c++ 211 212 #ifndef __has_declspec_attribute // Optional of course. 213 #define __has_declspec_attribute(x) 0 // Compatibility with non-clang compilers. 214 #endif 215 216 ... 217 #if __has_declspec_attribute(dllexport) 218 #define DLLEXPORT __declspec(dllexport) 219 #else 220 #define DLLEXPORT 221 #endif 222 ... 223 224The attribute name can also be specified with a preceding and following ``__`` 225(double underscore) to avoid interference from a macro with the same name. For 226instance, ``__dllexport__`` can be used instead of ``dllexport``. 227 228``__is_identifier`` 229------------------- 230 231This function-like macro takes a single identifier argument that might be either 232a reserved word or a regular identifier. It evaluates to 1 if the argument is just 233a regular identifier and not a reserved word, in the sense that it can then be 234used as the name of a user-defined function or variable. Otherwise it evaluates 235to 0. It can be used like this: 236 237.. code-block:: c++ 238 239 ... 240 #ifdef __is_identifier // Compatibility with non-clang compilers. 241 #if __is_identifier(__wchar_t) 242 typedef wchar_t __wchar_t; 243 #endif 244 #endif 245 246 __wchar_t WideCharacter; 247 ... 248 249Include File Checking Macros 250============================ 251 252Not all developments systems have the same include files. The 253:ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow 254you to check for the existence of an include file before doing a possibly 255failing ``#include`` directive. Include file checking macros must be used 256as expressions in ``#if`` or ``#elif`` preprocessing directives. 257 258.. _langext-__has_include: 259 260``__has_include`` 261----------------- 262 263This function-like macro takes a single file name string argument that is the 264name of an include file. It evaluates to 1 if the file can be found using the 265include paths, or 0 otherwise: 266 267.. code-block:: c++ 268 269 // Note the two possible file name string formats. 270 #if __has_include("myinclude.h") && __has_include(<stdint.h>) 271 # include "myinclude.h" 272 #endif 273 274To test for this feature, use ``#if defined(__has_include)``: 275 276.. code-block:: c++ 277 278 // To avoid problem with non-clang compilers not having this macro. 279 #if defined(__has_include) 280 #if __has_include("myinclude.h") 281 # include "myinclude.h" 282 #endif 283 #endif 284 285.. _langext-__has_include_next: 286 287``__has_include_next`` 288---------------------- 289 290This function-like macro takes a single file name string argument that is the 291name of an include file. It is like ``__has_include`` except that it looks for 292the second instance of the given file found in the include paths. It evaluates 293to 1 if the second instance of the file can be found using the include paths, 294or 0 otherwise: 295 296.. code-block:: c++ 297 298 // Note the two possible file name string formats. 299 #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>) 300 # include_next "myinclude.h" 301 #endif 302 303 // To avoid problem with non-clang compilers not having this macro. 304 #if defined(__has_include_next) 305 #if __has_include_next("myinclude.h") 306 # include_next "myinclude.h" 307 #endif 308 #endif 309 310Note that ``__has_include_next``, like the GNU extension ``#include_next`` 311directive, is intended for use in headers only, and will issue a warning if 312used in the top-level compilation file. A warning will also be issued if an 313absolute path is used in the file argument. 314 315``__has_warning`` 316----------------- 317 318This function-like macro takes a string literal that represents a command line 319option for a warning and returns true if that is a valid warning option. 320 321.. code-block:: c++ 322 323 #if __has_warning("-Wformat") 324 ... 325 #endif 326 327Builtin Macros 328============== 329 330``__BASE_FILE__`` 331 Defined to a string that contains the name of the main input file passed to 332 Clang. 333 334``__FILE_NAME__`` 335 Clang-specific extension that functions similar to ``__FILE__`` but only 336 renders the last path component (the filename) instead of an invocation 337 dependent full path to that file. 338 339``__COUNTER__`` 340 Defined to an integer value that starts at zero and is incremented each time 341 the ``__COUNTER__`` macro is expanded. 342 343``__INCLUDE_LEVEL__`` 344 Defined to an integral value that is the include depth of the file currently 345 being translated. For the main file, this value is zero. 346 347``__TIMESTAMP__`` 348 Defined to the date and time of the last modification of the current source 349 file. 350 351``__clang__`` 352 Defined when compiling with Clang 353 354``__clang_major__`` 355 Defined to the major marketing version number of Clang (e.g., the 2 in 356 2.0.1). Note that marketing version numbers should not be used to check for 357 language features, as different vendors use different numbering schemes. 358 Instead, use the :ref:`langext-feature_check`. 359 360``__clang_minor__`` 361 Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note 362 that marketing version numbers should not be used to check for language 363 features, as different vendors use different numbering schemes. Instead, use 364 the :ref:`langext-feature_check`. 365 366``__clang_patchlevel__`` 367 Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1). 368 369``__clang_version__`` 370 Defined to a string that captures the Clang marketing version, including the 371 Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``". 372 373.. _langext-vectors: 374 375Vectors and Extended Vectors 376============================ 377 378Supports the GCC, OpenCL, AltiVec and NEON vector extensions. 379 380OpenCL vector types are created using ``ext_vector_type`` attribute. It 381support for ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example 382is: 383 384.. code-block:: c++ 385 386 typedef float float4 __attribute__((ext_vector_type(4))); 387 typedef float float2 __attribute__((ext_vector_type(2))); 388 389 float4 foo(float2 a, float2 b) { 390 float4 c; 391 c.xz = a; 392 c.yw = b; 393 return c; 394 } 395 396Query for this feature with ``__has_extension(attribute_ext_vector_type)``. 397 398Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax 399and functions. For example: 400 401.. code-block:: c++ 402 403 vector float foo(vector int a) { 404 vector int b; 405 b = vec_add(a, a) + a; 406 return (vector float)b; 407 } 408 409NEON vector types are created using ``neon_vector_type`` and 410``neon_polyvector_type`` attributes. For example: 411 412.. code-block:: c++ 413 414 typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t; 415 typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t; 416 417 int8x8_t foo(int8x8_t a) { 418 int8x8_t v; 419 v = a; 420 return v; 421 } 422 423Vector Literals 424--------------- 425 426Vector literals can be used to create vectors from a set of scalars, or 427vectors. Either parentheses or braces form can be used. In the parentheses 428form the number of literal values specified must be one, i.e. referring to a 429scalar value, or must match the size of the vector type being created. If a 430single scalar literal value is specified, the scalar literal value will be 431replicated to all the components of the vector type. In the brackets form any 432number of literals can be specified. For example: 433 434.. code-block:: c++ 435 436 typedef int v4si __attribute__((__vector_size__(16))); 437 typedef float float4 __attribute__((ext_vector_type(4))); 438 typedef float float2 __attribute__((ext_vector_type(2))); 439 440 v4si vsi = (v4si){1, 2, 3, 4}; 441 float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f); 442 vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1). 443 vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0). 444 vector int vi3 = (vector int)(1, 2); // error 445 vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0). 446 vector int vi5 = (vector int)(1, 2, 3, 4); 447 float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f)); 448 449Vector Operations 450----------------- 451 452The table below shows the support for each operation by vector extension. A 453dash indicates that an operation is not accepted according to a corresponding 454specification. 455 456============================== ======= ======= ======= ======= 457 Operator OpenCL AltiVec GCC NEON 458============================== ======= ======= ======= ======= 459[] yes yes yes -- 460unary operators +, -- yes yes yes -- 461++, -- -- yes yes yes -- 462+,--,*,/,% yes yes yes -- 463bitwise operators &,|,^,~ yes yes yes -- 464>>,<< yes yes yes -- 465!, &&, || yes -- -- -- 466==, !=, >, <, >=, <= yes yes -- -- 467= yes yes yes yes 468:? yes -- -- -- 469sizeof yes yes yes yes 470C-style cast yes yes yes no 471reinterpret_cast yes no yes no 472static_cast yes no yes no 473const_cast no no no no 474============================== ======= ======= ======= ======= 475 476See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`. 477 478Half-Precision Floating Point 479============================= 480 481Clang supports two half-precision (16-bit) floating point types: ``__fp16`` and 482``_Float16``. These types are supported in all language modes. 483 484``__fp16`` is supported on every target, as it is purely a storage format; see below. 485``_Float16`` is currently only supported on the following targets, with further 486targets pending ABI standardization: 487- 32-bit ARM 488- 64-bit ARM (AArch64) 489- SPIR 490``_Float16`` will be supported on more targets as they define ABIs for it. 491 492``__fp16`` is a storage and interchange format only. This means that values of 493``__fp16`` are immediately promoted to (at least) ``float`` when used in arithmetic 494operations, so that e.g. the result of adding two ``__fp16`` values has type ``float``. 495The behavior of ``__fp16`` is specified by the ARM C Language Extensions (`ACLE <http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053d/IHI0053D_acle_2_1.pdf>`_). 496Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``, not the ARM 497alternative format. 498 499``_Float16`` is an extended floating-point type. This means that, just like arithmetic on 500``float`` or ``double``, arithmetic on ``_Float16`` operands is formally performed in the 501``_Float16`` type, so that e.g. the result of adding two ``_Float16`` values has type 502``_Float16``. The behavior of ``_Float16`` is specified by ISO/IEC TS 18661-3:2015 503("Floating-point extensions for C"). As with ``__fp16``, Clang uses the ``binary16`` 504format from IEEE 754-2008 for ``_Float16``. 505 506``_Float16`` arithmetic will be performed using native half-precision support 507when available on the target (e.g. on ARMv8.2a); otherwise it will be performed 508at a higher precision (currently always ``float``) and then truncated down to 509``_Float16``. Note that C and C++ allow intermediate floating-point operands 510of an expression to be computed with greater precision than is expressible in 511their type, so Clang may avoid intermediate truncations in certain cases; this may 512lead to results that are inconsistent with native arithmetic. 513 514It is recommended that portable code use ``_Float16`` instead of ``__fp16``, 515as it has been defined by the C standards committee and has behavior that is 516more familiar to most programmers. 517 518Because ``__fp16`` operands are always immediately promoted to ``float``, the 519common real type of ``__fp16`` and ``_Float16`` for the purposes of the usual 520arithmetic conversions is ``float``. 521 522A literal can be given ``_Float16`` type using the suffix ``f16``; for example: 523``` 5243.14f16 525``` 526 527Because default argument promotion only applies to the standard floating-point 528types, ``_Float16`` values are not promoted to ``double`` when passed as variadic 529or untyped arguments. As a consequence, some caution must be taken when using 530certain library facilities with ``_Float16``; for example, there is no ``printf`` format 531specifier for ``_Float16``, and (unlike ``float``) it will not be implicitly promoted to 532``double`` when passed to ``printf``, so the programmer must explicitly cast it to 533``double`` before using it with an ``%f`` or similar specifier. 534 535Messages on ``deprecated`` and ``unavailable`` Attributes 536========================================================= 537 538An optional string message can be added to the ``deprecated`` and 539``unavailable`` attributes. For example: 540 541.. code-block:: c++ 542 543 void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!"))); 544 545If the deprecated or unavailable declaration is used, the message will be 546incorporated into the appropriate diagnostic: 547 548.. code-block:: none 549 550 harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!! 551 [-Wdeprecated-declarations] 552 explode(); 553 ^ 554 555Query for this feature with 556``__has_extension(attribute_deprecated_with_message)`` and 557``__has_extension(attribute_unavailable_with_message)``. 558 559Attributes on Enumerators 560========================= 561 562Clang allows attributes to be written on individual enumerators. This allows 563enumerators to be deprecated, made unavailable, etc. The attribute must appear 564after the enumerator name and before any initializer, like so: 565 566.. code-block:: c++ 567 568 enum OperationMode { 569 OM_Invalid, 570 OM_Normal, 571 OM_Terrified __attribute__((deprecated)), 572 OM_AbortOnError __attribute__((deprecated)) = 4 573 }; 574 575Attributes on the ``enum`` declaration do not apply to individual enumerators. 576 577Query for this feature with ``__has_extension(enumerator_attributes)``. 578 579'User-Specified' System Frameworks 580================================== 581 582Clang provides a mechanism by which frameworks can be built in such a way that 583they will always be treated as being "system frameworks", even if they are not 584present in a system framework directory. This can be useful to system 585framework developers who want to be able to test building other applications 586with development builds of their framework, including the manner in which the 587compiler changes warning behavior for system headers. 588 589Framework developers can opt-in to this mechanism by creating a 590"``.system_framework``" file at the top-level of their framework. That is, the 591framework should have contents like: 592 593.. code-block:: none 594 595 .../TestFramework.framework 596 .../TestFramework.framework/.system_framework 597 .../TestFramework.framework/Headers 598 .../TestFramework.framework/Headers/TestFramework.h 599 ... 600 601Clang will treat the presence of this file as an indicator that the framework 602should be treated as a system framework, regardless of how it was found in the 603framework search path. For consistency, we recommend that such files never be 604included in installed versions of the framework. 605 606Checks for Standard Language Features 607===================================== 608 609The ``__has_feature`` macro can be used to query if certain standard language 610features are enabled. The ``__has_extension`` macro can be used to query if 611language features are available as an extension when compiling for a standard 612which does not provide them. The features which can be tested are listed here. 613 614Since Clang 3.4, the C++ SD-6 feature test macros are also supported. 615These are macros with names of the form ``__cpp_<feature_name>``, and are 616intended to be a portable way to query the supported features of the compiler. 617See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for 618information on the version of SD-6 supported by each Clang release, and the 619macros provided by that revision of the recommendations. 620 621C++98 622----- 623 624The features listed below are part of the C++98 standard. These features are 625enabled by default when compiling C++ code. 626 627C++ exceptions 628^^^^^^^^^^^^^^ 629 630Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been 631enabled. For example, compiling code with ``-fno-exceptions`` disables C++ 632exceptions. 633 634C++ RTTI 635^^^^^^^^ 636 637Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For 638example, compiling code with ``-fno-rtti`` disables the use of RTTI. 639 640C++11 641----- 642 643The features listed below are part of the C++11 standard. As a result, all 644these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option 645when compiling C++ code. 646 647C++11 SFINAE includes access control 648^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 649 650Use ``__has_feature(cxx_access_control_sfinae)`` or 651``__has_extension(cxx_access_control_sfinae)`` to determine whether 652access-control errors (e.g., calling a private constructor) are considered to 653be template argument deduction errors (aka SFINAE errors), per `C++ DR1170 654<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_. 655 656C++11 alias templates 657^^^^^^^^^^^^^^^^^^^^^ 658 659Use ``__has_feature(cxx_alias_templates)`` or 660``__has_extension(cxx_alias_templates)`` to determine if support for C++11's 661alias declarations and alias templates is enabled. 662 663C++11 alignment specifiers 664^^^^^^^^^^^^^^^^^^^^^^^^^^ 665 666Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to 667determine if support for alignment specifiers using ``alignas`` is enabled. 668 669Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to 670determine if support for the ``alignof`` keyword is enabled. 671 672C++11 attributes 673^^^^^^^^^^^^^^^^ 674 675Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to 676determine if support for attribute parsing with C++11's square bracket notation 677is enabled. 678 679C++11 generalized constant expressions 680^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 681 682Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized 683constant expressions (e.g., ``constexpr``) is enabled. 684 685C++11 ``decltype()`` 686^^^^^^^^^^^^^^^^^^^^ 687 688Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to 689determine if support for the ``decltype()`` specifier is enabled. C++11's 690``decltype`` does not require type-completeness of a function call expression. 691Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or 692``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if 693support for this feature is enabled. 694 695C++11 default template arguments in function templates 696^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 697 698Use ``__has_feature(cxx_default_function_template_args)`` or 699``__has_extension(cxx_default_function_template_args)`` to determine if support 700for default template arguments in function templates is enabled. 701 702C++11 ``default``\ ed functions 703^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 704 705Use ``__has_feature(cxx_defaulted_functions)`` or 706``__has_extension(cxx_defaulted_functions)`` to determine if support for 707defaulted function definitions (with ``= default``) is enabled. 708 709C++11 delegating constructors 710^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 711 712Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for 713delegating constructors is enabled. 714 715C++11 ``deleted`` functions 716^^^^^^^^^^^^^^^^^^^^^^^^^^^ 717 718Use ``__has_feature(cxx_deleted_functions)`` or 719``__has_extension(cxx_deleted_functions)`` to determine if support for deleted 720function definitions (with ``= delete``) is enabled. 721 722C++11 explicit conversion functions 723^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 724 725Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for 726``explicit`` conversion functions is enabled. 727 728C++11 generalized initializers 729^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 730 731Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for 732generalized initializers (using braced lists and ``std::initializer_list``) is 733enabled. 734 735C++11 implicit move constructors/assignment operators 736^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 737 738Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly 739generate move constructors and move assignment operators where needed. 740 741C++11 inheriting constructors 742^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 743 744Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for 745inheriting constructors is enabled. 746 747C++11 inline namespaces 748^^^^^^^^^^^^^^^^^^^^^^^ 749 750Use ``__has_feature(cxx_inline_namespaces)`` or 751``__has_extension(cxx_inline_namespaces)`` to determine if support for inline 752namespaces is enabled. 753 754C++11 lambdas 755^^^^^^^^^^^^^ 756 757Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to 758determine if support for lambdas is enabled. 759 760C++11 local and unnamed types as template arguments 761^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 762 763Use ``__has_feature(cxx_local_type_template_args)`` or 764``__has_extension(cxx_local_type_template_args)`` to determine if support for 765local and unnamed types as template arguments is enabled. 766 767C++11 noexcept 768^^^^^^^^^^^^^^ 769 770Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to 771determine if support for noexcept exception specifications is enabled. 772 773C++11 in-class non-static data member initialization 774^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 775 776Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class 777initialization of non-static data members is enabled. 778 779C++11 ``nullptr`` 780^^^^^^^^^^^^^^^^^ 781 782Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to 783determine if support for ``nullptr`` is enabled. 784 785C++11 ``override control`` 786^^^^^^^^^^^^^^^^^^^^^^^^^^ 787 788Use ``__has_feature(cxx_override_control)`` or 789``__has_extension(cxx_override_control)`` to determine if support for the 790override control keywords is enabled. 791 792C++11 reference-qualified functions 793^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 794 795Use ``__has_feature(cxx_reference_qualified_functions)`` or 796``__has_extension(cxx_reference_qualified_functions)`` to determine if support 797for reference-qualified functions (e.g., member functions with ``&`` or ``&&`` 798applied to ``*this``) is enabled. 799 800C++11 range-based ``for`` loop 801^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 802 803Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to 804determine if support for the range-based for loop is enabled. 805 806C++11 raw string literals 807^^^^^^^^^^^^^^^^^^^^^^^^^ 808 809Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw 810string literals (e.g., ``R"x(foo\bar)x"``) is enabled. 811 812C++11 rvalue references 813^^^^^^^^^^^^^^^^^^^^^^^ 814 815Use ``__has_feature(cxx_rvalue_references)`` or 816``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue 817references is enabled. 818 819C++11 ``static_assert()`` 820^^^^^^^^^^^^^^^^^^^^^^^^^ 821 822Use ``__has_feature(cxx_static_assert)`` or 823``__has_extension(cxx_static_assert)`` to determine if support for compile-time 824assertions using ``static_assert`` is enabled. 825 826C++11 ``thread_local`` 827^^^^^^^^^^^^^^^^^^^^^^ 828 829Use ``__has_feature(cxx_thread_local)`` to determine if support for 830``thread_local`` variables is enabled. 831 832C++11 type inference 833^^^^^^^^^^^^^^^^^^^^ 834 835Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to 836determine C++11 type inference is supported using the ``auto`` specifier. If 837this is disabled, ``auto`` will instead be a storage class specifier, as in C 838or C++98. 839 840C++11 strongly typed enumerations 841^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 842 843Use ``__has_feature(cxx_strong_enums)`` or 844``__has_extension(cxx_strong_enums)`` to determine if support for strongly 845typed, scoped enumerations is enabled. 846 847C++11 trailing return type 848^^^^^^^^^^^^^^^^^^^^^^^^^^ 849 850Use ``__has_feature(cxx_trailing_return)`` or 851``__has_extension(cxx_trailing_return)`` to determine if support for the 852alternate function declaration syntax with trailing return type is enabled. 853 854C++11 Unicode string literals 855^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 856 857Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode 858string literals is enabled. 859 860C++11 unrestricted unions 861^^^^^^^^^^^^^^^^^^^^^^^^^ 862 863Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for 864unrestricted unions is enabled. 865 866C++11 user-defined literals 867^^^^^^^^^^^^^^^^^^^^^^^^^^^ 868 869Use ``__has_feature(cxx_user_literals)`` to determine if support for 870user-defined literals is enabled. 871 872C++11 variadic templates 873^^^^^^^^^^^^^^^^^^^^^^^^ 874 875Use ``__has_feature(cxx_variadic_templates)`` or 876``__has_extension(cxx_variadic_templates)`` to determine if support for 877variadic templates is enabled. 878 879C++14 880----- 881 882The features listed below are part of the C++14 standard. As a result, all 883these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option 884when compiling C++ code. 885 886C++14 binary literals 887^^^^^^^^^^^^^^^^^^^^^ 888 889Use ``__has_feature(cxx_binary_literals)`` or 890``__has_extension(cxx_binary_literals)`` to determine whether 891binary literals (for instance, ``0b10010``) are recognized. Clang supports this 892feature as an extension in all language modes. 893 894C++14 contextual conversions 895^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 896 897Use ``__has_feature(cxx_contextual_conversions)`` or 898``__has_extension(cxx_contextual_conversions)`` to determine if the C++14 rules 899are used when performing an implicit conversion for an array bound in a 900*new-expression*, the operand of a *delete-expression*, an integral constant 901expression, or a condition in a ``switch`` statement. 902 903C++14 decltype(auto) 904^^^^^^^^^^^^^^^^^^^^ 905 906Use ``__has_feature(cxx_decltype_auto)`` or 907``__has_extension(cxx_decltype_auto)`` to determine if support 908for the ``decltype(auto)`` placeholder type is enabled. 909 910C++14 default initializers for aggregates 911^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 912 913Use ``__has_feature(cxx_aggregate_nsdmi)`` or 914``__has_extension(cxx_aggregate_nsdmi)`` to determine if support 915for default initializers in aggregate members is enabled. 916 917C++14 digit separators 918^^^^^^^^^^^^^^^^^^^^^^ 919 920Use ``__cpp_digit_separators`` to determine if support for digit separators 921using single quotes (for instance, ``10'000``) is enabled. At this time, there 922is no corresponding ``__has_feature`` name 923 924C++14 generalized lambda capture 925^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 926 927Use ``__has_feature(cxx_init_captures)`` or 928``__has_extension(cxx_init_captures)`` to determine if support for 929lambda captures with explicit initializers is enabled 930(for instance, ``[n(0)] { return ++n; }``). 931 932C++14 generic lambdas 933^^^^^^^^^^^^^^^^^^^^^ 934 935Use ``__has_feature(cxx_generic_lambdas)`` or 936``__has_extension(cxx_generic_lambdas)`` to determine if support for generic 937(polymorphic) lambdas is enabled 938(for instance, ``[] (auto x) { return x + 1; }``). 939 940C++14 relaxed constexpr 941^^^^^^^^^^^^^^^^^^^^^^^ 942 943Use ``__has_feature(cxx_relaxed_constexpr)`` or 944``__has_extension(cxx_relaxed_constexpr)`` to determine if variable 945declarations, local variable modification, and control flow constructs 946are permitted in ``constexpr`` functions. 947 948C++14 return type deduction 949^^^^^^^^^^^^^^^^^^^^^^^^^^^ 950 951Use ``__has_feature(cxx_return_type_deduction)`` or 952``__has_extension(cxx_return_type_deduction)`` to determine if support 953for return type deduction for functions (using ``auto`` as a return type) 954is enabled. 955 956C++14 runtime-sized arrays 957^^^^^^^^^^^^^^^^^^^^^^^^^^ 958 959Use ``__has_feature(cxx_runtime_array)`` or 960``__has_extension(cxx_runtime_array)`` to determine if support 961for arrays of runtime bound (a restricted form of variable-length arrays) 962is enabled. 963Clang's implementation of this feature is incomplete. 964 965C++14 variable templates 966^^^^^^^^^^^^^^^^^^^^^^^^ 967 968Use ``__has_feature(cxx_variable_templates)`` or 969``__has_extension(cxx_variable_templates)`` to determine if support for 970templated variable declarations is enabled. 971 972C11 973--- 974 975The features listed below are part of the C11 standard. As a result, all these 976features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when 977compiling C code. Additionally, because these features are all 978backward-compatible, they are available as extensions in all language modes. 979 980C11 alignment specifiers 981^^^^^^^^^^^^^^^^^^^^^^^^ 982 983Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine 984if support for alignment specifiers using ``_Alignas`` is enabled. 985 986Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine 987if support for the ``_Alignof`` keyword is enabled. 988 989C11 atomic operations 990^^^^^^^^^^^^^^^^^^^^^ 991 992Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine 993if support for atomic types using ``_Atomic`` is enabled. Clang also provides 994:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement 995the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use 996``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header 997is available. 998 999Clang will use the system's ``<stdatomic.h>`` header when one is available, and 1000will otherwise use its own. When using its own, implementations of the atomic 1001operations are provided as macros. In the cases where C11 also requires a real 1002function, this header provides only the declaration of that function (along 1003with a shadowing macro implementation), and you must link to a library which 1004provides a definition of the function if you use it instead of the macro. 1005 1006C11 generic selections 1007^^^^^^^^^^^^^^^^^^^^^^ 1008 1009Use ``__has_feature(c_generic_selections)`` or 1010``__has_extension(c_generic_selections)`` to determine if support for generic 1011selections is enabled. 1012 1013As an extension, the C11 generic selection expression is available in all 1014languages supported by Clang. The syntax is the same as that given in the C11 1015standard. 1016 1017In C, type compatibility is decided according to the rules given in the 1018appropriate standard, but in C++, which lacks the type compatibility rules used 1019in C, types are considered compatible only if they are equivalent. 1020 1021C11 ``_Static_assert()`` 1022^^^^^^^^^^^^^^^^^^^^^^^^ 1023 1024Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)`` 1025to determine if support for compile-time assertions using ``_Static_assert`` is 1026enabled. 1027 1028C11 ``_Thread_local`` 1029^^^^^^^^^^^^^^^^^^^^^ 1030 1031Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)`` 1032to determine if support for ``_Thread_local`` variables is enabled. 1033 1034Modules 1035------- 1036 1037Use ``__has_feature(modules)`` to determine if Modules have been enabled. 1038For example, compiling code with ``-fmodules`` enables the use of Modules. 1039 1040More information could be found `here <https://clang.llvm.org/docs/Modules.html>`_. 1041 1042Checks for Type Trait Primitives 1043================================ 1044 1045Type trait primitives are special builtin constant expressions that can be used 1046by the standard C++ library to facilitate or simplify the implementation of 1047user-facing type traits in the <type_traits> header. 1048 1049They are not intended to be used directly by user code because they are 1050implementation-defined and subject to change -- as such they're tied closely to 1051the supported set of system headers, currently: 1052 1053* LLVM's own libc++ 1054* GNU libstdc++ 1055* The Microsoft standard C++ library 1056 1057Clang supports the `GNU C++ type traits 1058<https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the 1059`Microsoft Visual C++ Type traits 1060<https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_. 1061 1062Feature detection is supported only for some of the primitives at present. User 1063code should not use these checks because they bear no direct relation to the 1064actual set of type traits supported by the C++ standard library. 1065 1066For type trait ``__X``, ``__has_extension(X)`` indicates the presence of the 1067type trait primitive in the compiler. A simplistic usage example as might be 1068seen in standard C++ headers follows: 1069 1070.. code-block:: c++ 1071 1072 #if __has_extension(is_convertible_to) 1073 template<typename From, typename To> 1074 struct is_convertible_to { 1075 static const bool value = __is_convertible_to(From, To); 1076 }; 1077 #else 1078 // Emulate type trait for compatibility with other compilers. 1079 #endif 1080 1081The following type trait primitives are supported by Clang: 1082 1083* ``__has_nothrow_assign`` (GNU, Microsoft) 1084* ``__has_nothrow_copy`` (GNU, Microsoft) 1085* ``__has_nothrow_constructor`` (GNU, Microsoft) 1086* ``__has_trivial_assign`` (GNU, Microsoft) 1087* ``__has_trivial_copy`` (GNU, Microsoft) 1088* ``__has_trivial_constructor`` (GNU, Microsoft) 1089* ``__has_trivial_destructor`` (GNU, Microsoft) 1090* ``__has_virtual_destructor`` (GNU, Microsoft) 1091* ``__is_abstract`` (GNU, Microsoft) 1092* ``__is_aggregate`` (GNU, Microsoft) 1093* ``__is_base_of`` (GNU, Microsoft) 1094* ``__is_class`` (GNU, Microsoft) 1095* ``__is_convertible_to`` (Microsoft) 1096* ``__is_empty`` (GNU, Microsoft) 1097* ``__is_enum`` (GNU, Microsoft) 1098* ``__is_interface_class`` (Microsoft) 1099* ``__is_pod`` (GNU, Microsoft) 1100* ``__is_polymorphic`` (GNU, Microsoft) 1101* ``__is_union`` (GNU, Microsoft) 1102* ``__is_literal(type)``: Determines whether the given type is a literal type 1103* ``__is_final``: Determines whether the given type is declared with a 1104 ``final`` class-virt-specifier. 1105* ``__underlying_type(type)``: Retrieves the underlying type for a given 1106 ``enum`` type. This trait is required to implement the C++11 standard 1107 library. 1108* ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value 1109 of type ``totype`` can be assigned to from a value of type ``fromtype`` such 1110 that no non-trivial functions are called as part of that assignment. This 1111 trait is required to implement the C++11 standard library. 1112* ``__is_trivially_constructible(type, argtypes...)``: Determines whether a 1113 value of type ``type`` can be direct-initialized with arguments of types 1114 ``argtypes...`` such that no non-trivial functions are called as part of 1115 that initialization. This trait is required to implement the C++11 standard 1116 library. 1117* ``__is_destructible`` (MSVC 2013) 1118* ``__is_nothrow_destructible`` (MSVC 2013) 1119* ``__is_nothrow_assignable`` (MSVC 2013, clang) 1120* ``__is_constructible`` (MSVC 2013, clang) 1121* ``__is_nothrow_constructible`` (MSVC 2013, clang) 1122* ``__is_assignable`` (MSVC 2015, clang) 1123* ``__reference_binds_to_temporary(T, U)`` (Clang): Determines whether a 1124 reference of type ``T`` bound to an expression of type ``U`` would bind to a 1125 materialized temporary object. If ``T`` is not a reference type the result 1126 is false. Note this trait will also return false when the initialization of 1127 ``T`` from ``U`` is ill-formed. 1128 1129Blocks 1130====== 1131 1132The syntax and high level language feature description is in 1133:doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for 1134the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`. 1135 1136Query for this feature with ``__has_extension(blocks)``. 1137 1138Objective-C Features 1139==================== 1140 1141Related result types 1142-------------------- 1143 1144According to Cocoa conventions, Objective-C methods with certain names 1145("``init``", "``alloc``", etc.) always return objects that are an instance of 1146the receiving class's type. Such methods are said to have a "related result 1147type", meaning that a message send to one of these methods will have the same 1148static type as an instance of the receiver class. For example, given the 1149following classes: 1150 1151.. code-block:: objc 1152 1153 @interface NSObject 1154 + (id)alloc; 1155 - (id)init; 1156 @end 1157 1158 @interface NSArray : NSObject 1159 @end 1160 1161and this common initialization pattern 1162 1163.. code-block:: objc 1164 1165 NSArray *array = [[NSArray alloc] init]; 1166 1167the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because 1168``alloc`` implicitly has a related result type. Similarly, the type of the 1169expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a 1170related result type and its receiver is known to have the type ``NSArray *``. 1171If neither ``alloc`` nor ``init`` had a related result type, the expressions 1172would have had type ``id``, as declared in the method signature. 1173 1174A method with a related result type can be declared by using the type 1175``instancetype`` as its result type. ``instancetype`` is a contextual keyword 1176that is only permitted in the result type of an Objective-C method, e.g. 1177 1178.. code-block:: objc 1179 1180 @interface A 1181 + (instancetype)constructAnA; 1182 @end 1183 1184The related result type can also be inferred for some methods. To determine 1185whether a method has an inferred related result type, the first word in the 1186camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered, 1187and the method will have a related result type if its return type is compatible 1188with the type of its class and if: 1189 1190* the first word is "``alloc``" or "``new``", and the method is a class method, 1191 or 1192 1193* the first word is "``autorelease``", "``init``", "``retain``", or "``self``", 1194 and the method is an instance method. 1195 1196If a method with a related result type is overridden by a subclass method, the 1197subclass method must also return a type that is compatible with the subclass 1198type. For example: 1199 1200.. code-block:: objc 1201 1202 @interface NSString : NSObject 1203 - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString 1204 @end 1205 1206Related result types only affect the type of a message send or property access 1207via the given method. In all other respects, a method with a related result 1208type is treated the same way as method that returns ``id``. 1209 1210Use ``__has_feature(objc_instancetype)`` to determine whether the 1211``instancetype`` contextual keyword is available. 1212 1213Automatic reference counting 1214---------------------------- 1215 1216Clang provides support for :doc:`automated reference counting 1217<AutomaticReferenceCounting>` in Objective-C, which eliminates the need 1218for manual ``retain``/``release``/``autorelease`` message sends. There are three 1219feature macros associated with automatic reference counting: 1220``__has_feature(objc_arc)`` indicates the availability of automated reference 1221counting in general, while ``__has_feature(objc_arc_weak)`` indicates that 1222automated reference counting also includes support for ``__weak`` pointers to 1223Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs 1224are allowed to have fields that are pointers to Objective-C objects managed by 1225automatic reference counting. 1226 1227.. _objc-weak: 1228 1229Weak references 1230--------------- 1231 1232Clang supports ARC-style weak and unsafe references in Objective-C even 1233outside of ARC mode. Weak references must be explicitly enabled with 1234the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))`` 1235to test whether they are enabled. Unsafe references are enabled 1236unconditionally. ARC-style weak and unsafe references cannot be used 1237when Objective-C garbage collection is enabled. 1238 1239Except as noted below, the language rules for the ``__weak`` and 1240``__unsafe_unretained`` qualifiers (and the ``weak`` and 1241``unsafe_unretained`` property attributes) are just as laid out 1242in the :doc:`ARC specification <AutomaticReferenceCounting>`. 1243In particular, note that some classes do not support forming weak 1244references to their instances, and note that special care must be 1245taken when storing weak references in memory where initialization 1246and deinitialization are outside the responsibility of the compiler 1247(such as in ``malloc``-ed memory). 1248 1249Loading from a ``__weak`` variable always implicitly retains the 1250loaded value. In non-ARC modes, this retain is normally balanced 1251by an implicit autorelease. This autorelease can be suppressed 1252by performing the load in the receiver position of a ``-retain`` 1253message send (e.g. ``[weakReference retain]``); note that this performs 1254only a single retain (the retain done when primitively loading from 1255the weak reference). 1256 1257For the most part, ``__unsafe_unretained`` in non-ARC modes is just the 1258default behavior of variables and therefore is not needed. However, 1259it does have an effect on the semantics of block captures: normally, 1260copying a block which captures an Objective-C object or block pointer 1261causes the captured pointer to be retained or copied, respectively, 1262but that behavior is suppressed when the captured variable is qualified 1263with ``__unsafe_unretained``. 1264 1265Note that the ``__weak`` qualifier formerly meant the GC qualifier in 1266all non-ARC modes and was silently ignored outside of GC modes. It now 1267means the ARC-style qualifier in all non-GC modes and is no longer 1268allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``. 1269It is expected that ``-fobjc-weak`` will eventually be enabled by default 1270in all non-GC Objective-C modes. 1271 1272.. _objc-fixed-enum: 1273 1274Enumerations with a fixed underlying type 1275----------------------------------------- 1276 1277Clang provides support for C++11 enumerations with a fixed underlying type 1278within Objective-C. For example, one can write an enumeration type as: 1279 1280.. code-block:: c++ 1281 1282 typedef enum : unsigned char { Red, Green, Blue } Color; 1283 1284This specifies that the underlying type, which is used to store the enumeration 1285value, is ``unsigned char``. 1286 1287Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed 1288underlying types is available in Objective-C. 1289 1290Interoperability with C++11 lambdas 1291----------------------------------- 1292 1293Clang provides interoperability between C++11 lambdas and blocks-based APIs, by 1294permitting a lambda to be implicitly converted to a block pointer with the 1295corresponding signature. For example, consider an API such as ``NSArray``'s 1296array-sorting method: 1297 1298.. code-block:: objc 1299 1300 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr; 1301 1302``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult 1303(^)(id, id)``, and parameters of this type are generally provided with block 1304literals as arguments. However, one can also use a C++11 lambda so long as it 1305provides the same signature (in this case, accepting two parameters of type 1306``id`` and returning an ``NSComparisonResult``): 1307 1308.. code-block:: objc 1309 1310 NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11", 1311 @"String 02"]; 1312 const NSStringCompareOptions comparisonOptions 1313 = NSCaseInsensitiveSearch | NSNumericSearch | 1314 NSWidthInsensitiveSearch | NSForcedOrderingSearch; 1315 NSLocale *currentLocale = [NSLocale currentLocale]; 1316 NSArray *sorted 1317 = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult { 1318 NSRange string1Range = NSMakeRange(0, [s1 length]); 1319 return [s1 compare:s2 options:comparisonOptions 1320 range:string1Range locale:currentLocale]; 1321 }]; 1322 NSLog(@"sorted: %@", sorted); 1323 1324This code relies on an implicit conversion from the type of the lambda 1325expression (an unnamed, local class type called the *closure type*) to the 1326corresponding block pointer type. The conversion itself is expressed by a 1327conversion operator in that closure type that produces a block pointer with the 1328same signature as the lambda itself, e.g., 1329 1330.. code-block:: objc 1331 1332 operator NSComparisonResult (^)(id, id)() const; 1333 1334This conversion function returns a new block that simply forwards the two 1335parameters to the lambda object (which it captures by copy), then returns the 1336result. The returned block is first copied (with ``Block_copy``) and then 1337autoreleased. As an optimization, if a lambda expression is immediately 1338converted to a block pointer (as in the first example, above), then the block 1339is not copied and autoreleased: rather, it is given the same lifetime as a 1340block literal written at that point in the program, which avoids the overhead 1341of copying a block to the heap in the common case. 1342 1343The conversion from a lambda to a block pointer is only available in 1344Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory 1345management (autorelease). 1346 1347Object Literals and Subscripting 1348-------------------------------- 1349 1350Clang provides support for :doc:`Object Literals and Subscripting 1351<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C 1352programming patterns, makes programs more concise, and improves the safety of 1353container creation. There are several feature macros associated with object 1354literals and subscripting: ``__has_feature(objc_array_literals)`` tests the 1355availability of array literals; ``__has_feature(objc_dictionary_literals)`` 1356tests the availability of dictionary literals; 1357``__has_feature(objc_subscripting)`` tests the availability of object 1358subscripting. 1359 1360Objective-C Autosynthesis of Properties 1361--------------------------------------- 1362 1363Clang provides support for autosynthesis of declared properties. Using this 1364feature, clang provides default synthesis of those properties not declared 1365@dynamic and not having user provided backing getter and setter methods. 1366``__has_feature(objc_default_synthesize_properties)`` checks for availability 1367of this feature in version of clang being used. 1368 1369.. _langext-objc-retain-release: 1370 1371Objective-C retaining behavior attributes 1372----------------------------------------- 1373 1374In Objective-C, functions and methods are generally assumed to follow the 1375`Cocoa Memory Management 1376<https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_ 1377conventions for ownership of object arguments and 1378return values. However, there are exceptions, and so Clang provides attributes 1379to allow these exceptions to be documented. This are used by ARC and the 1380`static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be 1381better described using the ``objc_method_family`` attribute instead. 1382 1383**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``, 1384``ns_returns_autoreleased``, ``cf_returns_retained``, and 1385``cf_returns_not_retained`` attributes can be placed on methods and functions 1386that return Objective-C or CoreFoundation objects. They are commonly placed at 1387the end of a function prototype or method declaration: 1388 1389.. code-block:: objc 1390 1391 id foo() __attribute__((ns_returns_retained)); 1392 1393 - (NSString *)bar:(int)x __attribute__((ns_returns_retained)); 1394 1395The ``*_returns_retained`` attributes specify that the returned object has a +1 1396retain count. The ``*_returns_not_retained`` attributes specify that the return 1397object has a +0 retain count, even if the normal convention for its selector 1398would be +1. ``ns_returns_autoreleased`` specifies that the returned object is 1399+0, but is guaranteed to live at least as long as the next flush of an 1400autorelease pool. 1401 1402**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on 1403an parameter declaration; they specify that the argument is expected to have a 1404+1 retain count, which will be balanced in some way by the function or method. 1405The ``ns_consumes_self`` attribute can only be placed on an Objective-C 1406method; it specifies that the method expects its ``self`` parameter to have a 1407+1 retain count, which it will balance in some way. 1408 1409.. code-block:: objc 1410 1411 void foo(__attribute__((ns_consumed)) NSString *string); 1412 1413 - (void) bar __attribute__((ns_consumes_self)); 1414 - (void) baz:(id) __attribute__((ns_consumed)) x; 1415 1416Further examples of these attributes are available in the static analyzer's `list of annotations for analysis 1417<https://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_. 1418 1419Query for these features with ``__has_attribute(ns_consumed)``, 1420``__has_attribute(ns_returns_retained)``, etc. 1421 1422Objective-C @available 1423---------------------- 1424 1425It is possible to use the newest SDK but still build a program that can run on 1426older versions of macOS and iOS by passing ``-mmacosx-version-min=`` / 1427``-miphoneos-version-min=``. 1428 1429Before LLVM 5.0, when calling a function that exists only in the OS that's 1430newer than the target OS (as determined by the minimum deployment version), 1431programmers had to carefully check if the function exists at runtime, using 1432null checks for weakly-linked C functions, ``+class`` for Objective-C classes, 1433and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for 1434Objective-C methods. If such a check was missed, the program would compile 1435fine, run fine on newer systems, but crash on older systems. 1436 1437As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes 1438<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together 1439with the new ``@available()`` keyword to assist with this issue. 1440When a method that's introduced in the OS newer than the target OS is called, a 1441-Wunguarded-availability warning is emitted if that call is not guarded: 1442 1443.. code-block:: objc 1444 1445 void my_fun(NSSomeClass* var) { 1446 // If fancyNewMethod was added in e.g. macOS 10.12, but the code is 1447 // built with -mmacosx-version-min=10.11, then this unconditional call 1448 // will emit a -Wunguarded-availability warning: 1449 [var fancyNewMethod]; 1450 } 1451 1452To fix the warning and to avoid the crash on macOS 10.11, wrap it in 1453``if(@available())``: 1454 1455.. code-block:: objc 1456 1457 void my_fun(NSSomeClass* var) { 1458 if (@available(macOS 10.12, *)) { 1459 [var fancyNewMethod]; 1460 } else { 1461 // Put fallback behavior for old macOS versions (and for non-mac 1462 // platforms) here. 1463 } 1464 } 1465 1466The ``*`` is required and means that platforms not explicitly listed will take 1467the true branch, and the compiler will emit ``-Wunguarded-availability`` 1468warnings for unlisted platforms based on those platform's deployment target. 1469More than one platform can be listed in ``@available()``: 1470 1471.. code-block:: objc 1472 1473 void my_fun(NSSomeClass* var) { 1474 if (@available(macOS 10.12, iOS 10, *)) { 1475 [var fancyNewMethod]; 1476 } 1477 } 1478 1479If the caller of ``my_fun()`` already checks that ``my_fun()`` is only called 1480on 10.12, then add an `availability attribute 1481<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it, 1482which will also suppress the warning and require that calls to my_fun() are 1483checked: 1484 1485.. code-block:: objc 1486 1487 API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) { 1488 [var fancyNewMethod]; // Now ok. 1489 } 1490 1491``@available()`` is only available in Objective-C code. To use the feature 1492in C and C++ code, use the ``__builtin_available()`` spelling instead. 1493 1494If existing code uses null checks or ``-respondsToSelector:``, it should 1495be changed to use ``@available()`` (or ``__builtin_available``) instead. 1496 1497``-Wunguarded-availability`` is disabled by default, but 1498``-Wunguarded-availability-new``, which only emits this warning for APIs 1499that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and 1500tvOS >= 11, is enabled by default. 1501 1502.. _langext-overloading: 1503 1504Objective-C++ ABI: protocol-qualifier mangling of parameters 1505------------------------------------------------------------ 1506 1507Starting with LLVM 3.4, Clang produces a new mangling for parameters whose 1508type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such 1509parameters to be differentiated from those with the regular unqualified ``id`` 1510type. 1511 1512This was a non-backward compatible mangling change to the ABI. This change 1513allows proper overloading, and also prevents mangling conflicts with template 1514parameters of protocol-qualified type. 1515 1516Query the presence of this new mangling with 1517``__has_feature(objc_protocol_qualifier_mangling)``. 1518 1519Initializer lists for complex numbers in C 1520========================================== 1521 1522clang supports an extension which allows the following in C: 1523 1524.. code-block:: c++ 1525 1526 #include <math.h> 1527 #include <complex.h> 1528 complex float x = { 1.0f, INFINITY }; // Init to (1, Inf) 1529 1530This construct is useful because there is no way to separately initialize the 1531real and imaginary parts of a complex variable in standard C, given that clang 1532does not support ``_Imaginary``. (Clang also supports the ``__real__`` and 1533``__imag__`` extensions from gcc, which help in some cases, but are not usable 1534in static initializers.) 1535 1536Note that this extension does not allow eliding the braces; the meaning of the 1537following two lines is different: 1538 1539.. code-block:: c++ 1540 1541 complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1) 1542 complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0) 1543 1544This extension also works in C++ mode, as far as that goes, but does not apply 1545to the C++ ``std::complex``. (In C++11, list initialization allows the same 1546syntax to be used with ``std::complex`` with the same meaning.) 1547 1548Builtin Functions 1549================= 1550 1551Clang supports a number of builtin library functions with the same syntax as 1552GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``, 1553``__builtin_choose_expr``, ``__builtin_types_compatible_p``, 1554``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc. In addition to 1555the GCC builtins, Clang supports a number of builtins that GCC does not, which 1556are listed here. 1557 1558Please note that Clang does not and will not support all of the GCC builtins 1559for vector operations. Instead of using builtins, you should use the functions 1560defined in target-specific header files like ``<xmmintrin.h>``, which define 1561portable wrappers for these. Many of the Clang versions of these functions are 1562implemented directly in terms of :ref:`extended vector support 1563<langext-vectors>` instead of builtins, in order to reduce the number of 1564builtins that we need to implement. 1565 1566``__builtin_assume`` 1567------------------------------ 1568 1569``__builtin_assume`` is used to provide the optimizer with a boolean 1570invariant that is defined to be true. 1571 1572**Syntax**: 1573 1574.. code-block:: c++ 1575 1576 __builtin_assume(bool) 1577 1578**Example of Use**: 1579 1580.. code-block:: c++ 1581 1582 int foo(int x) { 1583 __builtin_assume(x != 0); 1584 1585 // The optimizer may short-circuit this check using the invariant. 1586 if (x == 0) 1587 return do_something(); 1588 1589 return do_something_else(); 1590 } 1591 1592**Description**: 1593 1594The boolean argument to this function is defined to be true. The optimizer may 1595analyze the form of the expression provided as the argument and deduce from 1596that information used to optimize the program. If the condition is violated 1597during execution, the behavior is undefined. The argument itself is never 1598evaluated, so any side effects of the expression will be discarded. 1599 1600Query for this feature with ``__has_builtin(__builtin_assume)``. 1601 1602``__builtin_readcyclecounter`` 1603------------------------------ 1604 1605``__builtin_readcyclecounter`` is used to access the cycle counter register (or 1606a similar low-latency, high-accuracy clock) on those targets that support it. 1607 1608**Syntax**: 1609 1610.. code-block:: c++ 1611 1612 __builtin_readcyclecounter() 1613 1614**Example of Use**: 1615 1616.. code-block:: c++ 1617 1618 unsigned long long t0 = __builtin_readcyclecounter(); 1619 do_something(); 1620 unsigned long long t1 = __builtin_readcyclecounter(); 1621 unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow 1622 1623**Description**: 1624 1625The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value, 1626which may be either global or process/thread-specific depending on the target. 1627As the backing counters often overflow quickly (on the order of seconds) this 1628should only be used for timing small intervals. When not supported by the 1629target, the return value is always zero. This builtin takes no arguments and 1630produces an unsigned long long result. 1631 1632Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note 1633that even if present, its use may depend on run-time privilege or other OS 1634controlled state. 1635 1636.. _langext-__builtin_shufflevector: 1637 1638``__builtin_shufflevector`` 1639--------------------------- 1640 1641``__builtin_shufflevector`` is used to express generic vector 1642permutation/shuffle/swizzle operations. This builtin is also very important 1643for the implementation of various target-specific header files like 1644``<xmmintrin.h>``. 1645 1646**Syntax**: 1647 1648.. code-block:: c++ 1649 1650 __builtin_shufflevector(vec1, vec2, index1, index2, ...) 1651 1652**Examples**: 1653 1654.. code-block:: c++ 1655 1656 // identity operation - return 4-element vector v1. 1657 __builtin_shufflevector(v1, v1, 0, 1, 2, 3) 1658 1659 // "Splat" element 0 of V1 into a 4-element result. 1660 __builtin_shufflevector(V1, V1, 0, 0, 0, 0) 1661 1662 // Reverse 4-element vector V1. 1663 __builtin_shufflevector(V1, V1, 3, 2, 1, 0) 1664 1665 // Concatenate every other element of 4-element vectors V1 and V2. 1666 __builtin_shufflevector(V1, V2, 0, 2, 4, 6) 1667 1668 // Concatenate every other element of 8-element vectors V1 and V2. 1669 __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14) 1670 1671 // Shuffle v1 with some elements being undefined 1672 __builtin_shufflevector(v1, v1, 3, -1, 1, -1) 1673 1674**Description**: 1675 1676The first two arguments to ``__builtin_shufflevector`` are vectors that have 1677the same element type. The remaining arguments are a list of integers that 1678specify the elements indices of the first two vectors that should be extracted 1679and returned in a new vector. These element indices are numbered sequentially 1680starting with the first vector, continuing into the second vector. Thus, if 1681``vec1`` is a 4-element vector, index 5 would refer to the second element of 1682``vec2``. An index of -1 can be used to indicate that the corresponding element 1683in the returned vector is a don't care and can be optimized by the backend. 1684 1685The result of ``__builtin_shufflevector`` is a vector with the same element 1686type as ``vec1``/``vec2`` but that has an element count equal to the number of 1687indices specified. 1688 1689Query for this feature with ``__has_builtin(__builtin_shufflevector)``. 1690 1691.. _langext-__builtin_convertvector: 1692 1693``__builtin_convertvector`` 1694--------------------------- 1695 1696``__builtin_convertvector`` is used to express generic vector 1697type-conversion operations. The input vector and the output vector 1698type must have the same number of elements. 1699 1700**Syntax**: 1701 1702.. code-block:: c++ 1703 1704 __builtin_convertvector(src_vec, dst_vec_type) 1705 1706**Examples**: 1707 1708.. code-block:: c++ 1709 1710 typedef double vector4double __attribute__((__vector_size__(32))); 1711 typedef float vector4float __attribute__((__vector_size__(16))); 1712 typedef short vector4short __attribute__((__vector_size__(8))); 1713 vector4float vf; vector4short vs; 1714 1715 // convert from a vector of 4 floats to a vector of 4 doubles. 1716 __builtin_convertvector(vf, vector4double) 1717 // equivalent to: 1718 (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] } 1719 1720 // convert from a vector of 4 shorts to a vector of 4 floats. 1721 __builtin_convertvector(vs, vector4float) 1722 // equivalent to: 1723 (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] } 1724 1725**Description**: 1726 1727The first argument to ``__builtin_convertvector`` is a vector, and the second 1728argument is a vector type with the same number of elements as the first 1729argument. 1730 1731The result of ``__builtin_convertvector`` is a vector with the same element 1732type as the second argument, with a value defined in terms of the action of a 1733C-style cast applied to each element of the first argument. 1734 1735Query for this feature with ``__has_builtin(__builtin_convertvector)``. 1736 1737``__builtin_bitreverse`` 1738------------------------ 1739 1740* ``__builtin_bitreverse8`` 1741* ``__builtin_bitreverse16`` 1742* ``__builtin_bitreverse32`` 1743* ``__builtin_bitreverse64`` 1744 1745**Syntax**: 1746 1747.. code-block:: c++ 1748 1749 __builtin_bitreverse32(x) 1750 1751**Examples**: 1752 1753.. code-block:: c++ 1754 1755 uint8_t rev_x = __builtin_bitreverse8(x); 1756 uint16_t rev_x = __builtin_bitreverse16(x); 1757 uint32_t rev_y = __builtin_bitreverse32(y); 1758 uint64_t rev_z = __builtin_bitreverse64(z); 1759 1760**Description**: 1761 1762The '``__builtin_bitreverse``' family of builtins is used to reverse 1763the bitpattern of an integer value; for example ``0b10110110`` becomes 1764``0b01101101``. 1765 1766``__builtin_rotateleft`` 1767------------------------ 1768 1769* ``__builtin_rotateleft8`` 1770* ``__builtin_rotateleft16`` 1771* ``__builtin_rotateleft32`` 1772* ``__builtin_rotateleft64`` 1773 1774**Syntax**: 1775 1776.. code-block:: c++ 1777 1778 __builtin_rotateleft32(x, y) 1779 1780**Examples**: 1781 1782.. code-block:: c++ 1783 1784 uint8_t rot_x = __builtin_rotateleft8(x, y); 1785 uint16_t rot_x = __builtin_rotateleft16(x, y); 1786 uint32_t rot_x = __builtin_rotateleft32(x, y); 1787 uint64_t rot_x = __builtin_rotateleft64(x, y); 1788 1789**Description**: 1790 1791The '``__builtin_rotateleft``' family of builtins is used to rotate 1792the bits in the first argument by the amount in the second argument. 1793For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``. 1794The shift value is treated as an unsigned amount modulo the size of 1795the arguments. Both arguments and the result have the bitwidth specified 1796by the name of the builtin. 1797 1798``__builtin_rotateright`` 1799------------------------- 1800 1801* ``__builtin_rotateright8`` 1802* ``__builtin_rotateright16`` 1803* ``__builtin_rotateright32`` 1804* ``__builtin_rotateright64`` 1805 1806**Syntax**: 1807 1808.. code-block:: c++ 1809 1810 __builtin_rotateright32(x, y) 1811 1812**Examples**: 1813 1814.. code-block:: c++ 1815 1816 uint8_t rot_x = __builtin_rotateright8(x, y); 1817 uint16_t rot_x = __builtin_rotateright16(x, y); 1818 uint32_t rot_x = __builtin_rotateright32(x, y); 1819 uint64_t rot_x = __builtin_rotateright64(x, y); 1820 1821**Description**: 1822 1823The '``__builtin_rotateright``' family of builtins is used to rotate 1824the bits in the first argument by the amount in the second argument. 1825For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``. 1826The shift value is treated as an unsigned amount modulo the size of 1827the arguments. Both arguments and the result have the bitwidth specified 1828by the name of the builtin. 1829 1830``__builtin_unreachable`` 1831------------------------- 1832 1833``__builtin_unreachable`` is used to indicate that a specific point in the 1834program cannot be reached, even if the compiler might otherwise think it can. 1835This is useful to improve optimization and eliminates certain warnings. For 1836example, without the ``__builtin_unreachable`` in the example below, the 1837compiler assumes that the inline asm can fall through and prints a "function 1838declared '``noreturn``' should not return" warning. 1839 1840**Syntax**: 1841 1842.. code-block:: c++ 1843 1844 __builtin_unreachable() 1845 1846**Example of use**: 1847 1848.. code-block:: c++ 1849 1850 void myabort(void) __attribute__((noreturn)); 1851 void myabort(void) { 1852 asm("int3"); 1853 __builtin_unreachable(); 1854 } 1855 1856**Description**: 1857 1858The ``__builtin_unreachable()`` builtin has completely undefined behavior. 1859Since it has undefined behavior, it is a statement that it is never reached and 1860the optimizer can take advantage of this to produce better code. This builtin 1861takes no arguments and produces a void result. 1862 1863Query for this feature with ``__has_builtin(__builtin_unreachable)``. 1864 1865``__builtin_unpredictable`` 1866--------------------------- 1867 1868``__builtin_unpredictable`` is used to indicate that a branch condition is 1869unpredictable by hardware mechanisms such as branch prediction logic. 1870 1871**Syntax**: 1872 1873.. code-block:: c++ 1874 1875 __builtin_unpredictable(long long) 1876 1877**Example of use**: 1878 1879.. code-block:: c++ 1880 1881 if (__builtin_unpredictable(x > 0)) { 1882 foo(); 1883 } 1884 1885**Description**: 1886 1887The ``__builtin_unpredictable()`` builtin is expected to be used with control 1888flow conditions such as in ``if`` and ``switch`` statements. 1889 1890Query for this feature with ``__has_builtin(__builtin_unpredictable)``. 1891 1892``__sync_swap`` 1893--------------- 1894 1895``__sync_swap`` is used to atomically swap integers or pointers in memory. 1896 1897**Syntax**: 1898 1899.. code-block:: c++ 1900 1901 type __sync_swap(type *ptr, type value, ...) 1902 1903**Example of Use**: 1904 1905.. code-block:: c++ 1906 1907 int old_value = __sync_swap(&value, new_value); 1908 1909**Description**: 1910 1911The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of 1912atomic intrinsics to allow code to atomically swap the current value with the 1913new value. More importantly, it helps developers write more efficient and 1914correct code by avoiding expensive loops around 1915``__sync_bool_compare_and_swap()`` or relying on the platform specific 1916implementation details of ``__sync_lock_test_and_set()``. The 1917``__sync_swap()`` builtin is a full barrier. 1918 1919``__builtin_addressof`` 1920----------------------- 1921 1922``__builtin_addressof`` performs the functionality of the built-in ``&`` 1923operator, ignoring any ``operator&`` overload. This is useful in constant 1924expressions in C++11, where there is no other way to take the address of an 1925object that overloads ``operator&``. 1926 1927**Example of use**: 1928 1929.. code-block:: c++ 1930 1931 template<typename T> constexpr T *addressof(T &value) { 1932 return __builtin_addressof(value); 1933 } 1934 1935``__builtin_operator_new`` and ``__builtin_operator_delete`` 1936------------------------------------------------------------ 1937 1938``__builtin_operator_new`` allocates memory just like a non-placement non-class 1939*new-expression*. This is exactly like directly calling the normal 1940non-placement ``::operator new``, except that it allows certain optimizations 1941that the C++ standard does not permit for a direct function call to 1942``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and 1943merging allocations). 1944 1945Likewise, ``__builtin_operator_delete`` deallocates memory just like a 1946non-class *delete-expression*, and is exactly like directly calling the normal 1947``::operator delete``, except that it permits optimizations. Only the unsized 1948form of ``__builtin_operator_delete`` is currently available. 1949 1950These builtins are intended for use in the implementation of ``std::allocator`` 1951and other similar allocation libraries, and are only available in C++. 1952 1953Multiprecision Arithmetic Builtins 1954---------------------------------- 1955 1956Clang provides a set of builtins which expose multiprecision arithmetic in a 1957manner amenable to C. They all have the following form: 1958 1959.. code-block:: c 1960 1961 unsigned x = ..., y = ..., carryin = ..., carryout; 1962 unsigned sum = __builtin_addc(x, y, carryin, &carryout); 1963 1964Thus one can form a multiprecision addition chain in the following manner: 1965 1966.. code-block:: c 1967 1968 unsigned *x, *y, *z, carryin=0, carryout; 1969 z[0] = __builtin_addc(x[0], y[0], carryin, &carryout); 1970 carryin = carryout; 1971 z[1] = __builtin_addc(x[1], y[1], carryin, &carryout); 1972 carryin = carryout; 1973 z[2] = __builtin_addc(x[2], y[2], carryin, &carryout); 1974 carryin = carryout; 1975 z[3] = __builtin_addc(x[3], y[3], carryin, &carryout); 1976 1977The complete list of builtins are: 1978 1979.. code-block:: c 1980 1981 unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout); 1982 unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout); 1983 unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout); 1984 unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout); 1985 unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout); 1986 unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout); 1987 unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout); 1988 unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout); 1989 unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout); 1990 unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout); 1991 1992Checked Arithmetic Builtins 1993--------------------------- 1994 1995Clang provides a set of builtins that implement checked arithmetic for security 1996critical applications in a manner that is fast and easily expressable in C. As 1997an example of their usage: 1998 1999.. code-block:: c 2000 2001 errorcode_t security_critical_application(...) { 2002 unsigned x, y, result; 2003 ... 2004 if (__builtin_mul_overflow(x, y, &result)) 2005 return kErrorCodeHackers; 2006 ... 2007 use_multiply(result); 2008 ... 2009 } 2010 2011Clang provides the following checked arithmetic builtins: 2012 2013.. code-block:: c 2014 2015 bool __builtin_add_overflow (type1 x, type2 y, type3 *sum); 2016 bool __builtin_sub_overflow (type1 x, type2 y, type3 *diff); 2017 bool __builtin_mul_overflow (type1 x, type2 y, type3 *prod); 2018 bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum); 2019 bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum); 2020 bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum); 2021 bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff); 2022 bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff); 2023 bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff); 2024 bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod); 2025 bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod); 2026 bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod); 2027 bool __builtin_sadd_overflow (int x, int y, int *sum); 2028 bool __builtin_saddl_overflow (long x, long y, long *sum); 2029 bool __builtin_saddll_overflow(long long x, long long y, long long *sum); 2030 bool __builtin_ssub_overflow (int x, int y, int *diff); 2031 bool __builtin_ssubl_overflow (long x, long y, long *diff); 2032 bool __builtin_ssubll_overflow(long long x, long long y, long long *diff); 2033 bool __builtin_smul_overflow (int x, int y, int *prod); 2034 bool __builtin_smull_overflow (long x, long y, long *prod); 2035 bool __builtin_smulll_overflow(long long x, long long y, long long *prod); 2036 2037Each builtin performs the specified mathematical operation on the 2038first two arguments and stores the result in the third argument. If 2039possible, the result will be equal to mathematically-correct result 2040and the builtin will return 0. Otherwise, the builtin will return 20411 and the result will be equal to the unique value that is equivalent 2042to the mathematically-correct result modulo two raised to the *k* 2043power, where *k* is the number of bits in the result type. The 2044behavior of these builtins is well-defined for all argument values. 2045 2046The first three builtins work generically for operands of any integer type, 2047including boolean types. The operands need not have the same type as each 2048other, or as the result. The other builtins may implicitly promote or 2049convert their operands before performing the operation. 2050 2051Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc. 2052 2053Floating point builtins 2054--------------------------------------- 2055 2056``__builtin_canonicalize`` 2057-------------------------- 2058 2059.. code-block:: c 2060 2061 double __builtin_canonicalize(double); 2062 float __builtin_canonicalizef(float); 2063 long double__builtin_canonicalizel(long double); 2064 2065Returns the platform specific canonical encoding of a floating point 2066number. This canonicalization is useful for implementing certain 2067numeric primitives such as frexp. See `LLVM canonicalize intrinsic 2068<https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for 2069more information on the semantics. 2070 2071String builtins 2072--------------- 2073 2074Clang provides constant expression evaluation support for builtins forms of 2075the following functions from the C standard library ``<string.h>`` header: 2076 2077* ``memchr`` 2078* ``memcmp`` 2079* ``strchr`` 2080* ``strcmp`` 2081* ``strlen`` 2082* ``strncmp`` 2083* ``wcschr`` 2084* ``wcscmp`` 2085* ``wcslen`` 2086* ``wcsncmp`` 2087* ``wmemchr`` 2088* ``wmemcmp`` 2089 2090In each case, the builtin form has the name of the C library function prefixed 2091by ``__builtin_``. Example: 2092 2093.. code-block:: c 2094 2095 void *p = __builtin_memchr("foobar", 'b', 5); 2096 2097In addition to the above, one further builtin is provided: 2098 2099.. code-block:: c 2100 2101 char *__builtin_char_memchr(const char *haystack, int needle, size_t size); 2102 2103``__builtin_char_memchr(a, b, c)`` is identical to 2104``(char*)__builtin_memchr(a, b, c)`` except that its use is permitted within 2105constant expressions in C++11 onwards (where a cast from ``void*`` to ``char*`` 2106is disallowed in general). 2107 2108Support for constant expression evaluation for the above builtins be detected 2109with ``__has_feature(cxx_constexpr_string_builtins)``. 2110 2111Atomic Min/Max builtins with memory ordering 2112-------------------------------------------- 2113 2114There are two atomic builtins with min/max in-memory comparison and swap. 2115The syntax and semantics are similar to GCC-compatible __atomic_* builtins. 2116 2117* ``__atomic_fetch_min`` 2118* ``__atomic_fetch_max`` 2119 2120The builtins work with signed and unsigned integers and require to specify memory ordering. 2121The return value is the original value that was stored in memory before comparison. 2122 2123Example: 2124 2125.. code-block:: c 2126 2127 unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED); 2128 2129The third argument is one of the memory ordering specifiers ``__ATOMIC_RELAXED``, 2130``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, ``__ATOMIC_RELEASE``, 2131``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics. 2132 2133In terms or aquire-release ordering barriers these two operations are always 2134considered as operations with *load-store* semantics, even when the original value 2135is not actually modified after comparison. 2136 2137.. _langext-__c11_atomic: 2138 2139__c11_atomic builtins 2140--------------------- 2141 2142Clang provides a set of builtins which are intended to be used to implement 2143C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the 2144``_explicit`` form of the corresponding C11 operation, and are named with a 2145``__c11_`` prefix. The supported operations, and the differences from 2146the corresponding C11 operations, are: 2147 2148* ``__c11_atomic_init`` 2149* ``__c11_atomic_thread_fence`` 2150* ``__c11_atomic_signal_fence`` 2151* ``__c11_atomic_is_lock_free`` (The argument is the size of the 2152 ``_Atomic(...)`` object, instead of its address) 2153* ``__c11_atomic_store`` 2154* ``__c11_atomic_load`` 2155* ``__c11_atomic_exchange`` 2156* ``__c11_atomic_compare_exchange_strong`` 2157* ``__c11_atomic_compare_exchange_weak`` 2158* ``__c11_atomic_fetch_add`` 2159* ``__c11_atomic_fetch_sub`` 2160* ``__c11_atomic_fetch_and`` 2161* ``__c11_atomic_fetch_or`` 2162* ``__c11_atomic_fetch_xor`` 2163 2164The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, 2165``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are 2166provided, with values corresponding to the enumerators of C11's 2167``memory_order`` enumeration. 2168 2169(Note that Clang additionally provides GCC-compatible ``__atomic_*`` 2170builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.0 2171atomic builtins are an explicit form of the corresponding OpenCL 2.0 2172builtin function, and are named with a ``__opencl_`` prefix. The macros 2173``__OPENCL_MEMORY_SCOPE_WORK_ITEM``, ``__OPENCL_MEMORY_SCOPE_WORK_GROUP``, 2174``__OPENCL_MEMORY_SCOPE_DEVICE``, ``__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES``, 2175and ``__OPENCL_MEMORY_SCOPE_SUB_GROUP`` are provided, with values 2176corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.) 2177 2178Low-level ARM exclusive memory builtins 2179--------------------------------------- 2180 2181Clang provides overloaded builtins giving direct access to the three key ARM 2182instructions for implementing atomic operations. 2183 2184.. code-block:: c 2185 2186 T __builtin_arm_ldrex(const volatile T *addr); 2187 T __builtin_arm_ldaex(const volatile T *addr); 2188 int __builtin_arm_strex(T val, volatile T *addr); 2189 int __builtin_arm_stlex(T val, volatile T *addr); 2190 void __builtin_arm_clrex(void); 2191 2192The types ``T`` currently supported are: 2193 2194* Integer types with width at most 64 bits (or 128 bits on AArch64). 2195* Floating-point types 2196* Pointer types. 2197 2198Note that the compiler does not guarantee it will not insert stores which clear 2199the exclusive monitor in between an ``ldrex`` type operation and its paired 2200``strex``. In practice this is only usually a risk when the extra store is on 2201the same cache line as the variable being modified and Clang will only insert 2202stack stores on its own, so it is best not to use these operations on variables 2203with automatic storage duration. 2204 2205Also, loads and stores may be implicit in code written between the ``ldrex`` and 2206``strex``. Clang will not necessarily mitigate the effects of these either, so 2207care should be exercised. 2208 2209For these reasons the higher level atomic primitives should be preferred where 2210possible. 2211 2212Non-temporal load/store builtins 2213-------------------------------- 2214 2215Clang provides overloaded builtins allowing generation of non-temporal memory 2216accesses. 2217 2218.. code-block:: c 2219 2220 T __builtin_nontemporal_load(T *addr); 2221 void __builtin_nontemporal_store(T value, T *addr); 2222 2223The types ``T`` currently supported are: 2224 2225* Integer types. 2226* Floating-point types. 2227* Vector types. 2228 2229Note that the compiler does not guarantee that non-temporal loads or stores 2230will be used. 2231 2232C++ Coroutines support builtins 2233-------------------------------- 2234 2235.. warning:: 2236 This is a work in progress. Compatibility across Clang/LLVM releases is not 2237 guaranteed. 2238 2239Clang provides experimental builtins to support C++ Coroutines as defined by 2240https://wg21.link/P0057. The following four are intended to be used by the 2241standard library to implement `std::experimental::coroutine_handle` type. 2242 2243**Syntax**: 2244 2245.. code-block:: c 2246 2247 void __builtin_coro_resume(void *addr); 2248 void __builtin_coro_destroy(void *addr); 2249 bool __builtin_coro_done(void *addr); 2250 void *__builtin_coro_promise(void *addr, int alignment, bool from_promise) 2251 2252**Example of use**: 2253 2254.. code-block:: c++ 2255 2256 template <> struct coroutine_handle<void> { 2257 void resume() const { __builtin_coro_resume(ptr); } 2258 void destroy() const { __builtin_coro_destroy(ptr); } 2259 bool done() const { return __builtin_coro_done(ptr); } 2260 // ... 2261 protected: 2262 void *ptr; 2263 }; 2264 2265 template <typename Promise> struct coroutine_handle : coroutine_handle<> { 2266 // ... 2267 Promise &promise() const { 2268 return *reinterpret_cast<Promise *>( 2269 __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false)); 2270 } 2271 static coroutine_handle from_promise(Promise &promise) { 2272 coroutine_handle p; 2273 p.ptr = __builtin_coro_promise(&promise, alignof(Promise), 2274 /*from-promise=*/true); 2275 return p; 2276 } 2277 }; 2278 2279 2280Other coroutine builtins are either for internal clang use or for use during 2281development of the coroutine feature. See `Coroutines in LLVM 2282<https://llvm.org/docs/Coroutines.html#intrinsics>`_ for 2283more information on their semantics. Note that builtins matching the intrinsics 2284that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc, 2285llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to 2286an appropriate value during the emission. 2287 2288**Syntax**: 2289 2290.. code-block:: c 2291 2292 size_t __builtin_coro_size() 2293 void *__builtin_coro_frame() 2294 void *__builtin_coro_free(void *coro_frame) 2295 2296 void *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts) 2297 bool __builtin_coro_alloc() 2298 void *__builtin_coro_begin(void *memory) 2299 void __builtin_coro_end(void *coro_frame, bool unwind) 2300 char __builtin_coro_suspend(bool final) 2301 bool __builtin_coro_param(void *original, void *copy) 2302 2303Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM 2304automatically will insert one if the first argument to `llvm.coro.suspend` is 2305token `none`. If a user calls `__builin_suspend`, clang will insert `token none` 2306as the first argument to the intrinsic. 2307 2308Source location builtins 2309------------------------ 2310 2311Clang provides experimental builtins to support C++ standard library implementation 2312of ``std::experimental::source_location`` as specified in http://wg21.link/N4600. 2313With the exception of ``__builtin_COLUMN``, these builtins are also implemented by 2314GCC. 2315 2316**Syntax**: 2317 2318.. code-block:: c 2319 2320 const char *__builtin_FILE(); 2321 const char *__builtin_FUNCTION(); 2322 unsigned __builtin_LINE(); 2323 unsigned __builtin_COLUMN(); // Clang only 2324 2325**Example of use**: 2326 2327.. code-block:: c++ 2328 2329 void my_assert(bool pred, int line = __builtin_LINE(), // Captures line of caller 2330 const char* file = __builtin_FILE(), 2331 const char* function = __builtin_FUNCTION()) { 2332 if (pred) return; 2333 printf("%s:%d assertion failed in function %s\n", file, line, function); 2334 std::abort(); 2335 } 2336 2337 struct MyAggregateType { 2338 int x; 2339 int line = __builtin_LINE(); // captures line where aggregate initialization occurs 2340 }; 2341 static_assert(MyAggregateType{42}.line == __LINE__); 2342 2343 struct MyClassType { 2344 int line = __builtin_LINE(); // captures line of the constructor used during initialization 2345 constexpr MyClassType(int) { assert(line == __LINE__); } 2346 }; 2347 2348**Description**: 2349 2350The builtins ``__builtin_LINE``, ``__builtin_FUNCTION``, and ``__builtin_FILE`` return 2351the values, at the "invocation point", for ``__LINE__``, ``__FUNCTION__``, and 2352``__FILE__`` respectively. These builtins are constant expressions. 2353 2354When the builtins appear as part of a default function argument the invocation 2355point is the location of the caller. When the builtins appear as part of a 2356default member initializer, the invocation point is the location of the 2357constructor or aggregate initialization used to create the object. Otherwise 2358the invocation point is the same as the location of the builtin. 2359 2360When the invocation point of ``__builtin_FUNCTION`` is not a function scope the 2361empty string is returned. 2362 2363Non-standard C++11 Attributes 2364============================= 2365 2366Clang's non-standard C++11 attributes live in the ``clang`` attribute 2367namespace. 2368 2369Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which 2370are accepted with the ``__attribute__((foo))`` syntax are also accepted as 2371``[[gnu::foo]]``. This only extends to attributes which are specified by GCC 2372(see the list of `GCC function attributes 2373<https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable 2374attributes <https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and 2375`GCC type attributes 2376<https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC 2377implementation, these attributes must appertain to the *declarator-id* in a 2378declaration, which means they must go either at the start of the declaration or 2379immediately after the name being declared. 2380 2381For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and 2382also applies the GNU ``noreturn`` attribute to ``f``. 2383 2384.. code-block:: c++ 2385 2386 [[gnu::unused]] int a, f [[gnu::noreturn]] (); 2387 2388Target-Specific Extensions 2389========================== 2390 2391Clang supports some language features conditionally on some targets. 2392 2393ARM/AArch64 Language Extensions 2394------------------------------- 2395 2396Memory Barrier Intrinsics 2397^^^^^^^^^^^^^^^^^^^^^^^^^ 2398Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined 2399in the `ARM C Language Extensions Release 2.0 2400<http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053c/IHI0053C_acle_2_0.pdf>`_. 2401Note that these intrinsics are implemented as motion barriers that block 2402reordering of memory accesses and side effect instructions. Other instructions 2403like simple arithmetic may be reordered around the intrinsic. If you expect to 2404have no reordering at all, use inline assembly instead. 2405 2406X86/X86-64 Language Extensions 2407------------------------------ 2408 2409The X86 backend has these language extensions: 2410 2411Memory references to specified segments 2412^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2413 2414Annotating a pointer with address space #256 causes it to be code generated 2415relative to the X86 GS segment register, address space #257 causes it to be 2416relative to the X86 FS segment, and address space #258 causes it to be 2417relative to the X86 SS segment. Note that this is a very very low-level 2418feature that should only be used if you know what you're doing (for example in 2419an OS kernel). 2420 2421Here is an example: 2422 2423.. code-block:: c++ 2424 2425 #define GS_RELATIVE __attribute__((address_space(256))) 2426 int foo(int GS_RELATIVE *P) { 2427 return *P; 2428 } 2429 2430Which compiles to (on X86-32): 2431 2432.. code-block:: gas 2433 2434 _foo: 2435 movl 4(%esp), %eax 2436 movl %gs:(%eax), %eax 2437 ret 2438 2439PowerPC Language Extensions 2440------------------------------ 2441 2442Set the Floating Point Rounding Mode 2443^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2444PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set 2445the floating point rounding mode. This function will use the least significant 2446two bits of integer argument to set the floating point rounding mode. 2447 2448.. code-block:: c++ 2449 2450 double __builtin_setrnd(int mode); 2451 2452The effective values for mode are: 2453 2454 - 0 - round to nearest 2455 - 1 - round to zero 2456 - 2 - round to +infinity 2457 - 3 - round to -infinity 2458 2459Note that the mode argument will modulo 4, so if the int argument is greater 2460than 3, it will only use the least significant two bits of the mode. 2461Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``. 2462 2463PowerPC Language Extensions 2464------------------------------ 2465 2466Set the Floating Point Rounding Mode 2467^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2468PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set 2469the floating point rounding mode. This function will use the least significant 2470two bits of integer argument to set the floating point rounding mode. 2471 2472.. code-block:: c++ 2473 2474 double __builtin_setrnd(int mode); 2475 2476The effective values for mode are: 2477 2478 - 0 - round to nearest 2479 - 1 - round to zero 2480 - 2 - round to +infinity 2481 - 3 - round to -infinity 2482 2483Note that the mode argument will modulo 4, so if the integer argument is greater 2484than 3, it will only use the least significant two bits of the mode. 2485Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``. 2486 2487PowerPC Language Extensions 2488------------------------------ 2489 2490Set the Floating Point Rounding Mode 2491^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2492PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set 2493the floating point rounding mode. This function will use the least significant 2494two bits of integer argument to set the floating point rounding mode. 2495 2496.. code-block:: c++ 2497 2498 double __builtin_setrnd(int mode); 2499 2500The effective values for mode are: 2501 2502 - 0 - round to nearest 2503 - 1 - round to zero 2504 - 2 - round to +infinity 2505 - 3 - round to -infinity 2506 2507Note that the mode argument will modulo 4, so if the integer argument is greater 2508than 3, it will only use the least significant two bits of the mode. 2509Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``. 2510 2511PowerPC cache builtins 2512^^^^^^^^^^^^^^^^^^^^^^ 2513 2514The PowerPC architecture specifies instructions implementing cache operations. 2515Clang provides builtins that give direct programmer access to these cache 2516instructions. 2517 2518Currently the following builtins are implemented in clang: 2519 2520``__builtin_dcbf`` copies the contents of a modified block from the data cache 2521to main memory and flushes the copy from the data cache. 2522 2523**Syntax**: 2524 2525.. code-block:: c 2526 2527 void __dcbf(const void* addr); /* Data Cache Block Flush */ 2528 2529**Example of Use**: 2530 2531.. code-block:: c 2532 2533 int a = 1; 2534 __builtin_dcbf (&a); 2535 2536Extensions for Static Analysis 2537============================== 2538 2539Clang supports additional attributes that are useful for documenting program 2540invariants and rules for static analysis tools, such as the `Clang Static 2541Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented 2542in the analyzer's `list of source-level annotations 2543<https://clang-analyzer.llvm.org/annotations.html>`_. 2544 2545 2546Extensions for Dynamic Analysis 2547=============================== 2548 2549Use ``__has_feature(address_sanitizer)`` to check if the code is being built 2550with :doc:`AddressSanitizer`. 2551 2552Use ``__has_feature(thread_sanitizer)`` to check if the code is being built 2553with :doc:`ThreadSanitizer`. 2554 2555Use ``__has_feature(memory_sanitizer)`` to check if the code is being built 2556with :doc:`MemorySanitizer`. 2557 2558Use ``__has_feature(safe_stack)`` to check if the code is being built 2559with :doc:`SafeStack`. 2560 2561 2562Extensions for selectively disabling optimization 2563================================================= 2564 2565Clang provides a mechanism for selectively disabling optimizations in functions 2566and methods. 2567 2568To disable optimizations in a single function definition, the GNU-style or C++11 2569non-standard attribute ``optnone`` can be used. 2570 2571.. code-block:: c++ 2572 2573 // The following functions will not be optimized. 2574 // GNU-style attribute 2575 __attribute__((optnone)) int foo() { 2576 // ... code 2577 } 2578 // C++11 attribute 2579 [[clang::optnone]] int bar() { 2580 // ... code 2581 } 2582 2583To facilitate disabling optimization for a range of function definitions, a 2584range-based pragma is provided. Its syntax is ``#pragma clang optimize`` 2585followed by ``off`` or ``on``. 2586 2587All function definitions in the region between an ``off`` and the following 2588``on`` will be decorated with the ``optnone`` attribute unless doing so would 2589conflict with explicit attributes already present on the function (e.g. the 2590ones that control inlining). 2591 2592.. code-block:: c++ 2593 2594 #pragma clang optimize off 2595 // This function will be decorated with optnone. 2596 int foo() { 2597 // ... code 2598 } 2599 2600 // optnone conflicts with always_inline, so bar() will not be decorated. 2601 __attribute__((always_inline)) int bar() { 2602 // ... code 2603 } 2604 #pragma clang optimize on 2605 2606If no ``on`` is found to close an ``off`` region, the end of the region is the 2607end of the compilation unit. 2608 2609Note that a stray ``#pragma clang optimize on`` does not selectively enable 2610additional optimizations when compiling at low optimization levels. This feature 2611can only be used to selectively disable optimizations. 2612 2613The pragma has an effect on functions only at the point of their definition; for 2614function templates, this means that the state of the pragma at the point of an 2615instantiation is not necessarily relevant. Consider the following example: 2616 2617.. code-block:: c++ 2618 2619 template<typename T> T twice(T t) { 2620 return 2 * t; 2621 } 2622 2623 #pragma clang optimize off 2624 template<typename T> T thrice(T t) { 2625 return 3 * t; 2626 } 2627 2628 int container(int a, int b) { 2629 return twice(a) + thrice(b); 2630 } 2631 #pragma clang optimize on 2632 2633In this example, the definition of the template function ``twice`` is outside 2634the pragma region, whereas the definition of ``thrice`` is inside the region. 2635The ``container`` function is also in the region and will not be optimized, but 2636it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of 2637these two instantiations, ``twice`` will be optimized (because its definition 2638was outside the region) and ``thrice`` will not be optimized. 2639 2640Extensions for loop hint optimizations 2641====================================== 2642 2643The ``#pragma clang loop`` directive is used to specify hints for optimizing the 2644subsequent for, while, do-while, or c++11 range-based for loop. The directive 2645provides options for vectorization, interleaving, unrolling and 2646distribution. Loop hints can be specified before any loop and will be ignored if 2647the optimization is not safe to apply. 2648 2649Vectorization and Interleaving 2650------------------------------ 2651 2652A vectorized loop performs multiple iterations of the original loop 2653in parallel using vector instructions. The instruction set of the target 2654processor determines which vector instructions are available and their vector 2655widths. This restricts the types of loops that can be vectorized. The vectorizer 2656automatically determines if the loop is safe and profitable to vectorize. A 2657vector instruction cost model is used to select the vector width. 2658 2659Interleaving multiple loop iterations allows modern processors to further 2660improve instruction-level parallelism (ILP) using advanced hardware features, 2661such as multiple execution units and out-of-order execution. The vectorizer uses 2662a cost model that depends on the register pressure and generated code size to 2663select the interleaving count. 2664 2665Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled 2666by ``interleave(enable)``. This is useful when compiling with ``-Os`` to 2667manually enable vectorization or interleaving. 2668 2669.. code-block:: c++ 2670 2671 #pragma clang loop vectorize(enable) 2672 #pragma clang loop interleave(enable) 2673 for(...) { 2674 ... 2675 } 2676 2677The vector width is specified by ``vectorize_width(_value_)`` and the interleave 2678count is specified by ``interleave_count(_value_)``, where 2679_value_ is a positive integer. This is useful for specifying the optimal 2680width/count of the set of target architectures supported by your application. 2681 2682.. code-block:: c++ 2683 2684 #pragma clang loop vectorize_width(2) 2685 #pragma clang loop interleave_count(2) 2686 for(...) { 2687 ... 2688 } 2689 2690Specifying a width/count of 1 disables the optimization, and is equivalent to 2691``vectorize(disable)`` or ``interleave(disable)``. 2692 2693Loop Unrolling 2694-------------- 2695 2696Unrolling a loop reduces the loop control overhead and exposes more 2697opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling 2698eliminates the loop and replaces it with an enumerated sequence of loop 2699iterations. Full unrolling is only possible if the loop trip count is known at 2700compile time. Partial unrolling replicates the loop body within the loop and 2701reduces the trip count. 2702 2703If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the 2704loop if the trip count is known at compile time. If the fully unrolled code size 2705is greater than an internal limit the loop will be partially unrolled up to this 2706limit. If the trip count is not known at compile time the loop will be partially 2707unrolled with a heuristically chosen unroll factor. 2708 2709.. code-block:: c++ 2710 2711 #pragma clang loop unroll(enable) 2712 for(...) { 2713 ... 2714 } 2715 2716If ``unroll(full)`` is specified the unroller will attempt to fully unroll the 2717loop if the trip count is known at compile time identically to 2718``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled 2719if the loop count is not known at compile time. 2720 2721.. code-block:: c++ 2722 2723 #pragma clang loop unroll(full) 2724 for(...) { 2725 ... 2726 } 2727 2728The unroll count can be specified explicitly with ``unroll_count(_value_)`` where 2729_value_ is a positive integer. If this value is greater than the trip count the 2730loop will be fully unrolled. Otherwise the loop is partially unrolled subject 2731to the same code size limit as with ``unroll(enable)``. 2732 2733.. code-block:: c++ 2734 2735 #pragma clang loop unroll_count(8) 2736 for(...) { 2737 ... 2738 } 2739 2740Unrolling of a loop can be prevented by specifying ``unroll(disable)``. 2741 2742Loop Distribution 2743----------------- 2744 2745Loop Distribution allows splitting a loop into multiple loops. This is 2746beneficial for example when the entire loop cannot be vectorized but some of the 2747resulting loops can. 2748 2749If ``distribute(enable))`` is specified and the loop has memory dependencies 2750that inhibit vectorization, the compiler will attempt to isolate the offending 2751operations into a new loop. This optimization is not enabled by default, only 2752loops marked with the pragma are considered. 2753 2754.. code-block:: c++ 2755 2756 #pragma clang loop distribute(enable) 2757 for (i = 0; i < N; ++i) { 2758 S1: A[i + 1] = A[i] + B[i]; 2759 S2: C[i] = D[i] * E[i]; 2760 } 2761 2762This loop will be split into two loops between statements S1 and S2. The 2763second loop containing S2 will be vectorized. 2764 2765Loop Distribution is currently not enabled by default in the optimizer because 2766it can hurt performance in some cases. For example, instruction-level 2767parallelism could be reduced by sequentializing the execution of the 2768statements S1 and S2 above. 2769 2770If Loop Distribution is turned on globally with 2771``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can 2772be used the disable it on a per-loop basis. 2773 2774Additional Information 2775---------------------- 2776 2777For convenience multiple loop hints can be specified on a single line. 2778 2779.. code-block:: c++ 2780 2781 #pragma clang loop vectorize_width(4) interleave_count(8) 2782 for(...) { 2783 ... 2784 } 2785 2786If an optimization cannot be applied any hints that apply to it will be ignored. 2787For example, the hint ``vectorize_width(4)`` is ignored if the loop is not 2788proven safe to vectorize. To identify and diagnose optimization issues use 2789`-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the 2790user guide for details. 2791 2792Extensions to specify floating-point flags 2793==================================================== 2794 2795The ``#pragma clang fp`` pragma allows floating-point options to be specified 2796for a section of the source code. This pragma can only appear at file scope or 2797at the start of a compound statement (excluding comments). When using within a 2798compound statement, the pragma is active within the scope of the compound 2799statement. 2800 2801Currently, only FP contraction can be controlled with the pragma. ``#pragma 2802clang fp contract`` specifies whether the compiler should contract a multiply 2803and an addition (or subtraction) into a fused FMA operation when supported by 2804the target. 2805 2806The pragma can take three values: ``on``, ``fast`` and ``off``. The ``on`` 2807option is identical to using ``#pragma STDC FP_CONTRACT(ON)`` and it allows 2808fusion as specified the language standard. The ``fast`` option allows fusiong 2809in cases when the language standard does not make this possible (e.g. across 2810statements in C) 2811 2812.. code-block:: c++ 2813 2814 for(...) { 2815 #pragma clang fp contract(fast) 2816 a = b[i] * c[i]; 2817 d[i] += a; 2818 } 2819 2820 2821The pragma can also be used with ``off`` which turns FP contraction off for a 2822section of the code. This can be useful when fast contraction is otherwise 2823enabled for the translation unit with the ``-ffp-contract=fast`` flag. 2824 2825Specifying an attribute for multiple declarations (#pragma clang attribute) 2826=========================================================================== 2827 2828The ``#pragma clang attribute`` directive can be used to apply an attribute to 2829multiple declarations. The ``#pragma clang attribute push`` variation of the 2830directive pushes a new "scope" of ``#pragma clang attribute`` that attributes 2831can be added to. The ``#pragma clang attribute (...)`` variation adds an 2832attribute to that scope, and the ``#pragma clang attribute pop`` variation pops 2833the scope. You can also use ``#pragma clang attribute push (...)``, which is a 2834shorthand for when you want to add one attribute to a new scope. Multiple push 2835directives can be nested inside each other. 2836 2837The attributes that are used in the ``#pragma clang attribute`` directives 2838can be written using the GNU-style syntax: 2839 2840.. code-block:: c++ 2841 2842 #pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function) 2843 2844 void function(); // The function now has the annotate("custom") attribute 2845 2846 #pragma clang attribute pop 2847 2848The attributes can also be written using the C++11 style syntax: 2849 2850.. code-block:: c++ 2851 2852 #pragma clang attribute push ([[noreturn]], apply_to = function) 2853 2854 void function(); // The function now has the [[noreturn]] attribute 2855 2856 #pragma clang attribute pop 2857 2858The ``__declspec`` style syntax is also supported: 2859 2860.. code-block:: c++ 2861 2862 #pragma clang attribute push (__declspec(dllexport), apply_to = function) 2863 2864 void function(); // The function now has the __declspec(dllexport) attribute 2865 2866 #pragma clang attribute pop 2867 2868A single push directive accepts only one attribute regardless of the syntax 2869used. 2870 2871Because multiple push directives can be nested, if you're writing a macro that 2872expands to ``_Pragma("clang attribute")`` it's good hygiene (though not 2873required) to add a namespace to your push/pop directives. A pop directive with a 2874namespace will pop the innermost push that has that same namespace. This will 2875ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note 2876that an ``pop`` without a namespace will pop the innermost ``push`` without a 2877namespace. ``push``es with a namespace can only be popped by ``pop`` with the 2878same namespace. For instance: 2879 2880.. code-block:: c++ 2881 2882 #define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)") 2883 #define ASSUME_NORETURN_END _Pragma("clang attribute AssumeNoreturn.pop") 2884 2885 #define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)") 2886 #define ASSUME_UNAVAILABLE_END _Pragma("clang attribute Unavailable.pop") 2887 2888 2889 ASSUME_NORETURN_BEGIN 2890 ASSUME_UNAVAILABLE_BEGIN 2891 void function(); // function has [[noreturn]] and __attribute__((unavailable)) 2892 ASSUME_NORETURN_END 2893 void other_function(); // function has __attribute__((unavailable)) 2894 ASSUME_UNAVAILABLE_END 2895 2896Without the namespaces on the macros, ``other_function`` will be annotated with 2897``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like 2898a contrived example, but its very possible for this kind of situation to appear 2899in real code if the pragmas are spread out across a large file. You can test if 2900your version of clang supports namespaces on ``#pragma clang attribute`` with 2901``__has_extension(pragma_clang_attribute_namespaces)``. 2902 2903Subject Match Rules 2904------------------- 2905 2906The set of declarations that receive a single attribute from the attribute stack 2907depends on the subject match rules that were specified in the pragma. Subject 2908match rules are specified after the attribute. The compiler expects an 2909identifier that corresponds to the subject set specifier. The ``apply_to`` 2910specifier is currently the only supported subject set specifier. It allows you 2911to specify match rules that form a subset of the attribute's allowed subject 2912set, i.e. the compiler doesn't require all of the attribute's subjects. For 2913example, an attribute like ``[[nodiscard]]`` whose subject set includes 2914``enum``, ``record`` and ``hasType(functionType)``, requires the presence of at 2915least one of these rules after ``apply_to``: 2916 2917.. code-block:: c++ 2918 2919 #pragma clang attribute push([[nodiscard]], apply_to = enum) 2920 2921 enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]] 2922 2923 struct Record1 { }; // The struct will *not* receive [[nodiscard]] 2924 2925 #pragma clang attribute pop 2926 2927 #pragma clang attribute push([[nodiscard]], apply_to = any(record, enum)) 2928 2929 enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]] 2930 2931 struct Record2 { }; // The struct *will* receive [[nodiscard]] 2932 2933 #pragma clang attribute pop 2934 2935 // This is an error, since [[nodiscard]] can't be applied to namespaces: 2936 #pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace)) 2937 2938 #pragma clang attribute pop 2939 2940Multiple match rules can be specified using the ``any`` match rule, as shown 2941in the example above. The ``any`` rule applies attributes to all declarations 2942that are matched by at least one of the rules in the ``any``. It doesn't nest 2943and can't be used inside the other match rules. Redundant match rules or rules 2944that conflict with one another should not be used inside of ``any``. 2945 2946Clang supports the following match rules: 2947 2948- ``function``: Can be used to apply attributes to functions. This includes C++ 2949 member functions, static functions, operators, and constructors/destructors. 2950 2951- ``function(is_member)``: Can be used to apply attributes to C++ member 2952 functions. This includes members like static functions, operators, and 2953 constructors/destructors. 2954 2955- ``hasType(functionType)``: Can be used to apply attributes to functions, C++ 2956 member functions, and variables/fields whose type is a function pointer. It 2957 does not apply attributes to Objective-C methods or blocks. 2958 2959- ``type_alias``: Can be used to apply attributes to ``typedef`` declarations 2960 and C++11 type aliases. 2961 2962- ``record``: Can be used to apply attributes to ``struct``, ``class``, and 2963 ``union`` declarations. 2964 2965- ``record(unless(is_union))``: Can be used to apply attributes only to 2966 ``struct`` and ``class`` declarations. 2967 2968- ``enum``: Can be be used to apply attributes to enumeration declarations. 2969 2970- ``enum_constant``: Can be used to apply attributes to enumerators. 2971 2972- ``variable``: Can be used to apply attributes to variables, including 2973 local variables, parameters, global variables, and static member variables. 2974 It does not apply attributes to instance member variables or Objective-C 2975 ivars. 2976 2977- ``variable(is_thread_local)``: Can be used to apply attributes to thread-local 2978 variables only. 2979 2980- ``variable(is_global)``: Can be used to apply attributes to global variables 2981 only. 2982 2983- ``variable(is_parameter)``: Can be used to apply attributes to parameters 2984 only. 2985 2986- ``variable(unless(is_parameter))``: Can be used to apply attributes to all 2987 the variables that are not parameters. 2988 2989- ``field``: Can be used to apply attributes to non-static member variables 2990 in a record. This includes Objective-C ivars. 2991 2992- ``namespace``: Can be used to apply attributes to ``namespace`` declarations. 2993 2994- ``objc_interface``: Can be used to apply attributes to ``@interface`` 2995 declarations. 2996 2997- ``objc_protocol``: Can be used to apply attributes to ``@protocol`` 2998 declarations. 2999 3000- ``objc_category``: Can be used to apply attributes to category declarations, 3001 including class extensions. 3002 3003- ``objc_method``: Can be used to apply attributes to Objective-C methods, 3004 including instance and class methods. Implicit methods like implicit property 3005 getters and setters do not receive the attribute. 3006 3007- ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C 3008 instance methods. 3009 3010- ``objc_property``: Can be used to apply attributes to ``@property`` 3011 declarations. 3012 3013- ``block``: Can be used to apply attributes to block declarations. This does 3014 not include variables/fields of block pointer type. 3015 3016The use of ``unless`` in match rules is currently restricted to a strict set of 3017sub-rules that are used by the supported attributes. That means that even though 3018``variable(unless(is_parameter))`` is a valid match rule, 3019``variable(unless(is_thread_local))`` is not. 3020 3021Supported Attributes 3022-------------------- 3023 3024Not all attributes can be used with the ``#pragma clang attribute`` directive. 3025Notably, statement attributes like ``[[fallthrough]]`` or type attributes 3026like ``address_space`` aren't supported by this directive. You can determine 3027whether or not an attribute is supported by the pragma by referring to the 3028:doc:`individual documentation for that attribute <AttributeReference>`. 3029 3030The attributes are applied to all matching declarations individually, even when 3031the attribute is semantically incorrect. The attributes that aren't applied to 3032any declaration are not verified semantically. 3033 3034Specifying section names for global objects (#pragma clang section) 3035=================================================================== 3036 3037The ``#pragma clang section`` directive provides a means to assign section-names 3038to global variables, functions and static variables. 3039 3040The section names can be specified as: 3041 3042.. code-block:: c++ 3043 3044 #pragma clang section bss="myBSS" data="myData" rodata="myRodata" text="myText" 3045 3046The section names can be reverted back to default name by supplying an empty 3047string to the section kind, for example: 3048 3049.. code-block:: c++ 3050 3051 #pragma clang section bss="" data="" text="" rodata="" 3052 3053The ``#pragma clang section`` directive obeys the following rules: 3054 3055* The pragma applies to all global variable, statics and function declarations 3056 from the pragma to the end of the translation unit. 3057 3058* The pragma clang section is enabled automatically, without need of any flags. 3059 3060* This feature is only defined to work sensibly for ELF targets. 3061 3062* If section name is specified through _attribute_((section("myname"))), then 3063 the attribute name gains precedence. 3064 3065* Global variables that are initialized to zero will be placed in the named 3066 bss section, if one is present. 3067 3068* The ``#pragma clang section`` directive does not does try to infer section-kind 3069 from the name. For example, naming a section "``.bss.mySec``" does NOT mean 3070 it will be a bss section name. 3071 3072* The decision about which section-kind applies to each global is taken in the back-end. 3073 Once the section-kind is known, appropriate section name, as specified by the user using 3074 ``#pragma clang section`` directive, is applied to that global. 3075 3076Specifying Linker Options on ELF Targets 3077======================================== 3078 3079The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets. 3080The second parameter is the library name (without the traditional Unix prefix of 3081``lib``). This allows you to provide an implicit link of dependent libraries. 3082 3083Evaluating Object Size Dynamically 3084================================== 3085 3086Clang supports the builtin ``__builtin_dynamic_object_size``, the semantics are 3087the same as GCC's ``__builtin_object_size`` (which Clang also supports), but 3088``__builtin_dynamic_object_size`` can evaluate the object's size at runtime. 3089``__builtin_dynamic_object_size`` is meant to be used as a drop-in replacement 3090for ``__builtin_object_size`` in libraries that support it. 3091 3092For instance, here is a program that ``__builtin_dynamic_object_size`` will make 3093safer: 3094 3095.. code-block:: c 3096 3097 void copy_into_buffer(size_t size) { 3098 char* buffer = malloc(size); 3099 strlcpy(buffer, "some string", strlen("some string")); 3100 // Previous line preprocesses to: 3101 // __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buffer, 0)) 3102 } 3103 3104Since the size of ``buffer`` can't be known at compile time, Clang will fold 3105``__builtin_object_size(buffer, 0)`` into ``-1``. However, if this was written 3106as ``__builtin_dynamic_object_size(buffer, 0)``, Clang will fold it into 3107``size``, providing some extra runtime safety. 3108