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<http://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 backwards compatibility reasons, ``__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_attribute`` 113------------------- 114 115This function-like macro takes a single identifier argument that is the name of 116an attribute. It evaluates to 1 if the attribute is supported or 0 if not. It 117can be used like this: 118 119.. code-block:: c++ 120 121 #ifndef __has_attribute // Optional of course. 122 #define __has_attribute(x) 0 // Compatibility with non-clang compilers. 123 #endif 124 125 ... 126 #if __has_attribute(always_inline) 127 #define ALWAYS_INLINE __attribute__((always_inline)) 128 #else 129 #define ALWAYS_INLINE 130 #endif 131 ... 132 133The attribute name can also be specified with a preceding and following ``__`` 134(double underscore) to avoid interference from a macro with the same name. For 135instance, ``__always_inline__`` can be used instead of ``always_inline``. 136 137Include File Checking Macros 138============================ 139 140Not all developments systems have the same include files. The 141:ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow 142you to check for the existence of an include file before doing a possibly 143failing ``#include`` directive. Include file checking macros must be used 144as expressions in ``#if`` or ``#elif`` preprocessing directives. 145 146.. _langext-__has_include: 147 148``__has_include`` 149----------------- 150 151This function-like macro takes a single file name string argument that is the 152name of an include file. It evaluates to 1 if the file can be found using the 153include paths, or 0 otherwise: 154 155.. code-block:: c++ 156 157 // Note the two possible file name string formats. 158 #if __has_include("myinclude.h") && __has_include(<stdint.h>) 159 # include "myinclude.h" 160 #endif 161 162 // To avoid problem with non-clang compilers not having this macro. 163 #if defined(__has_include) && __has_include("myinclude.h") 164 # include "myinclude.h" 165 #endif 166 167To test for this feature, use ``#if defined(__has_include)``. 168 169.. _langext-__has_include_next: 170 171``__has_include_next`` 172---------------------- 173 174This function-like macro takes a single file name string argument that is the 175name of an include file. It is like ``__has_include`` except that it looks for 176the second instance of the given file found in the include paths. It evaluates 177to 1 if the second instance of the file can be found using the include paths, 178or 0 otherwise: 179 180.. code-block:: c++ 181 182 // Note the two possible file name string formats. 183 #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>) 184 # include_next "myinclude.h" 185 #endif 186 187 // To avoid problem with non-clang compilers not having this macro. 188 #if defined(__has_include_next) && __has_include_next("myinclude.h") 189 # include_next "myinclude.h" 190 #endif 191 192Note that ``__has_include_next``, like the GNU extension ``#include_next`` 193directive, is intended for use in headers only, and will issue a warning if 194used in the top-level compilation file. A warning will also be issued if an 195absolute path is used in the file argument. 196 197``__has_warning`` 198----------------- 199 200This function-like macro takes a string literal that represents a command line 201option for a warning and returns true if that is a valid warning option. 202 203.. code-block:: c++ 204 205 #if __has_warning("-Wformat") 206 ... 207 #endif 208 209Builtin Macros 210============== 211 212``__BASE_FILE__`` 213 Defined to a string that contains the name of the main input file passed to 214 Clang. 215 216``__COUNTER__`` 217 Defined to an integer value that starts at zero and is incremented each time 218 the ``__COUNTER__`` macro is expanded. 219 220``__INCLUDE_LEVEL__`` 221 Defined to an integral value that is the include depth of the file currently 222 being translated. For the main file, this value is zero. 223 224``__TIMESTAMP__`` 225 Defined to the date and time of the last modification of the current source 226 file. 227 228``__clang__`` 229 Defined when compiling with Clang 230 231``__clang_major__`` 232 Defined to the major marketing version number of Clang (e.g., the 2 in 233 2.0.1). Note that marketing version numbers should not be used to check for 234 language features, as different vendors use different numbering schemes. 235 Instead, use the :ref:`langext-feature_check`. 236 237``__clang_minor__`` 238 Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note 239 that marketing version numbers should not be used to check for language 240 features, as different vendors use different numbering schemes. Instead, use 241 the :ref:`langext-feature_check`. 242 243``__clang_patchlevel__`` 244 Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1). 245 246``__clang_version__`` 247 Defined to a string that captures the Clang marketing version, including the 248 Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``". 249 250.. _langext-vectors: 251 252Vectors and Extended Vectors 253============================ 254 255Supports the GCC, OpenCL, AltiVec and NEON vector extensions. 256 257OpenCL vector types are created using ``ext_vector_type`` attribute. It 258support for ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example 259is: 260 261.. code-block:: c++ 262 263 typedef float float4 __attribute__((ext_vector_type(4))); 264 typedef float float2 __attribute__((ext_vector_type(2))); 265 266 float4 foo(float2 a, float2 b) { 267 float4 c; 268 c.xz = a; 269 c.yw = b; 270 return c; 271 } 272 273Query for this feature with ``__has_extension(attribute_ext_vector_type)``. 274 275Giving ``-faltivec`` option to clang enables support for AltiVec vector syntax 276and functions. For example: 277 278.. code-block:: c++ 279 280 vector float foo(vector int a) { 281 vector int b; 282 b = vec_add(a, a) + a; 283 return (vector float)b; 284 } 285 286NEON vector types are created using ``neon_vector_type`` and 287``neon_polyvector_type`` attributes. For example: 288 289.. code-block:: c++ 290 291 typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t; 292 typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t; 293 294 int8x8_t foo(int8x8_t a) { 295 int8x8_t v; 296 v = a; 297 return v; 298 } 299 300Vector Literals 301--------------- 302 303Vector literals can be used to create vectors from a set of scalars, or 304vectors. Either parentheses or braces form can be used. In the parentheses 305form the number of literal values specified must be one, i.e. referring to a 306scalar value, or must match the size of the vector type being created. If a 307single scalar literal value is specified, the scalar literal value will be 308replicated to all the components of the vector type. In the brackets form any 309number of literals can be specified. For example: 310 311.. code-block:: c++ 312 313 typedef int v4si __attribute__((__vector_size__(16))); 314 typedef float float4 __attribute__((ext_vector_type(4))); 315 typedef float float2 __attribute__((ext_vector_type(2))); 316 317 v4si vsi = (v4si){1, 2, 3, 4}; 318 float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f); 319 vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1). 320 vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0). 321 vector int vi3 = (vector int)(1, 2); // error 322 vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0). 323 vector int vi5 = (vector int)(1, 2, 3, 4); 324 float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f)); 325 326Vector Operations 327----------------- 328 329The table below shows the support for each operation by vector extension. A 330dash indicates that an operation is not accepted according to a corresponding 331specification. 332 333============================== ====== ======= === ==== 334 Opeator OpenCL AltiVec GCC NEON 335============================== ====== ======= === ==== 336[] yes yes yes -- 337unary operators +, -- yes yes yes -- 338++, -- -- yes yes yes -- 339+,--,*,/,% yes yes yes -- 340bitwise operators &,|,^,~ yes yes yes -- 341>>,<< yes yes yes -- 342!, &&, || no -- -- -- 343==, !=, >, <, >=, <= yes yes -- -- 344= yes yes yes yes 345:? yes -- -- -- 346sizeof yes yes yes yes 347============================== ====== ======= === ==== 348 349See also :ref:`langext-__builtin_shufflevector`. 350 351Messages on ``deprecated`` and ``unavailable`` Attributes 352========================================================= 353 354An optional string message can be added to the ``deprecated`` and 355``unavailable`` attributes. For example: 356 357.. code-block:: c++ 358 359 void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!"))); 360 361If the deprecated or unavailable declaration is used, the message will be 362incorporated into the appropriate diagnostic: 363 364.. code-block:: c++ 365 366 harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!! 367 [-Wdeprecated-declarations] 368 explode(); 369 ^ 370 371Query for this feature with 372``__has_extension(attribute_deprecated_with_message)`` and 373``__has_extension(attribute_unavailable_with_message)``. 374 375Attributes on Enumerators 376========================= 377 378Clang allows attributes to be written on individual enumerators. This allows 379enumerators to be deprecated, made unavailable, etc. The attribute must appear 380after the enumerator name and before any initializer, like so: 381 382.. code-block:: c++ 383 384 enum OperationMode { 385 OM_Invalid, 386 OM_Normal, 387 OM_Terrified __attribute__((deprecated)), 388 OM_AbortOnError __attribute__((deprecated)) = 4 389 }; 390 391Attributes on the ``enum`` declaration do not apply to individual enumerators. 392 393Query for this feature with ``__has_extension(enumerator_attributes)``. 394 395'User-Specified' System Frameworks 396================================== 397 398Clang provides a mechanism by which frameworks can be built in such a way that 399they will always be treated as being "system frameworks", even if they are not 400present in a system framework directory. This can be useful to system 401framework developers who want to be able to test building other applications 402with development builds of their framework, including the manner in which the 403compiler changes warning behavior for system headers. 404 405Framework developers can opt-in to this mechanism by creating a 406"``.system_framework``" file at the top-level of their framework. That is, the 407framework should have contents like: 408 409.. code-block:: none 410 411 .../TestFramework.framework 412 .../TestFramework.framework/.system_framework 413 .../TestFramework.framework/Headers 414 .../TestFramework.framework/Headers/TestFramework.h 415 ... 416 417Clang will treat the presence of this file as an indicator that the framework 418should be treated as a system framework, regardless of how it was found in the 419framework search path. For consistency, we recommend that such files never be 420included in installed versions of the framework. 421 422Availability attribute 423====================== 424 425Clang introduces the ``availability`` attribute, which can be placed on 426declarations to describe the lifecycle of that declaration relative to 427operating system versions. Consider the function declaration for a 428hypothetical function ``f``: 429 430.. code-block:: c++ 431 432 void f(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.6,obsoleted=10.7))); 433 434The availability attribute states that ``f`` was introduced in Mac OS X 10.4, 435deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7. This information 436is used by Clang to determine when it is safe to use ``f``: for example, if 437Clang is instructed to compile code for Mac OS X 10.5, a call to ``f()`` 438succeeds. If Clang is instructed to compile code for Mac OS X 10.6, the call 439succeeds but Clang emits a warning specifying that the function is deprecated. 440Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call 441fails because ``f()`` is no longer available. 442 443The availability attribute is a comma-separated list starting with the 444platform name and then including clauses specifying important milestones in the 445declaration's lifetime (in any order) along with additional information. Those 446clauses can be: 447 448introduced=\ *version* 449 The first version in which this declaration was introduced. 450 451deprecated=\ *version* 452 The first version in which this declaration was deprecated, meaning that 453 users should migrate away from this API. 454 455obsoleted=\ *version* 456 The first version in which this declaration was obsoleted, meaning that it 457 was removed completely and can no longer be used. 458 459unavailable 460 This declaration is never available on this platform. 461 462message=\ *string-literal* 463 Additional message text that Clang will provide when emitting a warning or 464 error about use of a deprecated or obsoleted declaration. Useful to direct 465 users to replacement APIs. 466 467Multiple availability attributes can be placed on a declaration, which may 468correspond to different platforms. Only the availability attribute with the 469platform corresponding to the target platform will be used; any others will be 470ignored. If no availability attribute specifies availability for the current 471target platform, the availability attributes are ignored. Supported platforms 472are: 473 474``ios`` 475 Apple's iOS operating system. The minimum deployment target is specified by 476 the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*`` 477 command-line arguments. 478 479``macosx`` 480 Apple's Mac OS X operating system. The minimum deployment target is 481 specified by the ``-mmacosx-version-min=*version*`` command-line argument. 482 483A declaration can be used even when deploying back to a platform version prior 484to when the declaration was introduced. When this happens, the declaration is 485`weakly linked 486<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_, 487as if the ``weak_import`` attribute were added to the declaration. A 488weakly-linked declaration may or may not be present a run-time, and a program 489can determine whether the declaration is present by checking whether the 490address of that declaration is non-NULL. 491 492If there are multiple declarations of the same entity, the availability 493attributes must either match on a per-platform basis or later 494declarations must not have availability attributes for that 495platform. For example: 496 497.. code-block:: c 498 499 void g(void) __attribute__((availability(macosx,introduced=10.4))); 500 void g(void) __attribute__((availability(macosx,introduced=10.4))); // okay, matches 501 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform 502 void g(void); // okay, inherits both macosx and ios availability from above. 503 void g(void) __attribute__((availability(macosx,introduced=10.5))); // error: mismatch 504 505When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,: 506 507.. code-block:: objc 508 509 @interface A 510 - (id)method __attribute__((availability(macosx,introduced=10.4))); 511 - (id)method2 __attribute__((availability(macosx,introduced=10.4))); 512 @end 513 514 @interface B : A 515 - (id)method __attribute__((availability(macosx,introduced=10.3))); // okay: method moved into base class later 516 - (id)method __attribute__((availability(macosx,introduced=10.5))); // error: this method was available via the base class in 10.4 517 @end 518 519Checks for Standard Language Features 520===================================== 521 522The ``__has_feature`` macro can be used to query if certain standard language 523features are enabled. The ``__has_extension`` macro can be used to query if 524language features are available as an extension when compiling for a standard 525which does not provide them. The features which can be tested are listed here. 526 527C++98 528----- 529 530The features listed below are part of the C++98 standard. These features are 531enabled by default when compiling C++ code. 532 533C++ exceptions 534^^^^^^^^^^^^^^ 535 536Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been 537enabled. For example, compiling code with ``-fno-exceptions`` disables C++ 538exceptions. 539 540C++ RTTI 541^^^^^^^^ 542 543Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For 544example, compiling code with ``-fno-rtti`` disables the use of RTTI. 545 546C++11 547----- 548 549The features listed below are part of the C++11 standard. As a result, all 550these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option 551when compiling C++ code. 552 553C++11 SFINAE includes access control 554^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 555 556Use ``__has_feature(cxx_access_control_sfinae)`` or 557``__has_extension(cxx_access_control_sfinae)`` to determine whether 558access-control errors (e.g., calling a private constructor) are considered to 559be template argument deduction errors (aka SFINAE errors), per `C++ DR1170 560<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_. 561 562C++11 alias templates 563^^^^^^^^^^^^^^^^^^^^^ 564 565Use ``__has_feature(cxx_alias_templates)`` or 566``__has_extension(cxx_alias_templates)`` to determine if support for C++11's 567alias declarations and alias templates is enabled. 568 569C++11 alignment specifiers 570^^^^^^^^^^^^^^^^^^^^^^^^^^ 571 572Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to 573determine if support for alignment specifiers using ``alignas`` is enabled. 574 575C++11 attributes 576^^^^^^^^^^^^^^^^ 577 578Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to 579determine if support for attribute parsing with C++11's square bracket notation 580is enabled. 581 582C++11 generalized constant expressions 583^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 584 585Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized 586constant expressions (e.g., ``constexpr``) is enabled. 587 588C++11 ``decltype()`` 589^^^^^^^^^^^^^^^^^^^^ 590 591Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to 592determine if support for the ``decltype()`` specifier is enabled. C++11's 593``decltype`` does not require type-completeness of a function call expression. 594Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or 595``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if 596support for this feature is enabled. 597 598C++11 default template arguments in function templates 599^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 600 601Use ``__has_feature(cxx_default_function_template_args)`` or 602``__has_extension(cxx_default_function_template_args)`` to determine if support 603for default template arguments in function templates is enabled. 604 605C++11 ``default``\ ed functions 606^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 607 608Use ``__has_feature(cxx_defaulted_functions)`` or 609``__has_extension(cxx_defaulted_functions)`` to determine if support for 610defaulted function definitions (with ``= default``) is enabled. 611 612C++11 delegating constructors 613^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 614 615Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for 616delegating constructors is enabled. 617 618C++11 ``deleted`` functions 619^^^^^^^^^^^^^^^^^^^^^^^^^^^ 620 621Use ``__has_feature(cxx_deleted_functions)`` or 622``__has_extension(cxx_deleted_functions)`` to determine if support for deleted 623function definitions (with ``= delete``) is enabled. 624 625C++11 explicit conversion functions 626^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 627 628Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for 629``explicit`` conversion functions is enabled. 630 631C++11 generalized initializers 632^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 633 634Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for 635generalized initializers (using braced lists and ``std::initializer_list``) is 636enabled. 637 638C++11 implicit move constructors/assignment operators 639^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 640 641Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly 642generate move constructors and move assignment operators where needed. 643 644C++11 inheriting constructors 645^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 646 647Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for 648inheriting constructors is enabled. 649 650C++11 inline namespaces 651^^^^^^^^^^^^^^^^^^^^^^^ 652 653Use ``__has_feature(cxx_inline_namespaces)`` or 654``__has_extension(cxx_inline_namespaces)`` to determine if support for inline 655namespaces is enabled. 656 657C++11 lambdas 658^^^^^^^^^^^^^ 659 660Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to 661determine if support for lambdas is enabled. 662 663C++11 local and unnamed types as template arguments 664^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 665 666Use ``__has_feature(cxx_local_type_template_args)`` or 667``__has_extension(cxx_local_type_template_args)`` to determine if support for 668local and unnamed types as template arguments is enabled. 669 670C++11 noexcept 671^^^^^^^^^^^^^^ 672 673Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to 674determine if support for noexcept exception specifications is enabled. 675 676C++11 in-class non-static data member initialization 677^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 678 679Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class 680initialization of non-static data members is enabled. 681 682C++11 ``nullptr`` 683^^^^^^^^^^^^^^^^^ 684 685Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to 686determine if support for ``nullptr`` is enabled. 687 688C++11 ``override control`` 689^^^^^^^^^^^^^^^^^^^^^^^^^^ 690 691Use ``__has_feature(cxx_override_control)`` or 692``__has_extension(cxx_override_control)`` to determine if support for the 693override control keywords is enabled. 694 695C++11 reference-qualified functions 696^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 697 698Use ``__has_feature(cxx_reference_qualified_functions)`` or 699``__has_extension(cxx_reference_qualified_functions)`` to determine if support 700for reference-qualified functions (e.g., member functions with ``&`` or ``&&`` 701applied to ``*this``) is enabled. 702 703C++11 range-based ``for`` loop 704^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 705 706Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to 707determine if support for the range-based for loop is enabled. 708 709C++11 raw string literals 710^^^^^^^^^^^^^^^^^^^^^^^^^ 711 712Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw 713string literals (e.g., ``R"x(foo\bar)x"``) is enabled. 714 715C++11 rvalue references 716^^^^^^^^^^^^^^^^^^^^^^^ 717 718Use ``__has_feature(cxx_rvalue_references)`` or 719``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue 720references is enabled. 721 722C++11 ``static_assert()`` 723^^^^^^^^^^^^^^^^^^^^^^^^^ 724 725Use ``__has_feature(cxx_static_assert)`` or 726``__has_extension(cxx_static_assert)`` to determine if support for compile-time 727assertions using ``static_assert`` is enabled. 728 729C++11 ``thread_local`` 730^^^^^^^^^^^^^^^^^^^^^^ 731 732Use ``__has_feature(cxx_thread_local)`` to determine if support for 733``thread_local`` variables is enabled. 734 735C++11 type inference 736^^^^^^^^^^^^^^^^^^^^ 737 738Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to 739determine C++11 type inference is supported using the ``auto`` specifier. If 740this is disabled, ``auto`` will instead be a storage class specifier, as in C 741or C++98. 742 743C++11 strongly typed enumerations 744^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 745 746Use ``__has_feature(cxx_strong_enums)`` or 747``__has_extension(cxx_strong_enums)`` to determine if support for strongly 748typed, scoped enumerations is enabled. 749 750C++11 trailing return type 751^^^^^^^^^^^^^^^^^^^^^^^^^^ 752 753Use ``__has_feature(cxx_trailing_return)`` or 754``__has_extension(cxx_trailing_return)`` to determine if support for the 755alternate function declaration syntax with trailing return type is enabled. 756 757C++11 Unicode string literals 758^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 759 760Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode 761string literals is enabled. 762 763C++11 unrestricted unions 764^^^^^^^^^^^^^^^^^^^^^^^^^ 765 766Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for 767unrestricted unions is enabled. 768 769C++11 user-defined literals 770^^^^^^^^^^^^^^^^^^^^^^^^^^^ 771 772Use ``__has_feature(cxx_user_literals)`` to determine if support for 773user-defined literals is enabled. 774 775C++11 variadic templates 776^^^^^^^^^^^^^^^^^^^^^^^^ 777 778Use ``__has_feature(cxx_variadic_templates)`` or 779``__has_extension(cxx_variadic_templates)`` to determine if support for 780variadic templates is enabled. 781 782C++1y 783----- 784 785The features listed below are part of the committee draft for the C++1y 786standard. As a result, all these features are enabled with the ``-std=c++1y`` 787or ``-std=gnu++1y`` option when compiling C++ code. 788 789C++1y binary literals 790^^^^^^^^^^^^^^^^^^^^^ 791 792Use ``__has_feature(cxx_binary_literals)`` or 793``__has_extension(cxx_binary_literals)`` to determine whether 794binary literals (for instance, ``0b10010``) are recognized. Clang supports this 795feature as an extension in all language modes. 796 797C++1y contextual conversions 798^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 799 800Use ``__has_feature(cxx_contextual_conversions)`` or 801``__has_extension(cxx_contextual_conversions)`` to determine if the C++1y rules 802are used when performing an implicit conversion for an array bound in a 803*new-expression*, the operand of a *delete-expression*, an integral constant 804expression, or a condition in a ``switch`` statement. Clang does not yet 805support this feature. 806 807C++1y decltype(auto) 808^^^^^^^^^^^^^^^^^^^^ 809 810Use ``__has_feature(cxx_decltype_auto)`` or 811``__has_extension(cxx_decltype_auto)`` to determine if support 812for the ``decltype(auto)`` placeholder type is enabled. 813 814C++1y default initializers for aggregates 815^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 816 817Use ``__has_feature(cxx_aggregate_nsdmi)`` or 818``__has_extension(cxx_aggregate_nsdmi)`` to determine if support 819for default initializers in aggregate members is enabled. 820 821C++1y generalized lambda capture 822^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 823 824Use ``__has_feature(cxx_generalized_capture)`` or 825``__has_extension(cxx_generalized_capture`` to determine if support for 826generalized lambda captures is enabled 827(for instance, ``[n(0)] { return ++n; }``). 828Clang does not yet support this feature. 829 830C++1y generic lambdas 831^^^^^^^^^^^^^^^^^^^^^ 832 833Use ``__has_feature(cxx_generic_lambda)`` or 834``__has_extension(cxx_generic_lambda)`` to determine if support for generic 835(polymorphic) lambdas is enabled 836(for instance, ``[] (auto x) { return x + 1; }``). 837Clang does not yet support this feature. 838 839C++1y relaxed constexpr 840^^^^^^^^^^^^^^^^^^^^^^^ 841 842Use ``__has_feature(cxx_relaxed_constexpr)`` or 843``__has_extension(cxx_relaxed_constexpr)`` to determine if variable 844declarations, local variable modification, and control flow constructs 845are permitted in ``constexpr`` functions. 846Clang's implementation of this feature is incomplete. 847 848C++1y return type deduction 849^^^^^^^^^^^^^^^^^^^^^^^^^^^ 850 851Use ``__has_feature(cxx_return_type_deduction)`` or 852``__has_extension(cxx_return_type_deduction)`` to determine if support 853for return type deduction for functions (using ``auto`` as a return type) 854is enabled. 855Clang's implementation of this feature is incomplete. 856 857C++1y runtime-sized arrays 858^^^^^^^^^^^^^^^^^^^^^^^^^^ 859 860Use ``__has_feature(cxx_runtime_array)`` or 861``__has_extension(cxx_runtime_array)`` to determine if support 862for arrays of runtime bound (a restricted form of variable-length arrays) 863is enabled. 864Clang's implementation of this feature is incomplete. 865 866C++1y variable templates 867^^^^^^^^^^^^^^^^^^^^^^^^ 868 869Use ``__has_feature(cxx_variable_templates)`` or 870``__has_extension(cxx_variable_templates)`` to determine if support for 871templated variable declarations is enabled. 872Clang does not yet support this feature. 873 874C11 875--- 876 877The features listed below are part of the C11 standard. As a result, all these 878features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when 879compiling C code. Additionally, because these features are all 880backward-compatible, they are available as extensions in all language modes. 881 882C11 alignment specifiers 883^^^^^^^^^^^^^^^^^^^^^^^^ 884 885Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine 886if support for alignment specifiers using ``_Alignas`` is enabled. 887 888C11 atomic operations 889^^^^^^^^^^^^^^^^^^^^^ 890 891Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine 892if support for atomic types using ``_Atomic`` is enabled. Clang also provides 893:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement 894the ``<stdatomic.h>`` operations on ``_Atomic`` types. 895 896C11 generic selections 897^^^^^^^^^^^^^^^^^^^^^^ 898 899Use ``__has_feature(c_generic_selections)`` or 900``__has_extension(c_generic_selections)`` to determine if support for generic 901selections is enabled. 902 903As an extension, the C11 generic selection expression is available in all 904languages supported by Clang. The syntax is the same as that given in the C11 905standard. 906 907In C, type compatibility is decided according to the rules given in the 908appropriate standard, but in C++, which lacks the type compatibility rules used 909in C, types are considered compatible only if they are equivalent. 910 911C11 ``_Static_assert()`` 912^^^^^^^^^^^^^^^^^^^^^^^^ 913 914Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)`` 915to determine if support for compile-time assertions using ``_Static_assert`` is 916enabled. 917 918C11 ``_Thread_local`` 919^^^^^^^^^^^^^^^^^^^^^ 920 921Use ``__has_feature(c_thread_local)`` to determine if support for 922``_Thread_local`` variables is enabled. 923 924Checks for Type Traits 925====================== 926 927Clang supports the `GNU C++ type traits 928<http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the 929`Microsoft Visual C++ Type traits 930<http://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_. For each 931supported type trait ``__X``, ``__has_extension(X)`` indicates the presence of 932the type trait. For example: 933 934.. code-block:: c++ 935 936 #if __has_extension(is_convertible_to) 937 template<typename From, typename To> 938 struct is_convertible_to { 939 static const bool value = __is_convertible_to(From, To); 940 }; 941 #else 942 // Emulate type trait 943 #endif 944 945The following type traits are supported by Clang: 946 947* ``__has_nothrow_assign`` (GNU, Microsoft) 948* ``__has_nothrow_copy`` (GNU, Microsoft) 949* ``__has_nothrow_constructor`` (GNU, Microsoft) 950* ``__has_trivial_assign`` (GNU, Microsoft) 951* ``__has_trivial_copy`` (GNU, Microsoft) 952* ``__has_trivial_constructor`` (GNU, Microsoft) 953* ``__has_trivial_destructor`` (GNU, Microsoft) 954* ``__has_virtual_destructor`` (GNU, Microsoft) 955* ``__is_abstract`` (GNU, Microsoft) 956* ``__is_base_of`` (GNU, Microsoft) 957* ``__is_class`` (GNU, Microsoft) 958* ``__is_convertible_to`` (Microsoft) 959* ``__is_empty`` (GNU, Microsoft) 960* ``__is_enum`` (GNU, Microsoft) 961* ``__is_interface_class`` (Microsoft) 962* ``__is_pod`` (GNU, Microsoft) 963* ``__is_polymorphic`` (GNU, Microsoft) 964* ``__is_union`` (GNU, Microsoft) 965* ``__is_literal(type)``: Determines whether the given type is a literal type 966* ``__is_final``: Determines whether the given type is declared with a 967 ``final`` class-virt-specifier. 968* ``__underlying_type(type)``: Retrieves the underlying type for a given 969 ``enum`` type. This trait is required to implement the C++11 standard 970 library. 971* ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value 972 of type ``totype`` can be assigned to from a value of type ``fromtype`` such 973 that no non-trivial functions are called as part of that assignment. This 974 trait is required to implement the C++11 standard library. 975* ``__is_trivially_constructible(type, argtypes...)``: Determines whether a 976 value of type ``type`` can be direct-initialized with arguments of types 977 ``argtypes...`` such that no non-trivial functions are called as part of 978 that initialization. This trait is required to implement the C++11 standard 979 library. 980 981Blocks 982====== 983 984The syntax and high level language feature description is in 985:doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for 986the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`. 987 988Query for this feature with ``__has_extension(blocks)``. 989 990Objective-C Features 991==================== 992 993Related result types 994-------------------- 995 996According to Cocoa conventions, Objective-C methods with certain names 997("``init``", "``alloc``", etc.) always return objects that are an instance of 998the receiving class's type. Such methods are said to have a "related result 999type", meaning that a message send to one of these methods will have the same 1000static type as an instance of the receiver class. For example, given the 1001following classes: 1002 1003.. code-block:: objc 1004 1005 @interface NSObject 1006 + (id)alloc; 1007 - (id)init; 1008 @end 1009 1010 @interface NSArray : NSObject 1011 @end 1012 1013and this common initialization pattern 1014 1015.. code-block:: objc 1016 1017 NSArray *array = [[NSArray alloc] init]; 1018 1019the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because 1020``alloc`` implicitly has a related result type. Similarly, the type of the 1021expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a 1022related result type and its receiver is known to have the type ``NSArray *``. 1023If neither ``alloc`` nor ``init`` had a related result type, the expressions 1024would have had type ``id``, as declared in the method signature. 1025 1026A method with a related result type can be declared by using the type 1027``instancetype`` as its result type. ``instancetype`` is a contextual keyword 1028that is only permitted in the result type of an Objective-C method, e.g. 1029 1030.. code-block:: objc 1031 1032 @interface A 1033 + (instancetype)constructAnA; 1034 @end 1035 1036The related result type can also be inferred for some methods. To determine 1037whether a method has an inferred related result type, the first word in the 1038camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered, 1039and the method will have a related result type if its return type is compatible 1040with the type of its class and if: 1041 1042* the first word is "``alloc``" or "``new``", and the method is a class method, 1043 or 1044 1045* the first word is "``autorelease``", "``init``", "``retain``", or "``self``", 1046 and the method is an instance method. 1047 1048If a method with a related result type is overridden by a subclass method, the 1049subclass method must also return a type that is compatible with the subclass 1050type. For example: 1051 1052.. code-block:: objc 1053 1054 @interface NSString : NSObject 1055 - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString 1056 @end 1057 1058Related result types only affect the type of a message send or property access 1059via the given method. In all other respects, a method with a related result 1060type is treated the same way as method that returns ``id``. 1061 1062Use ``__has_feature(objc_instancetype)`` to determine whether the 1063``instancetype`` contextual keyword is available. 1064 1065Automatic reference counting 1066---------------------------- 1067 1068Clang provides support for :doc:`automated reference counting 1069<AutomaticReferenceCounting>` in Objective-C, which eliminates the need 1070for manual ``retain``/``release``/``autorelease`` message sends. There are two 1071feature macros associated with automatic reference counting: 1072``__has_feature(objc_arc)`` indicates the availability of automated reference 1073counting in general, while ``__has_feature(objc_arc_weak)`` indicates that 1074automated reference counting also includes support for ``__weak`` pointers to 1075Objective-C objects. 1076 1077.. _objc-fixed-enum: 1078 1079Enumerations with a fixed underlying type 1080----------------------------------------- 1081 1082Clang provides support for C++11 enumerations with a fixed underlying type 1083within Objective-C. For example, one can write an enumeration type as: 1084 1085.. code-block:: c++ 1086 1087 typedef enum : unsigned char { Red, Green, Blue } Color; 1088 1089This specifies that the underlying type, which is used to store the enumeration 1090value, is ``unsigned char``. 1091 1092Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed 1093underlying types is available in Objective-C. 1094 1095Interoperability with C++11 lambdas 1096----------------------------------- 1097 1098Clang provides interoperability between C++11 lambdas and blocks-based APIs, by 1099permitting a lambda to be implicitly converted to a block pointer with the 1100corresponding signature. For example, consider an API such as ``NSArray``'s 1101array-sorting method: 1102 1103.. code-block:: objc 1104 1105 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr; 1106 1107``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult 1108(^)(id, id)``, and parameters of this type are generally provided with block 1109literals as arguments. However, one can also use a C++11 lambda so long as it 1110provides the same signature (in this case, accepting two parameters of type 1111``id`` and returning an ``NSComparisonResult``): 1112 1113.. code-block:: objc 1114 1115 NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11", 1116 @"String 02"]; 1117 const NSStringCompareOptions comparisonOptions 1118 = NSCaseInsensitiveSearch | NSNumericSearch | 1119 NSWidthInsensitiveSearch | NSForcedOrderingSearch; 1120 NSLocale *currentLocale = [NSLocale currentLocale]; 1121 NSArray *sorted 1122 = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult { 1123 NSRange string1Range = NSMakeRange(0, [s1 length]); 1124 return [s1 compare:s2 options:comparisonOptions 1125 range:string1Range locale:currentLocale]; 1126 }]; 1127 NSLog(@"sorted: %@", sorted); 1128 1129This code relies on an implicit conversion from the type of the lambda 1130expression (an unnamed, local class type called the *closure type*) to the 1131corresponding block pointer type. The conversion itself is expressed by a 1132conversion operator in that closure type that produces a block pointer with the 1133same signature as the lambda itself, e.g., 1134 1135.. code-block:: objc 1136 1137 operator NSComparisonResult (^)(id, id)() const; 1138 1139This conversion function returns a new block that simply forwards the two 1140parameters to the lambda object (which it captures by copy), then returns the 1141result. The returned block is first copied (with ``Block_copy``) and then 1142autoreleased. As an optimization, if a lambda expression is immediately 1143converted to a block pointer (as in the first example, above), then the block 1144is not copied and autoreleased: rather, it is given the same lifetime as a 1145block literal written at that point in the program, which avoids the overhead 1146of copying a block to the heap in the common case. 1147 1148The conversion from a lambda to a block pointer is only available in 1149Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory 1150management (autorelease). 1151 1152Object Literals and Subscripting 1153-------------------------------- 1154 1155Clang provides support for :doc:`Object Literals and Subscripting 1156<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C 1157programming patterns, makes programs more concise, and improves the safety of 1158container creation. There are several feature macros associated with object 1159literals and subscripting: ``__has_feature(objc_array_literals)`` tests the 1160availability of array literals; ``__has_feature(objc_dictionary_literals)`` 1161tests the availability of dictionary literals; 1162``__has_feature(objc_subscripting)`` tests the availability of object 1163subscripting. 1164 1165Objective-C Autosynthesis of Properties 1166--------------------------------------- 1167 1168Clang provides support for autosynthesis of declared properties. Using this 1169feature, clang provides default synthesis of those properties not declared 1170@dynamic and not having user provided backing getter and setter methods. 1171``__has_feature(objc_default_synthesize_properties)`` checks for availability 1172of this feature in version of clang being used. 1173 1174.. _langext-objc_method_family: 1175 1176The ``objc_method_family`` attribute 1177------------------------------------ 1178 1179Many methods in Objective-C have conventional meanings determined by their 1180selectors. It is sometimes useful to be able to mark a method as having a 1181particular conventional meaning despite not having the right selector, or as 1182not having the conventional meaning that its selector would suggest. For these 1183use cases, we provide an attribute to specifically describe the "method family" 1184that a method belongs to. 1185 1186**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of 1187``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This 1188attribute can only be placed at the end of a method declaration: 1189 1190.. code-block:: objc 1191 1192 - (NSString *)initMyStringValue __attribute__((objc_method_family(none))); 1193 1194Users who do not wish to change the conventional meaning of a method, and who 1195merely want to document its non-standard retain and release semantics, should 1196use the :ref:`retaining behavior attributes <langext-objc-retain-release>` 1197described below. 1198 1199Query for this feature with ``__has_attribute(objc_method_family)``. 1200 1201.. _langext-objc-retain-release: 1202 1203Objective-C retaining behavior attributes 1204----------------------------------------- 1205 1206In Objective-C, functions and methods are generally assumed to follow the 1207`Cocoa Memory Management 1208<http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_ 1209conventions for ownership of object arguments and 1210return values. However, there are exceptions, and so Clang provides attributes 1211to allow these exceptions to be documented. This are used by ARC and the 1212`static analyzer <http://clang-analyzer.llvm.org>`_ Some exceptions may be 1213better described using the :ref:`objc_method_family 1214<langext-objc_method_family>` attribute instead. 1215 1216**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``, 1217``ns_returns_autoreleased``, ``cf_returns_retained``, and 1218``cf_returns_not_retained`` attributes can be placed on methods and functions 1219that return Objective-C or CoreFoundation objects. They are commonly placed at 1220the end of a function prototype or method declaration: 1221 1222.. code-block:: objc 1223 1224 id foo() __attribute__((ns_returns_retained)); 1225 1226 - (NSString *)bar:(int)x __attribute__((ns_returns_retained)); 1227 1228The ``*_returns_retained`` attributes specify that the returned object has a +1 1229retain count. The ``*_returns_not_retained`` attributes specify that the return 1230object has a +0 retain count, even if the normal convention for its selector 1231would be +1. ``ns_returns_autoreleased`` specifies that the returned object is 1232+0, but is guaranteed to live at least as long as the next flush of an 1233autorelease pool. 1234 1235**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on 1236an parameter declaration; they specify that the argument is expected to have a 1237+1 retain count, which will be balanced in some way by the function or method. 1238The ``ns_consumes_self`` attribute can only be placed on an Objective-C 1239method; it specifies that the method expects its ``self`` parameter to have a 1240+1 retain count, which it will balance in some way. 1241 1242.. code-block:: objc 1243 1244 void foo(__attribute__((ns_consumed)) NSString *string); 1245 1246 - (void) bar __attribute__((ns_consumes_self)); 1247 - (void) baz:(id) __attribute__((ns_consumed)) x; 1248 1249Further examples of these attributes are available in the static analyzer's `list of annotations for analysis 1250<http://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_. 1251 1252Query for these features with ``__has_attribute(ns_consumed)``, 1253``__has_attribute(ns_returns_retained)``, etc. 1254 1255 1256Function Overloading in C 1257========================= 1258 1259Clang provides support for C++ function overloading in C. Function overloading 1260in C is introduced using the ``overloadable`` attribute. For example, one 1261might provide several overloaded versions of a ``tgsin`` function that invokes 1262the appropriate standard function computing the sine of a value with ``float``, 1263``double``, or ``long double`` precision: 1264 1265.. code-block:: c 1266 1267 #include <math.h> 1268 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); } 1269 double __attribute__((overloadable)) tgsin(double x) { return sin(x); } 1270 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); } 1271 1272Given these declarations, one can call ``tgsin`` with a ``float`` value to 1273receive a ``float`` result, with a ``double`` to receive a ``double`` result, 1274etc. Function overloading in C follows the rules of C++ function overloading 1275to pick the best overload given the call arguments, with a few C-specific 1276semantics: 1277 1278* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a 1279 floating-point promotion (per C99) rather than as a floating-point conversion 1280 (as in C++). 1281 1282* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is 1283 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are 1284 compatible types. 1285 1286* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T`` 1287 and ``U`` are compatible types. This conversion is given "conversion" rank. 1288 1289The declaration of ``overloadable`` functions is restricted to function 1290declarations and definitions. Most importantly, if any function with a given 1291name is given the ``overloadable`` attribute, then all function declarations 1292and definitions with that name (and in that scope) must have the 1293``overloadable`` attribute. This rule even applies to redeclarations of 1294functions whose original declaration had the ``overloadable`` attribute, e.g., 1295 1296.. code-block:: c 1297 1298 int f(int) __attribute__((overloadable)); 1299 float f(float); // error: declaration of "f" must have the "overloadable" attribute 1300 1301 int g(int) __attribute__((overloadable)); 1302 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute 1303 1304Functions marked ``overloadable`` must have prototypes. Therefore, the 1305following code is ill-formed: 1306 1307.. code-block:: c 1308 1309 int h() __attribute__((overloadable)); // error: h does not have a prototype 1310 1311However, ``overloadable`` functions are allowed to use a ellipsis even if there 1312are no named parameters (as is permitted in C++). This feature is particularly 1313useful when combined with the ``unavailable`` attribute: 1314 1315.. code-block:: c++ 1316 1317 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error 1318 1319Functions declared with the ``overloadable`` attribute have their names mangled 1320according to the same rules as C++ function names. For example, the three 1321``tgsin`` functions in our motivating example get the mangled names 1322``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two 1323caveats to this use of name mangling: 1324 1325* Future versions of Clang may change the name mangling of functions overloaded 1326 in C, so you should not depend on an specific mangling. To be completely 1327 safe, we strongly urge the use of ``static inline`` with ``overloadable`` 1328 functions. 1329 1330* The ``overloadable`` attribute has almost no meaning when used in C++, 1331 because names will already be mangled and functions are already overloadable. 1332 However, when an ``overloadable`` function occurs within an ``extern "C"`` 1333 linkage specification, it's name *will* be mangled in the same way as it 1334 would in C. 1335 1336Query for this feature with ``__has_extension(attribute_overloadable)``. 1337 1338Initializer lists for complex numbers in C 1339========================================== 1340 1341clang supports an extension which allows the following in C: 1342 1343.. code-block:: c++ 1344 1345 #include <math.h> 1346 #include <complex.h> 1347 complex float x = { 1.0f, INFINITY }; // Init to (1, Inf) 1348 1349This construct is useful because there is no way to separately initialize the 1350real and imaginary parts of a complex variable in standard C, given that clang 1351does not support ``_Imaginary``. (Clang also supports the ``__real__`` and 1352``__imag__`` extensions from gcc, which help in some cases, but are not usable 1353in static initializers.) 1354 1355Note that this extension does not allow eliding the braces; the meaning of the 1356following two lines is different: 1357 1358.. code-block:: c++ 1359 1360 complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1) 1361 complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0) 1362 1363This extension also works in C++ mode, as far as that goes, but does not apply 1364to the C++ ``std::complex``. (In C++11, list initialization allows the same 1365syntax to be used with ``std::complex`` with the same meaning.) 1366 1367Builtin Functions 1368================= 1369 1370Clang supports a number of builtin library functions with the same syntax as 1371GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``, 1372``__builtin_choose_expr``, ``__builtin_types_compatible_p``, 1373``__sync_fetch_and_add``, etc. In addition to the GCC builtins, Clang supports 1374a number of builtins that GCC does not, which are listed here. 1375 1376Please note that Clang does not and will not support all of the GCC builtins 1377for vector operations. Instead of using builtins, you should use the functions 1378defined in target-specific header files like ``<xmmintrin.h>``, which define 1379portable wrappers for these. Many of the Clang versions of these functions are 1380implemented directly in terms of :ref:`extended vector support 1381<langext-vectors>` instead of builtins, in order to reduce the number of 1382builtins that we need to implement. 1383 1384``__builtin_readcyclecounter`` 1385------------------------------ 1386 1387``__builtin_readcyclecounter`` is used to access the cycle counter register (or 1388a similar low-latency, high-accuracy clock) on those targets that support it. 1389 1390**Syntax**: 1391 1392.. code-block:: c++ 1393 1394 __builtin_readcyclecounter() 1395 1396**Example of Use**: 1397 1398.. code-block:: c++ 1399 1400 unsigned long long t0 = __builtin_readcyclecounter(); 1401 do_something(); 1402 unsigned long long t1 = __builtin_readcyclecounter(); 1403 unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow 1404 1405**Description**: 1406 1407The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value, 1408which may be either global or process/thread-specific depending on the target. 1409As the backing counters often overflow quickly (on the order of seconds) this 1410should only be used for timing small intervals. When not supported by the 1411target, the return value is always zero. This builtin takes no arguments and 1412produces an unsigned long long result. 1413 1414Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. 1415 1416.. _langext-__builtin_shufflevector: 1417 1418``__builtin_shufflevector`` 1419--------------------------- 1420 1421``__builtin_shufflevector`` is used to express generic vector 1422permutation/shuffle/swizzle operations. This builtin is also very important 1423for the implementation of various target-specific header files like 1424``<xmmintrin.h>``. 1425 1426**Syntax**: 1427 1428.. code-block:: c++ 1429 1430 __builtin_shufflevector(vec1, vec2, index1, index2, ...) 1431 1432**Examples**: 1433 1434.. code-block:: c++ 1435 1436 // Identity operation - return 4-element vector V1. 1437 __builtin_shufflevector(V1, V1, 0, 1, 2, 3) 1438 1439 // "Splat" element 0 of V1 into a 4-element result. 1440 __builtin_shufflevector(V1, V1, 0, 0, 0, 0) 1441 1442 // Reverse 4-element vector V1. 1443 __builtin_shufflevector(V1, V1, 3, 2, 1, 0) 1444 1445 // Concatenate every other element of 4-element vectors V1 and V2. 1446 __builtin_shufflevector(V1, V2, 0, 2, 4, 6) 1447 1448 // Concatenate every other element of 8-element vectors V1 and V2. 1449 __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14) 1450 1451**Description**: 1452 1453The first two arguments to ``__builtin_shufflevector`` are vectors that have 1454the same element type. The remaining arguments are a list of integers that 1455specify the elements indices of the first two vectors that should be extracted 1456and returned in a new vector. These element indices are numbered sequentially 1457starting with the first vector, continuing into the second vector. Thus, if 1458``vec1`` is a 4-element vector, index 5 would refer to the second element of 1459``vec2``. 1460 1461The result of ``__builtin_shufflevector`` is a vector with the same element 1462type as ``vec1``/``vec2`` but that has an element count equal to the number of 1463indices specified. 1464 1465Query for this feature with ``__has_builtin(__builtin_shufflevector)``. 1466 1467``__builtin_unreachable`` 1468------------------------- 1469 1470``__builtin_unreachable`` is used to indicate that a specific point in the 1471program cannot be reached, even if the compiler might otherwise think it can. 1472This is useful to improve optimization and eliminates certain warnings. For 1473example, without the ``__builtin_unreachable`` in the example below, the 1474compiler assumes that the inline asm can fall through and prints a "function 1475declared '``noreturn``' should not return" warning. 1476 1477**Syntax**: 1478 1479.. code-block:: c++ 1480 1481 __builtin_unreachable() 1482 1483**Example of use**: 1484 1485.. code-block:: c++ 1486 1487 void myabort(void) __attribute__((noreturn)); 1488 void myabort(void) { 1489 asm("int3"); 1490 __builtin_unreachable(); 1491 } 1492 1493**Description**: 1494 1495The ``__builtin_unreachable()`` builtin has completely undefined behavior. 1496Since it has undefined behavior, it is a statement that it is never reached and 1497the optimizer can take advantage of this to produce better code. This builtin 1498takes no arguments and produces a void result. 1499 1500Query for this feature with ``__has_builtin(__builtin_unreachable)``. 1501 1502``__sync_swap`` 1503--------------- 1504 1505``__sync_swap`` is used to atomically swap integers or pointers in memory. 1506 1507**Syntax**: 1508 1509.. code-block:: c++ 1510 1511 type __sync_swap(type *ptr, type value, ...) 1512 1513**Example of Use**: 1514 1515.. code-block:: c++ 1516 1517 int old_value = __sync_swap(&value, new_value); 1518 1519**Description**: 1520 1521The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of 1522atomic intrinsics to allow code to atomically swap the current value with the 1523new value. More importantly, it helps developers write more efficient and 1524correct code by avoiding expensive loops around 1525``__sync_bool_compare_and_swap()`` or relying on the platform specific 1526implementation details of ``__sync_lock_test_and_set()``. The 1527``__sync_swap()`` builtin is a full barrier. 1528 1529Multiprecision Arithmetic Builtins 1530---------------------------------- 1531 1532Clang provides a set of builtins which expose multiprecision arithmetic in a 1533manner amenable to C. They all have the following form: 1534 1535.. code-block:: c 1536 1537 unsigned x = ..., y = ..., carryin = ..., carryout; 1538 unsigned sum = __builtin_addc(x, y, carryin, &carryout); 1539 1540Thus one can form a multiprecision addition chain in the following manner: 1541 1542.. code-block:: c 1543 1544 unsigned *x, *y, *z, carryin=0, carryout; 1545 z[0] = __builtin_addc(x[0], y[0], carryin, &carryout); 1546 carryin = carryout; 1547 z[1] = __builtin_addc(x[1], y[1], carryin, &carryout); 1548 carryin = carryout; 1549 z[2] = __builtin_addc(x[2], y[2], carryin, &carryout); 1550 carryin = carryout; 1551 z[3] = __builtin_addc(x[3], y[3], carryin, &carryout); 1552 1553The complete list of builtins are: 1554 1555.. code-block:: c 1556 1557 unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout); 1558 unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout); 1559 unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout); 1560 unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout); 1561 unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout); 1562 unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout); 1563 unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout); 1564 unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout); 1565 1566.. _langext-__c11_atomic: 1567 1568__c11_atomic builtins 1569--------------------- 1570 1571Clang provides a set of builtins which are intended to be used to implement 1572C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the 1573``_explicit`` form of the corresponding C11 operation, and are named with a 1574``__c11_`` prefix. The supported operations are: 1575 1576* ``__c11_atomic_init`` 1577* ``__c11_atomic_thread_fence`` 1578* ``__c11_atomic_signal_fence`` 1579* ``__c11_atomic_is_lock_free`` 1580* ``__c11_atomic_store`` 1581* ``__c11_atomic_load`` 1582* ``__c11_atomic_exchange`` 1583* ``__c11_atomic_compare_exchange_strong`` 1584* ``__c11_atomic_compare_exchange_weak`` 1585* ``__c11_atomic_fetch_add`` 1586* ``__c11_atomic_fetch_sub`` 1587* ``__c11_atomic_fetch_and`` 1588* ``__c11_atomic_fetch_or`` 1589* ``__c11_atomic_fetch_xor`` 1590 1591Non-standard C++11 Attributes 1592============================= 1593 1594Clang's non-standard C++11 attributes live in the ``clang`` attribute 1595namespace. 1596 1597The ``clang::fallthrough`` attribute 1598------------------------------------ 1599 1600The ``clang::fallthrough`` attribute is used along with the 1601``-Wimplicit-fallthrough`` argument to annotate intentional fall-through 1602between switch labels. It can only be applied to a null statement placed at a 1603point of execution between any statement and the next switch label. It is 1604common to mark these places with a specific comment, but this attribute is 1605meant to replace comments with a more strict annotation, which can be checked 1606by the compiler. This attribute doesn't change semantics of the code and can 1607be used wherever an intended fall-through occurs. It is designed to mimic 1608control-flow statements like ``break;``, so it can be placed in most places 1609where ``break;`` can, but only if there are no statements on the execution path 1610between it and the next switch label. 1611 1612Here is an example: 1613 1614.. code-block:: c++ 1615 1616 // compile with -Wimplicit-fallthrough 1617 switch (n) { 1618 case 22: 1619 case 33: // no warning: no statements between case labels 1620 f(); 1621 case 44: // warning: unannotated fall-through 1622 g(); 1623 [[clang::fallthrough]]; 1624 case 55: // no warning 1625 if (x) { 1626 h(); 1627 break; 1628 } 1629 else { 1630 i(); 1631 [[clang::fallthrough]]; 1632 } 1633 case 66: // no warning 1634 p(); 1635 [[clang::fallthrough]]; // warning: fallthrough annotation does not 1636 // directly precede case label 1637 q(); 1638 case 77: // warning: unannotated fall-through 1639 r(); 1640 } 1641 1642``gnu::`` attributes 1643-------------------- 1644 1645Clang also supports GCC's ``gnu`` attribute namespace. All GCC attributes which 1646are accepted with the ``__attribute__((foo))`` syntax are also accepted as 1647``[[gnu::foo]]``. This only extends to attributes which are specified by GCC 1648(see the list of `GCC function attributes 1649<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable 1650attributes <http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and 1651`GCC type attributes 1652<http://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_. As with the GCC 1653implementation, these attributes must appertain to the *declarator-id* in a 1654declaration, which means they must go either at the start of the declaration or 1655immediately after the name being declared. 1656 1657For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and 1658also applies the GNU ``noreturn`` attribute to ``f``. 1659 1660.. code-block:: c++ 1661 1662 [[gnu::unused]] int a, f [[gnu::noreturn]] (); 1663 1664Target-Specific Extensions 1665========================== 1666 1667Clang supports some language features conditionally on some targets. 1668 1669X86/X86-64 Language Extensions 1670------------------------------ 1671 1672The X86 backend has these language extensions: 1673 1674Memory references off the GS segment 1675^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1676 1677Annotating a pointer with address space #256 causes it to be code generated 1678relative to the X86 GS segment register, and address space #257 causes it to be 1679relative to the X86 FS segment. Note that this is a very very low-level 1680feature that should only be used if you know what you're doing (for example in 1681an OS kernel). 1682 1683Here is an example: 1684 1685.. code-block:: c++ 1686 1687 #define GS_RELATIVE __attribute__((address_space(256))) 1688 int foo(int GS_RELATIVE *P) { 1689 return *P; 1690 } 1691 1692Which compiles to (on X86-32): 1693 1694.. code-block:: gas 1695 1696 _foo: 1697 movl 4(%esp), %eax 1698 movl %gs:(%eax), %eax 1699 ret 1700 1701Extensions for Static Analysis 1702============================== 1703 1704Clang supports additional attributes that are useful for documenting program 1705invariants and rules for static analysis tools, such as the `Clang Static 1706Analyzer <http://clang-analyzer.llvm.org/>`_. These attributes are documented 1707in the analyzer's `list of source-level annotations 1708<http://clang-analyzer.llvm.org/annotations.html>`_. 1709 1710 1711Extensions for Dynamic Analysis 1712=============================== 1713 1714.. _langext-address_sanitizer: 1715 1716AddressSanitizer 1717---------------- 1718 1719Use ``__has_feature(address_sanitizer)`` to check if the code is being built 1720with :doc:`AddressSanitizer`. 1721 1722Use ``__attribute__((no_sanitize_address))`` 1723on a function declaration 1724to specify that address safety instrumentation (e.g. AddressSanitizer) should 1725not be applied to that function. 1726 1727.. _langext-thread_sanitizer: 1728 1729ThreadSanitizer 1730---------------- 1731 1732Use ``__has_feature(thread_sanitizer)`` to check if the code is being built 1733with :doc:`ThreadSanitizer`. 1734 1735Use ``__attribute__((no_sanitize_thread))`` on a function declaration 1736to specify that checks for data races on plain (non-atomic) memory accesses 1737should not be inserted by ThreadSanitizer. 1738The function may still be instrumented by the tool 1739to avoid false positives in other places. 1740 1741.. _langext-memory_sanitizer: 1742 1743MemorySanitizer 1744---------------- 1745Use ``__has_feature(memory_sanitizer)`` to check if the code is being built 1746with :doc:`MemorySanitizer`. 1747 1748Use ``__attribute__((no_sanitize_memory))`` on a function declaration 1749to specify that checks for uninitialized memory should not be inserted 1750(e.g. by MemorySanitizer). The function may still be instrumented by the tool 1751to avoid false positives in other places. 1752 1753 1754Thread-Safety Annotation Checking 1755================================= 1756 1757Clang supports additional attributes for checking basic locking policies in 1758multithreaded programs. Clang currently parses the following list of 1759attributes, although **the implementation for these annotations is currently in 1760development.** For more details, see the `GCC implementation 1761<http://gcc.gnu.org/wiki/ThreadSafetyAnnotation>`_. 1762 1763``no_thread_safety_analysis`` 1764----------------------------- 1765 1766Use ``__attribute__((no_thread_safety_analysis))`` on a function declaration to 1767specify that the thread safety analysis should not be run on that function. 1768This attribute provides an escape hatch (e.g. for situations when it is 1769difficult to annotate the locking policy). 1770 1771``lockable`` 1772------------ 1773 1774Use ``__attribute__((lockable))`` on a class definition to specify that it has 1775a lockable type (e.g. a Mutex class). This annotation is primarily used to 1776check consistency. 1777 1778``scoped_lockable`` 1779------------------- 1780 1781Use ``__attribute__((scoped_lockable))`` on a class definition to specify that 1782it has a "scoped" lockable type. Objects of this type will acquire the lock 1783upon construction and release it upon going out of scope. This annotation is 1784primarily used to check consistency. 1785 1786``guarded_var`` 1787--------------- 1788 1789Use ``__attribute__((guarded_var))`` on a variable declaration to specify that 1790the variable must be accessed while holding some lock. 1791 1792``pt_guarded_var`` 1793------------------ 1794 1795Use ``__attribute__((pt_guarded_var))`` on a pointer declaration to specify 1796that the pointer must be dereferenced while holding some lock. 1797 1798``guarded_by(l)`` 1799----------------- 1800 1801Use ``__attribute__((guarded_by(l)))`` on a variable declaration to specify 1802that the variable must be accessed while holding lock ``l``. 1803 1804``pt_guarded_by(l)`` 1805-------------------- 1806 1807Use ``__attribute__((pt_guarded_by(l)))`` on a pointer declaration to specify 1808that the pointer must be dereferenced while holding lock ``l``. 1809 1810``acquired_before(...)`` 1811------------------------ 1812 1813Use ``__attribute__((acquired_before(...)))`` on a declaration of a lockable 1814variable to specify that the lock must be acquired before all attribute 1815arguments. Arguments must be lockable type, and there must be at least one 1816argument. 1817 1818``acquired_after(...)`` 1819----------------------- 1820 1821Use ``__attribute__((acquired_after(...)))`` on a declaration of a lockable 1822variable to specify that the lock must be acquired after all attribute 1823arguments. Arguments must be lockable type, and there must be at least one 1824argument. 1825 1826``exclusive_lock_function(...)`` 1827-------------------------------- 1828 1829Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration 1830to specify that the function acquires all listed locks exclusively. This 1831attribute takes zero or more arguments: either of lockable type or integers 1832indexing into function parameters of lockable type. If no arguments are given, 1833the acquired lock is implicitly ``this`` of the enclosing object. 1834 1835``shared_lock_function(...)`` 1836----------------------------- 1837 1838Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to 1839specify that the function acquires all listed locks, although the locks may be 1840shared (e.g. read locks). This attribute takes zero or more arguments: either 1841of lockable type or integers indexing into function parameters of lockable 1842type. If no arguments are given, the acquired lock is implicitly ``this`` of 1843the enclosing object. 1844 1845``exclusive_trylock_function(...)`` 1846----------------------------------- 1847 1848Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration 1849to specify that the function will try (without blocking) to acquire all listed 1850locks exclusively. This attribute takes one or more arguments. The first 1851argument is an integer or boolean value specifying the return value of a 1852successful lock acquisition. The remaining arugments are either of lockable 1853type or integers indexing into function parameters of lockable type. If only 1854one argument is given, the acquired lock is implicitly ``this`` of the 1855enclosing object. 1856 1857``shared_trylock_function(...)`` 1858-------------------------------- 1859 1860Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to 1861specify that the function will try (without blocking) to acquire all listed 1862locks, although the locks may be shared (e.g. read locks). This attribute 1863takes one or more arguments. The first argument is an integer or boolean value 1864specifying the return value of a successful lock acquisition. The remaining 1865arugments are either of lockable type or integers indexing into function 1866parameters of lockable type. If only one argument is given, the acquired lock 1867is implicitly ``this`` of the enclosing object. 1868 1869``unlock_function(...)`` 1870------------------------ 1871 1872Use ``__attribute__((unlock_function(...)))`` on a function declaration to 1873specify that the function release all listed locks. This attribute takes zero 1874or more arguments: either of lockable type or integers indexing into function 1875parameters of lockable type. If no arguments are given, the acquired lock is 1876implicitly ``this`` of the enclosing object. 1877 1878``lock_returned(l)`` 1879-------------------- 1880 1881Use ``__attribute__((lock_returned(l)))`` on a function declaration to specify 1882that the function returns lock ``l`` (``l`` must be of lockable type). This 1883annotation is used to aid in resolving lock expressions. 1884 1885``locks_excluded(...)`` 1886----------------------- 1887 1888Use ``__attribute__((locks_excluded(...)))`` on a function declaration to 1889specify that the function must not be called with the listed locks. Arguments 1890must be lockable type, and there must be at least one argument. 1891 1892``exclusive_locks_required(...)`` 1893--------------------------------- 1894 1895Use ``__attribute__((exclusive_locks_required(...)))`` on a function 1896declaration to specify that the function must be called while holding the 1897listed exclusive locks. Arguments must be lockable type, and there must be at 1898least one argument. 1899 1900``shared_locks_required(...)`` 1901------------------------------ 1902 1903Use ``__attribute__((shared_locks_required(...)))`` on a function declaration 1904to specify that the function must be called while holding the listed shared 1905locks. Arguments must be lockable type, and there must be at least one 1906argument. 1907 1908Type Safety Checking 1909==================== 1910 1911Clang supports additional attributes to enable checking type safety properties 1912that can't be enforced by C type system. Usecases include: 1913 1914* MPI library implementations, where these attributes enable checking that 1915 buffer type matches the passed ``MPI_Datatype``; 1916* for HDF5 library there is a similar usecase as MPI; 1917* checking types of variadic functions' arguments for functions like 1918 ``fcntl()`` and ``ioctl()``. 1919 1920You can detect support for these attributes with ``__has_attribute()``. For 1921example: 1922 1923.. code-block:: c++ 1924 1925 #if defined(__has_attribute) 1926 # if __has_attribute(argument_with_type_tag) && \ 1927 __has_attribute(pointer_with_type_tag) && \ 1928 __has_attribute(type_tag_for_datatype) 1929 # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx))) 1930 /* ... other macros ... */ 1931 # endif 1932 #endif 1933 1934 #if !defined(ATTR_MPI_PWT) 1935 # define ATTR_MPI_PWT(buffer_idx, type_idx) 1936 #endif 1937 1938 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) 1939 ATTR_MPI_PWT(1,3); 1940 1941``argument_with_type_tag(...)`` 1942------------------------------- 1943 1944Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx, 1945type_tag_idx)))`` on a function declaration to specify that the function 1946accepts a type tag that determines the type of some other argument. 1947``arg_kind`` is an identifier that should be used when annotating all 1948applicable type tags. 1949 1950This attribute is primarily useful for checking arguments of variadic functions 1951(``pointer_with_type_tag`` can be used in most of non-variadic cases). 1952 1953For example: 1954 1955.. code-block:: c++ 1956 1957 int fcntl(int fd, int cmd, ...) 1958 __attribute__(( argument_with_type_tag(fcntl,3,2) )); 1959 1960``pointer_with_type_tag(...)`` 1961------------------------------ 1962 1963Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))`` 1964on a function declaration to specify that the function accepts a type tag that 1965determines the pointee type of some other pointer argument. 1966 1967For example: 1968 1969.. code-block:: c++ 1970 1971 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) 1972 __attribute__(( pointer_with_type_tag(mpi,1,3) )); 1973 1974``type_tag_for_datatype(...)`` 1975------------------------------ 1976 1977Clang supports annotating type tags of two forms. 1978 1979* **Type tag that is an expression containing a reference to some declared 1980 identifier.** Use ``__attribute__((type_tag_for_datatype(kind, type)))`` on a 1981 declaration with that identifier: 1982 1983 .. code-block:: c++ 1984 1985 extern struct mpi_datatype mpi_datatype_int 1986 __attribute__(( type_tag_for_datatype(mpi,int) )); 1987 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int) 1988 1989* **Type tag that is an integral literal.** Introduce a ``static const`` 1990 variable with a corresponding initializer value and attach 1991 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration, 1992 for example: 1993 1994 .. code-block:: c++ 1995 1996 #define MPI_INT ((MPI_Datatype) 42) 1997 static const MPI_Datatype mpi_datatype_int 1998 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42 1999 2000The attribute also accepts an optional third argument that determines how the 2001expression is compared to the type tag. There are two supported flags: 2002 2003* ``layout_compatible`` will cause types to be compared according to 2004 layout-compatibility rules (C++11 [class.mem] p 17, 18). This is 2005 implemented to support annotating types like ``MPI_DOUBLE_INT``. 2006 2007 For example: 2008 2009 .. code-block:: c++ 2010 2011 /* In mpi.h */ 2012 struct internal_mpi_double_int { double d; int i; }; 2013 extern struct mpi_datatype mpi_datatype_double_int 2014 __attribute__(( type_tag_for_datatype(mpi, struct internal_mpi_double_int, layout_compatible) )); 2015 2016 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int) 2017 2018 /* In user code */ 2019 struct my_pair { double a; int b; }; 2020 struct my_pair *buffer; 2021 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning 2022 2023 struct my_int_pair { int a; int b; } 2024 struct my_int_pair *buffer2; 2025 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning: actual buffer element 2026 // type 'struct my_int_pair' 2027 // doesn't match specified MPI_Datatype 2028 2029* ``must_be_null`` specifies that the expression should be a null pointer 2030 constant, for example: 2031 2032 .. code-block:: c++ 2033 2034 /* In mpi.h */ 2035 extern struct mpi_datatype mpi_datatype_null 2036 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) )); 2037 2038 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null) 2039 2040 /* In user code */ 2041 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL 2042 // was specified but buffer 2043 // is not a null pointer 2044 2045Format String Checking 2046====================== 2047 2048Clang supports the ``format`` attribute, which indicates that the function 2049accepts a ``printf`` or ``scanf``-like format string and corresponding 2050arguments or a ``va_list`` that contains these arguments. 2051 2052Please see `GCC documentation about format attribute 2053<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details 2054about attribute syntax. 2055 2056Clang implements two kinds of checks with this attribute. 2057 2058#. Clang checks that the function with the ``format`` attribute is called with 2059 a format string that uses format specifiers that are allowed, and that 2060 arguments match the format string. This is the ``-Wformat`` warning, it is 2061 on by default. 2062 2063#. Clang checks that the format string argument is a literal string. This is 2064 the ``-Wformat-nonliteral`` warning, it is off by default. 2065 2066 Clang implements this mostly the same way as GCC, but there is a difference 2067 for functions that accept a ``va_list`` argument (for example, ``vprintf``). 2068 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such 2069 fuctions. Clang does not warn if the format string comes from a function 2070 parameter, where the function is annotated with a compatible attribute, 2071 otherwise it warns. For example: 2072 2073 .. code-block:: c 2074 2075 __attribute__((__format__ (__scanf__, 1, 3))) 2076 void foo(const char* s, char *buf, ...) { 2077 va_list ap; 2078 va_start(ap, buf); 2079 2080 vprintf(s, ap); // warning: format string is not a string literal 2081 } 2082 2083 In this case we warn because ``s`` contains a format string for a 2084 ``scanf``-like function, but it is passed to a ``printf``-like function. 2085 2086 If the attribute is removed, clang still warns, because the format string is 2087 not a string literal. 2088 2089 Another example: 2090 2091 .. code-block:: c 2092 2093 __attribute__((__format__ (__printf__, 1, 3))) 2094 void foo(const char* s, char *buf, ...) { 2095 va_list ap; 2096 va_start(ap, buf); 2097 2098 vprintf(s, ap); // warning 2099 } 2100 2101 In this case Clang does not warn because the format string ``s`` and 2102 the corresponding arguments are annotated. If the arguments are 2103 incorrect, the caller of ``foo`` will receive a warning. 2104