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