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