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