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