blob: 392e679f1532b147ec1a7736b7b7b70dee0554b4 [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
Stephen Hines651f13c2014-04-23 16:59:28 -070015 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
Stephen Hines651f13c2014-04-23 16:59:28 -0700116an attribute. It evaluates to 1 if the attribute is supported by the current
117compilation target, or 0 if not. It can be used like this:
Sean Silva3872b462012-12-12 23:44:55 +0000118
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
Stephen Hines651f13c2014-04-23 16:59:28 -0700137
Sean Silva3872b462012-12-12 23:44:55 +0000138Include File Checking Macros
139============================
140
141Not all developments systems have the same include files. The
142:ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
143you to check for the existence of an include file before doing a possibly
Dmitri Gribenko21937c62013-01-17 17:04:54 +0000144failing ``#include`` directive. Include file checking macros must be used
145as expressions in ``#if`` or ``#elif`` preprocessing directives.
Sean Silva3872b462012-12-12 23:44:55 +0000146
147.. _langext-__has_include:
148
149``__has_include``
150-----------------
151
152This function-like macro takes a single file name string argument that is the
153name of an include file. It evaluates to 1 if the file can be found using the
154include paths, or 0 otherwise:
155
156.. code-block:: c++
157
158 // Note the two possible file name string formats.
159 #if __has_include("myinclude.h") && __has_include(<stdint.h>)
160 # include "myinclude.h"
161 #endif
162
Richard Smith9e0a65e2013-07-11 00:27:05 +0000163To test for this feature, use ``#if defined(__has_include)``:
164
165.. code-block:: c++
166
Sean Silva3872b462012-12-12 23:44:55 +0000167 // To avoid problem with non-clang compilers not having this macro.
Richard Smith9e0a65e2013-07-11 00:27:05 +0000168 #if defined(__has_include)
169 #if __has_include("myinclude.h")
Sean Silva3872b462012-12-12 23:44:55 +0000170 # include "myinclude.h"
171 #endif
Richard Smith9e0a65e2013-07-11 00:27:05 +0000172 #endif
Sean Silva3872b462012-12-12 23:44:55 +0000173
174.. _langext-__has_include_next:
175
176``__has_include_next``
177----------------------
178
179This function-like macro takes a single file name string argument that is the
180name of an include file. It is like ``__has_include`` except that it looks for
181the second instance of the given file found in the include paths. It evaluates
182to 1 if the second instance of the file can be found using the include paths,
183or 0 otherwise:
184
185.. code-block:: c++
186
187 // Note the two possible file name string formats.
188 #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
189 # include_next "myinclude.h"
190 #endif
191
192 // To avoid problem with non-clang compilers not having this macro.
Richard Smith9e0a65e2013-07-11 00:27:05 +0000193 #if defined(__has_include_next)
194 #if __has_include_next("myinclude.h")
Sean Silva3872b462012-12-12 23:44:55 +0000195 # include_next "myinclude.h"
196 #endif
Richard Smith9e0a65e2013-07-11 00:27:05 +0000197 #endif
Sean Silva3872b462012-12-12 23:44:55 +0000198
199Note that ``__has_include_next``, like the GNU extension ``#include_next``
200directive, is intended for use in headers only, and will issue a warning if
201used in the top-level compilation file. A warning will also be issued if an
202absolute path is used in the file argument.
203
204``__has_warning``
205-----------------
206
207This function-like macro takes a string literal that represents a command line
208option for a warning and returns true if that is a valid warning option.
209
210.. code-block:: c++
211
212 #if __has_warning("-Wformat")
213 ...
214 #endif
215
216Builtin Macros
217==============
218
219``__BASE_FILE__``
220 Defined to a string that contains the name of the main input file passed to
221 Clang.
222
223``__COUNTER__``
224 Defined to an integer value that starts at zero and is incremented each time
225 the ``__COUNTER__`` macro is expanded.
226
227``__INCLUDE_LEVEL__``
228 Defined to an integral value that is the include depth of the file currently
229 being translated. For the main file, this value is zero.
230
231``__TIMESTAMP__``
232 Defined to the date and time of the last modification of the current source
233 file.
234
235``__clang__``
236 Defined when compiling with Clang
237
238``__clang_major__``
239 Defined to the major marketing version number of Clang (e.g., the 2 in
240 2.0.1). Note that marketing version numbers should not be used to check for
241 language features, as different vendors use different numbering schemes.
242 Instead, use the :ref:`langext-feature_check`.
243
244``__clang_minor__``
245 Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note
246 that marketing version numbers should not be used to check for language
247 features, as different vendors use different numbering schemes. Instead, use
248 the :ref:`langext-feature_check`.
249
250``__clang_patchlevel__``
251 Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
252
253``__clang_version__``
254 Defined to a string that captures the Clang marketing version, including the
255 Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
256
257.. _langext-vectors:
258
259Vectors and Extended Vectors
260============================
261
262Supports the GCC, OpenCL, AltiVec and NEON vector extensions.
263
264OpenCL vector types are created using ``ext_vector_type`` attribute. It
265support for ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example
266is:
267
268.. code-block:: c++
269
270 typedef float float4 __attribute__((ext_vector_type(4)));
271 typedef float float2 __attribute__((ext_vector_type(2)));
272
273 float4 foo(float2 a, float2 b) {
274 float4 c;
275 c.xz = a;
276 c.yw = b;
277 return c;
278 }
279
280Query for this feature with ``__has_extension(attribute_ext_vector_type)``.
281
282Giving ``-faltivec`` option to clang enables support for AltiVec vector syntax
283and functions. For example:
284
285.. code-block:: c++
286
287 vector float foo(vector int a) {
288 vector int b;
289 b = vec_add(a, a) + a;
290 return (vector float)b;
291 }
292
293NEON vector types are created using ``neon_vector_type`` and
294``neon_polyvector_type`` attributes. For example:
295
296.. code-block:: c++
297
298 typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
299 typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
300
301 int8x8_t foo(int8x8_t a) {
302 int8x8_t v;
303 v = a;
304 return v;
305 }
306
307Vector Literals
308---------------
309
310Vector literals can be used to create vectors from a set of scalars, or
311vectors. Either parentheses or braces form can be used. In the parentheses
312form the number of literal values specified must be one, i.e. referring to a
313scalar value, or must match the size of the vector type being created. If a
314single scalar literal value is specified, the scalar literal value will be
315replicated to all the components of the vector type. In the brackets form any
316number of literals can be specified. For example:
317
318.. code-block:: c++
319
320 typedef int v4si __attribute__((__vector_size__(16)));
321 typedef float float4 __attribute__((ext_vector_type(4)));
322 typedef float float2 __attribute__((ext_vector_type(2)));
323
324 v4si vsi = (v4si){1, 2, 3, 4};
325 float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
326 vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1).
327 vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0).
328 vector int vi3 = (vector int)(1, 2); // error
329 vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
330 vector int vi5 = (vector int)(1, 2, 3, 4);
331 float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
332
333Vector Operations
334-----------------
335
336The table below shows the support for each operation by vector extension. A
337dash indicates that an operation is not accepted according to a corresponding
338specification.
339
340============================== ====== ======= === ====
341 Opeator OpenCL AltiVec GCC NEON
342============================== ====== ======= === ====
343[] yes yes yes --
344unary operators +, -- yes yes yes --
345++, -- -- yes yes yes --
346+,--,*,/,% yes yes yes --
347bitwise operators &,|,^,~ yes yes yes --
348>>,<< yes yes yes --
349!, &&, || no -- -- --
350==, !=, >, <, >=, <= yes yes -- --
351= yes yes yes yes
352:? yes -- -- --
353sizeof yes yes yes yes
354============================== ====== ======= === ====
355
356See also :ref:`langext-__builtin_shufflevector`.
357
358Messages on ``deprecated`` and ``unavailable`` Attributes
359=========================================================
360
361An optional string message can be added to the ``deprecated`` and
362``unavailable`` attributes. For example:
363
364.. code-block:: c++
365
366 void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
367
368If the deprecated or unavailable declaration is used, the message will be
369incorporated into the appropriate diagnostic:
370
371.. code-block:: c++
372
373 harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
374 [-Wdeprecated-declarations]
375 explode();
376 ^
377
378Query for this feature with
379``__has_extension(attribute_deprecated_with_message)`` and
380``__has_extension(attribute_unavailable_with_message)``.
381
382Attributes on Enumerators
383=========================
384
385Clang allows attributes to be written on individual enumerators. This allows
386enumerators to be deprecated, made unavailable, etc. The attribute must appear
387after the enumerator name and before any initializer, like so:
388
389.. code-block:: c++
390
391 enum OperationMode {
392 OM_Invalid,
393 OM_Normal,
394 OM_Terrified __attribute__((deprecated)),
395 OM_AbortOnError __attribute__((deprecated)) = 4
396 };
397
398Attributes on the ``enum`` declaration do not apply to individual enumerators.
399
400Query for this feature with ``__has_extension(enumerator_attributes)``.
401
402'User-Specified' System Frameworks
403==================================
404
405Clang provides a mechanism by which frameworks can be built in such a way that
406they will always be treated as being "system frameworks", even if they are not
407present in a system framework directory. This can be useful to system
408framework developers who want to be able to test building other applications
409with development builds of their framework, including the manner in which the
410compiler changes warning behavior for system headers.
411
412Framework developers can opt-in to this mechanism by creating a
413"``.system_framework``" file at the top-level of their framework. That is, the
414framework should have contents like:
415
416.. code-block:: none
417
418 .../TestFramework.framework
419 .../TestFramework.framework/.system_framework
420 .../TestFramework.framework/Headers
421 .../TestFramework.framework/Headers/TestFramework.h
422 ...
423
424Clang will treat the presence of this file as an indicator that the framework
425should be treated as a system framework, regardless of how it was found in the
426framework search path. For consistency, we recommend that such files never be
427included in installed versions of the framework.
428
Sean Silva3872b462012-12-12 23:44:55 +0000429Checks for Standard Language Features
430=====================================
431
432The ``__has_feature`` macro can be used to query if certain standard language
433features are enabled. The ``__has_extension`` macro can be used to query if
434language features are available as an extension when compiling for a standard
435which does not provide them. The features which can be tested are listed here.
436
437C++98
438-----
439
440The features listed below are part of the C++98 standard. These features are
441enabled by default when compiling C++ code.
442
443C++ exceptions
444^^^^^^^^^^^^^^
445
446Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
447enabled. For example, compiling code with ``-fno-exceptions`` disables C++
448exceptions.
449
450C++ RTTI
451^^^^^^^^
452
453Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For
454example, compiling code with ``-fno-rtti`` disables the use of RTTI.
455
456C++11
457-----
458
459The features listed below are part of the C++11 standard. As a result, all
460these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
461when compiling C++ code.
462
463C++11 SFINAE includes access control
464^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
465
466Use ``__has_feature(cxx_access_control_sfinae)`` or
467``__has_extension(cxx_access_control_sfinae)`` to determine whether
468access-control errors (e.g., calling a private constructor) are considered to
469be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
470<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
471
472C++11 alias templates
473^^^^^^^^^^^^^^^^^^^^^
474
475Use ``__has_feature(cxx_alias_templates)`` or
476``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
477alias declarations and alias templates is enabled.
478
479C++11 alignment specifiers
480^^^^^^^^^^^^^^^^^^^^^^^^^^
481
482Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
483determine if support for alignment specifiers using ``alignas`` is enabled.
484
485C++11 attributes
486^^^^^^^^^^^^^^^^
487
488Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
489determine if support for attribute parsing with C++11's square bracket notation
490is enabled.
491
492C++11 generalized constant expressions
493^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
494
495Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
496constant expressions (e.g., ``constexpr``) is enabled.
497
498C++11 ``decltype()``
499^^^^^^^^^^^^^^^^^^^^
500
501Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
502determine if support for the ``decltype()`` specifier is enabled. C++11's
503``decltype`` does not require type-completeness of a function call expression.
504Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
505``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
506support for this feature is enabled.
507
508C++11 default template arguments in function templates
509^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
510
511Use ``__has_feature(cxx_default_function_template_args)`` or
512``__has_extension(cxx_default_function_template_args)`` to determine if support
513for default template arguments in function templates is enabled.
514
515C++11 ``default``\ ed functions
516^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
517
518Use ``__has_feature(cxx_defaulted_functions)`` or
519``__has_extension(cxx_defaulted_functions)`` to determine if support for
520defaulted function definitions (with ``= default``) is enabled.
521
522C++11 delegating constructors
523^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
524
525Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
526delegating constructors is enabled.
527
528C++11 ``deleted`` functions
529^^^^^^^^^^^^^^^^^^^^^^^^^^^
530
531Use ``__has_feature(cxx_deleted_functions)`` or
532``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
533function definitions (with ``= delete``) is enabled.
534
535C++11 explicit conversion functions
536^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
537
538Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
539``explicit`` conversion functions is enabled.
540
541C++11 generalized initializers
542^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
543
544Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
545generalized initializers (using braced lists and ``std::initializer_list``) is
546enabled.
547
548C++11 implicit move constructors/assignment operators
549^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
550
551Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
552generate move constructors and move assignment operators where needed.
553
554C++11 inheriting constructors
555^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
556
557Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
Richard Smithe6e68b52013-04-19 17:00:31 +0000558inheriting constructors is enabled.
Sean Silva3872b462012-12-12 23:44:55 +0000559
560C++11 inline namespaces
561^^^^^^^^^^^^^^^^^^^^^^^
562
563Use ``__has_feature(cxx_inline_namespaces)`` or
564``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
565namespaces is enabled.
566
567C++11 lambdas
568^^^^^^^^^^^^^
569
570Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
571determine if support for lambdas is enabled.
572
573C++11 local and unnamed types as template arguments
574^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
575
576Use ``__has_feature(cxx_local_type_template_args)`` or
577``__has_extension(cxx_local_type_template_args)`` to determine if support for
578local and unnamed types as template arguments is enabled.
579
580C++11 noexcept
581^^^^^^^^^^^^^^
582
583Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
584determine if support for noexcept exception specifications is enabled.
585
586C++11 in-class non-static data member initialization
587^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
588
589Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
590initialization of non-static data members is enabled.
591
592C++11 ``nullptr``
593^^^^^^^^^^^^^^^^^
594
595Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
596determine if support for ``nullptr`` is enabled.
597
598C++11 ``override control``
599^^^^^^^^^^^^^^^^^^^^^^^^^^
600
601Use ``__has_feature(cxx_override_control)`` or
602``__has_extension(cxx_override_control)`` to determine if support for the
603override control keywords is enabled.
604
605C++11 reference-qualified functions
606^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
607
608Use ``__has_feature(cxx_reference_qualified_functions)`` or
609``__has_extension(cxx_reference_qualified_functions)`` to determine if support
610for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
611applied to ``*this``) is enabled.
612
613C++11 range-based ``for`` loop
614^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
615
616Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
617determine if support for the range-based for loop is enabled.
618
619C++11 raw string literals
620^^^^^^^^^^^^^^^^^^^^^^^^^
621
622Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
623string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
624
625C++11 rvalue references
626^^^^^^^^^^^^^^^^^^^^^^^
627
628Use ``__has_feature(cxx_rvalue_references)`` or
629``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
630references is enabled.
631
632C++11 ``static_assert()``
633^^^^^^^^^^^^^^^^^^^^^^^^^
634
635Use ``__has_feature(cxx_static_assert)`` or
636``__has_extension(cxx_static_assert)`` to determine if support for compile-time
637assertions using ``static_assert`` is enabled.
638
Richard Smithe6e68b52013-04-19 17:00:31 +0000639C++11 ``thread_local``
640^^^^^^^^^^^^^^^^^^^^^^
641
642Use ``__has_feature(cxx_thread_local)`` to determine if support for
643``thread_local`` variables is enabled.
644
Sean Silva3872b462012-12-12 23:44:55 +0000645C++11 type inference
646^^^^^^^^^^^^^^^^^^^^
647
648Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
649determine C++11 type inference is supported using the ``auto`` specifier. If
650this is disabled, ``auto`` will instead be a storage class specifier, as in C
651or C++98.
652
653C++11 strongly typed enumerations
654^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
655
656Use ``__has_feature(cxx_strong_enums)`` or
657``__has_extension(cxx_strong_enums)`` to determine if support for strongly
658typed, scoped enumerations is enabled.
659
660C++11 trailing return type
661^^^^^^^^^^^^^^^^^^^^^^^^^^
662
663Use ``__has_feature(cxx_trailing_return)`` or
664``__has_extension(cxx_trailing_return)`` to determine if support for the
665alternate function declaration syntax with trailing return type is enabled.
666
667C++11 Unicode string literals
668^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
669
670Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
671string literals is enabled.
672
673C++11 unrestricted unions
674^^^^^^^^^^^^^^^^^^^^^^^^^
675
676Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
677unrestricted unions is enabled.
678
679C++11 user-defined literals
680^^^^^^^^^^^^^^^^^^^^^^^^^^^
681
682Use ``__has_feature(cxx_user_literals)`` to determine if support for
683user-defined literals is enabled.
684
685C++11 variadic templates
686^^^^^^^^^^^^^^^^^^^^^^^^
687
688Use ``__has_feature(cxx_variadic_templates)`` or
689``__has_extension(cxx_variadic_templates)`` to determine if support for
690variadic templates is enabled.
691
Richard Smith7f0ffb32013-05-07 19:32:56 +0000692C++1y
693-----
694
695The features listed below are part of the committee draft for the C++1y
696standard. As a result, all these features are enabled with the ``-std=c++1y``
697or ``-std=gnu++1y`` option when compiling C++ code.
698
699C++1y binary literals
700^^^^^^^^^^^^^^^^^^^^^
701
702Use ``__has_feature(cxx_binary_literals)`` or
703``__has_extension(cxx_binary_literals)`` to determine whether
704binary literals (for instance, ``0b10010``) are recognized. Clang supports this
705feature as an extension in all language modes.
706
707C++1y contextual conversions
708^^^^^^^^^^^^^^^^^^^^^^^^^^^^
709
710Use ``__has_feature(cxx_contextual_conversions)`` or
711``__has_extension(cxx_contextual_conversions)`` to determine if the C++1y rules
712are used when performing an implicit conversion for an array bound in a
713*new-expression*, the operand of a *delete-expression*, an integral constant
Richard Smitha4fb3392013-07-24 17:41:31 +0000714expression, or a condition in a ``switch`` statement.
Richard Smith7f0ffb32013-05-07 19:32:56 +0000715
716C++1y decltype(auto)
717^^^^^^^^^^^^^^^^^^^^
718
719Use ``__has_feature(cxx_decltype_auto)`` or
720``__has_extension(cxx_decltype_auto)`` to determine if support
721for the ``decltype(auto)`` placeholder type is enabled.
722
723C++1y default initializers for aggregates
724^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
725
726Use ``__has_feature(cxx_aggregate_nsdmi)`` or
727``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
728for default initializers in aggregate members is enabled.
729
730C++1y generalized lambda capture
731^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
732
Richard Smith3c3a5222013-07-24 17:51:13 +0000733Use ``__has_feature(cxx_init_capture)`` or
734``__has_extension(cxx_init_capture)`` to determine if support for
735lambda captures with explicit initializers is enabled
Richard Smith7f0ffb32013-05-07 19:32:56 +0000736(for instance, ``[n(0)] { return ++n; }``).
Richard Smith7f0ffb32013-05-07 19:32:56 +0000737
738C++1y generic lambdas
739^^^^^^^^^^^^^^^^^^^^^
740
741Use ``__has_feature(cxx_generic_lambda)`` or
742``__has_extension(cxx_generic_lambda)`` to determine if support for generic
743(polymorphic) lambdas is enabled
744(for instance, ``[] (auto x) { return x + 1; }``).
Richard Smith7f0ffb32013-05-07 19:32:56 +0000745
746C++1y relaxed constexpr
747^^^^^^^^^^^^^^^^^^^^^^^
748
749Use ``__has_feature(cxx_relaxed_constexpr)`` or
750``__has_extension(cxx_relaxed_constexpr)`` to determine if variable
751declarations, local variable modification, and control flow constructs
752are permitted in ``constexpr`` functions.
Richard Smith7f0ffb32013-05-07 19:32:56 +0000753
754C++1y return type deduction
755^^^^^^^^^^^^^^^^^^^^^^^^^^^
756
757Use ``__has_feature(cxx_return_type_deduction)`` or
758``__has_extension(cxx_return_type_deduction)`` to determine if support
759for return type deduction for functions (using ``auto`` as a return type)
760is enabled.
Richard Smith7f0ffb32013-05-07 19:32:56 +0000761
762C++1y runtime-sized arrays
763^^^^^^^^^^^^^^^^^^^^^^^^^^
764
765Use ``__has_feature(cxx_runtime_array)`` or
766``__has_extension(cxx_runtime_array)`` to determine if support
767for arrays of runtime bound (a restricted form of variable-length arrays)
768is enabled.
769Clang's implementation of this feature is incomplete.
770
771C++1y variable templates
772^^^^^^^^^^^^^^^^^^^^^^^^
773
774Use ``__has_feature(cxx_variable_templates)`` or
775``__has_extension(cxx_variable_templates)`` to determine if support for
776templated variable declarations is enabled.
Richard Smith7f0ffb32013-05-07 19:32:56 +0000777
Sean Silva3872b462012-12-12 23:44:55 +0000778C11
779---
780
781The features listed below are part of the C11 standard. As a result, all these
782features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
783compiling C code. Additionally, because these features are all
784backward-compatible, they are available as extensions in all language modes.
785
786C11 alignment specifiers
787^^^^^^^^^^^^^^^^^^^^^^^^
788
789Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
790if support for alignment specifiers using ``_Alignas`` is enabled.
791
792C11 atomic operations
793^^^^^^^^^^^^^^^^^^^^^
794
795Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
796if support for atomic types using ``_Atomic`` is enabled. Clang also provides
797:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
798the ``<stdatomic.h>`` operations on ``_Atomic`` types.
799
800C11 generic selections
801^^^^^^^^^^^^^^^^^^^^^^
802
803Use ``__has_feature(c_generic_selections)`` or
804``__has_extension(c_generic_selections)`` to determine if support for generic
805selections is enabled.
806
807As an extension, the C11 generic selection expression is available in all
808languages supported by Clang. The syntax is the same as that given in the C11
809standard.
810
811In C, type compatibility is decided according to the rules given in the
812appropriate standard, but in C++, which lacks the type compatibility rules used
813in C, types are considered compatible only if they are equivalent.
814
815C11 ``_Static_assert()``
816^^^^^^^^^^^^^^^^^^^^^^^^
817
818Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
819to determine if support for compile-time assertions using ``_Static_assert`` is
820enabled.
821
Richard Smithe6e68b52013-04-19 17:00:31 +0000822C11 ``_Thread_local``
823^^^^^^^^^^^^^^^^^^^^^
824
Ed Schoutenfa7d53f2013-09-14 16:17:20 +0000825Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)``
826to determine if support for ``_Thread_local`` variables is enabled.
Richard Smithe6e68b52013-04-19 17:00:31 +0000827
Stephen Hines651f13c2014-04-23 16:59:28 -0700828Checks for Type Trait Primitives
829================================
830
831Type trait primitives are special builtin constant expressions that can be used
832by the standard C++ library to facilitate or simplify the implementation of
833user-facing type traits in the <type_traits> header.
834
835They are not intended to be used directly by user code because they are
836implementation-defined and subject to change -- as such they're tied closely to
837the supported set of system headers, currently:
838
839* LLVM's own libc++
840* GNU libstdc++
841* The Microsoft standard C++ library
Sean Silva3872b462012-12-12 23:44:55 +0000842
843Clang supports the `GNU C++ type traits
844<http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
845`Microsoft Visual C++ Type traits
Stephen Hines651f13c2014-04-23 16:59:28 -0700846<http://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_.
847
848Feature detection is supported only for some of the primitives at present. User
849code should not use these checks because they bear no direct relation to the
850actual set of type traits supported by the C++ standard library.
851
852For type trait ``__X``, ``__has_extension(X)`` indicates the presence of the
853type trait primitive in the compiler. A simplistic usage example as might be
854seen in standard C++ headers follows:
Sean Silva3872b462012-12-12 23:44:55 +0000855
856.. code-block:: c++
857
858 #if __has_extension(is_convertible_to)
859 template<typename From, typename To>
860 struct is_convertible_to {
861 static const bool value = __is_convertible_to(From, To);
862 };
863 #else
Stephen Hines651f13c2014-04-23 16:59:28 -0700864 // Emulate type trait for compatibility with other compilers.
Sean Silva3872b462012-12-12 23:44:55 +0000865 #endif
866
Stephen Hines651f13c2014-04-23 16:59:28 -0700867The following type trait primitives are supported by Clang:
Sean Silva3872b462012-12-12 23:44:55 +0000868
869* ``__has_nothrow_assign`` (GNU, Microsoft)
870* ``__has_nothrow_copy`` (GNU, Microsoft)
871* ``__has_nothrow_constructor`` (GNU, Microsoft)
872* ``__has_trivial_assign`` (GNU, Microsoft)
873* ``__has_trivial_copy`` (GNU, Microsoft)
874* ``__has_trivial_constructor`` (GNU, Microsoft)
875* ``__has_trivial_destructor`` (GNU, Microsoft)
876* ``__has_virtual_destructor`` (GNU, Microsoft)
877* ``__is_abstract`` (GNU, Microsoft)
878* ``__is_base_of`` (GNU, Microsoft)
879* ``__is_class`` (GNU, Microsoft)
880* ``__is_convertible_to`` (Microsoft)
881* ``__is_empty`` (GNU, Microsoft)
882* ``__is_enum`` (GNU, Microsoft)
883* ``__is_interface_class`` (Microsoft)
884* ``__is_pod`` (GNU, Microsoft)
885* ``__is_polymorphic`` (GNU, Microsoft)
886* ``__is_union`` (GNU, Microsoft)
887* ``__is_literal(type)``: Determines whether the given type is a literal type
888* ``__is_final``: Determines whether the given type is declared with a
889 ``final`` class-virt-specifier.
890* ``__underlying_type(type)``: Retrieves the underlying type for a given
891 ``enum`` type. This trait is required to implement the C++11 standard
892 library.
893* ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value
894 of type ``totype`` can be assigned to from a value of type ``fromtype`` such
895 that no non-trivial functions are called as part of that assignment. This
896 trait is required to implement the C++11 standard library.
897* ``__is_trivially_constructible(type, argtypes...)``: Determines whether a
898 value of type ``type`` can be direct-initialized with arguments of types
899 ``argtypes...`` such that no non-trivial functions are called as part of
900 that initialization. This trait is required to implement the C++11 standard
901 library.
Stephen Hines651f13c2014-04-23 16:59:28 -0700902* ``__is_destructible`` (MSVC 2013): partially implemented
903* ``__is_nothrow_destructible`` (MSVC 2013): partially implemented
904* ``__is_nothrow_assignable`` (MSVC 2013, clang)
905* ``__is_constructible`` (MSVC 2013, clang)
906* ``__is_nothrow_constructible`` (MSVC 2013, clang)
Sean Silva3872b462012-12-12 23:44:55 +0000907
908Blocks
909======
910
911The syntax and high level language feature description is in
Michael Gottesmana65e0762013-01-07 22:24:45 +0000912:doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
913the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
Sean Silva3872b462012-12-12 23:44:55 +0000914
915Query for this feature with ``__has_extension(blocks)``.
916
917Objective-C Features
918====================
919
920Related result types
921--------------------
922
923According to Cocoa conventions, Objective-C methods with certain names
924("``init``", "``alloc``", etc.) always return objects that are an instance of
925the receiving class's type. Such methods are said to have a "related result
926type", meaning that a message send to one of these methods will have the same
927static type as an instance of the receiver class. For example, given the
928following classes:
929
930.. code-block:: objc
931
932 @interface NSObject
933 + (id)alloc;
934 - (id)init;
935 @end
936
937 @interface NSArray : NSObject
938 @end
939
940and this common initialization pattern
941
942.. code-block:: objc
943
944 NSArray *array = [[NSArray alloc] init];
945
946the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
947``alloc`` implicitly has a related result type. Similarly, the type of the
948expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
949related result type and its receiver is known to have the type ``NSArray *``.
950If neither ``alloc`` nor ``init`` had a related result type, the expressions
951would have had type ``id``, as declared in the method signature.
952
953A method with a related result type can be declared by using the type
954``instancetype`` as its result type. ``instancetype`` is a contextual keyword
955that is only permitted in the result type of an Objective-C method, e.g.
956
957.. code-block:: objc
958
959 @interface A
960 + (instancetype)constructAnA;
961 @end
962
963The related result type can also be inferred for some methods. To determine
964whether a method has an inferred related result type, the first word in the
965camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
966and the method will have a related result type if its return type is compatible
967with the type of its class and if:
968
969* the first word is "``alloc``" or "``new``", and the method is a class method,
970 or
971
972* the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
973 and the method is an instance method.
974
975If a method with a related result type is overridden by a subclass method, the
976subclass method must also return a type that is compatible with the subclass
977type. For example:
978
979.. code-block:: objc
980
981 @interface NSString : NSObject
982 - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
983 @end
984
985Related result types only affect the type of a message send or property access
986via the given method. In all other respects, a method with a related result
987type is treated the same way as method that returns ``id``.
988
989Use ``__has_feature(objc_instancetype)`` to determine whether the
990``instancetype`` contextual keyword is available.
991
992Automatic reference counting
993----------------------------
994
Sean Silva159cc9e2013-01-02 13:07:47 +0000995Clang provides support for :doc:`automated reference counting
996<AutomaticReferenceCounting>` in Objective-C, which eliminates the need
Sean Silva3872b462012-12-12 23:44:55 +0000997for manual ``retain``/``release``/``autorelease`` message sends. There are two
998feature macros associated with automatic reference counting:
999``__has_feature(objc_arc)`` indicates the availability of automated reference
1000counting in general, while ``__has_feature(objc_arc_weak)`` indicates that
1001automated reference counting also includes support for ``__weak`` pointers to
1002Objective-C objects.
1003
Sean Silva159cc9e2013-01-02 13:07:47 +00001004.. _objc-fixed-enum:
1005
Sean Silva3872b462012-12-12 23:44:55 +00001006Enumerations with a fixed underlying type
1007-----------------------------------------
1008
1009Clang provides support for C++11 enumerations with a fixed underlying type
1010within Objective-C. For example, one can write an enumeration type as:
1011
1012.. code-block:: c++
1013
1014 typedef enum : unsigned char { Red, Green, Blue } Color;
1015
1016This specifies that the underlying type, which is used to store the enumeration
1017value, is ``unsigned char``.
1018
1019Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
1020underlying types is available in Objective-C.
1021
1022Interoperability with C++11 lambdas
1023-----------------------------------
1024
1025Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
1026permitting a lambda to be implicitly converted to a block pointer with the
1027corresponding signature. For example, consider an API such as ``NSArray``'s
1028array-sorting method:
1029
1030.. code-block:: objc
1031
1032 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
1033
1034``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
1035(^)(id, id)``, and parameters of this type are generally provided with block
1036literals as arguments. However, one can also use a C++11 lambda so long as it
1037provides the same signature (in this case, accepting two parameters of type
1038``id`` and returning an ``NSComparisonResult``):
1039
1040.. code-block:: objc
1041
1042 NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
1043 @"String 02"];
1044 const NSStringCompareOptions comparisonOptions
1045 = NSCaseInsensitiveSearch | NSNumericSearch |
1046 NSWidthInsensitiveSearch | NSForcedOrderingSearch;
1047 NSLocale *currentLocale = [NSLocale currentLocale];
1048 NSArray *sorted
1049 = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
1050 NSRange string1Range = NSMakeRange(0, [s1 length]);
1051 return [s1 compare:s2 options:comparisonOptions
1052 range:string1Range locale:currentLocale];
1053 }];
1054 NSLog(@"sorted: %@", sorted);
1055
1056This code relies on an implicit conversion from the type of the lambda
1057expression (an unnamed, local class type called the *closure type*) to the
1058corresponding block pointer type. The conversion itself is expressed by a
1059conversion operator in that closure type that produces a block pointer with the
1060same signature as the lambda itself, e.g.,
1061
1062.. code-block:: objc
1063
1064 operator NSComparisonResult (^)(id, id)() const;
1065
1066This conversion function returns a new block that simply forwards the two
1067parameters to the lambda object (which it captures by copy), then returns the
1068result. The returned block is first copied (with ``Block_copy``) and then
1069autoreleased. As an optimization, if a lambda expression is immediately
1070converted to a block pointer (as in the first example, above), then the block
1071is not copied and autoreleased: rather, it is given the same lifetime as a
1072block literal written at that point in the program, which avoids the overhead
1073of copying a block to the heap in the common case.
1074
1075The conversion from a lambda to a block pointer is only available in
1076Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
1077management (autorelease).
1078
1079Object Literals and Subscripting
1080--------------------------------
1081
Sean Silva159cc9e2013-01-02 13:07:47 +00001082Clang provides support for :doc:`Object Literals and Subscripting
1083<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
Sean Silva3872b462012-12-12 23:44:55 +00001084programming patterns, makes programs more concise, and improves the safety of
1085container creation. There are several feature macros associated with object
1086literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
1087availability of array literals; ``__has_feature(objc_dictionary_literals)``
1088tests the availability of dictionary literals;
1089``__has_feature(objc_subscripting)`` tests the availability of object
1090subscripting.
1091
1092Objective-C Autosynthesis of Properties
1093---------------------------------------
1094
1095Clang provides support for autosynthesis of declared properties. Using this
1096feature, clang provides default synthesis of those properties not declared
1097@dynamic and not having user provided backing getter and setter methods.
1098``__has_feature(objc_default_synthesize_properties)`` checks for availability
1099of this feature in version of clang being used.
1100
Jordan Rose3115f5b62012-12-15 00:37:01 +00001101.. _langext-objc-retain-release:
1102
1103Objective-C retaining behavior attributes
1104-----------------------------------------
1105
1106In Objective-C, functions and methods are generally assumed to follow the
1107`Cocoa Memory Management
1108<http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
1109conventions for ownership of object arguments and
1110return values. However, there are exceptions, and so Clang provides attributes
1111to allow these exceptions to be documented. This are used by ARC and the
1112`static analyzer <http://clang-analyzer.llvm.org>`_ Some exceptions may be
Stephen Hines651f13c2014-04-23 16:59:28 -07001113better described using the ``objc_method_family`` attribute instead.
Jordan Rose3115f5b62012-12-15 00:37:01 +00001114
1115**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
1116``ns_returns_autoreleased``, ``cf_returns_retained``, and
1117``cf_returns_not_retained`` attributes can be placed on methods and functions
1118that return Objective-C or CoreFoundation objects. They are commonly placed at
1119the end of a function prototype or method declaration:
1120
1121.. code-block:: objc
1122
1123 id foo() __attribute__((ns_returns_retained));
1124
1125 - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
1126
1127The ``*_returns_retained`` attributes specify that the returned object has a +1
1128retain count. The ``*_returns_not_retained`` attributes specify that the return
1129object has a +0 retain count, even if the normal convention for its selector
1130would be +1. ``ns_returns_autoreleased`` specifies that the returned object is
1131+0, but is guaranteed to live at least as long as the next flush of an
1132autorelease pool.
1133
1134**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
1135an parameter declaration; they specify that the argument is expected to have a
1136+1 retain count, which will be balanced in some way by the function or method.
1137The ``ns_consumes_self`` attribute can only be placed on an Objective-C
1138method; it specifies that the method expects its ``self`` parameter to have a
1139+1 retain count, which it will balance in some way.
1140
1141.. code-block:: objc
1142
1143 void foo(__attribute__((ns_consumed)) NSString *string);
1144
1145 - (void) bar __attribute__((ns_consumes_self));
1146 - (void) baz:(id) __attribute__((ns_consumed)) x;
1147
1148Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
1149<http://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
1150
1151Query for these features with ``__has_attribute(ns_consumed)``,
1152``__has_attribute(ns_returns_retained)``, etc.
1153
1154
Ted Kremenek67ffcaa2013-10-15 04:28:42 +00001155Objective-C++ ABI: protocol-qualifier mangling of parameters
1156------------------------------------------------------------
1157
1158Starting with LLVM 3.4, Clang produces a new mangling for parameters whose
1159type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such
1160parameters to be differentiated from those with the regular unqualified ``id``
1161type.
1162
1163This was a non-backward compatible mangling change to the ABI. This change
1164allows proper overloading, and also prevents mangling conflicts with template
1165parameters of protocol-qualified type.
1166
1167Query the presence of this new mangling with
1168``__has_feature(objc_protocol_qualifier_mangling)``.
1169
Stephen Hines651f13c2014-04-23 16:59:28 -07001170.. _langext-overloading:
Sean Silva3872b462012-12-12 23:44:55 +00001171
1172Initializer lists for complex numbers in C
1173==========================================
1174
1175clang supports an extension which allows the following in C:
1176
1177.. code-block:: c++
1178
1179 #include <math.h>
1180 #include <complex.h>
1181 complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
1182
1183This construct is useful because there is no way to separately initialize the
1184real and imaginary parts of a complex variable in standard C, given that clang
1185does not support ``_Imaginary``. (Clang also supports the ``__real__`` and
1186``__imag__`` extensions from gcc, which help in some cases, but are not usable
1187in static initializers.)
1188
1189Note that this extension does not allow eliding the braces; the meaning of the
1190following two lines is different:
1191
1192.. code-block:: c++
1193
1194 complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
1195 complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
1196
1197This extension also works in C++ mode, as far as that goes, but does not apply
1198to the C++ ``std::complex``. (In C++11, list initialization allows the same
1199syntax to be used with ``std::complex`` with the same meaning.)
1200
1201Builtin Functions
1202=================
1203
1204Clang supports a number of builtin library functions with the same syntax as
1205GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
1206``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
1207``__sync_fetch_and_add``, etc. In addition to the GCC builtins, Clang supports
1208a number of builtins that GCC does not, which are listed here.
1209
1210Please note that Clang does not and will not support all of the GCC builtins
1211for vector operations. Instead of using builtins, you should use the functions
1212defined in target-specific header files like ``<xmmintrin.h>``, which define
1213portable wrappers for these. Many of the Clang versions of these functions are
1214implemented directly in terms of :ref:`extended vector support
1215<langext-vectors>` instead of builtins, in order to reduce the number of
1216builtins that we need to implement.
1217
1218``__builtin_readcyclecounter``
1219------------------------------
1220
1221``__builtin_readcyclecounter`` is used to access the cycle counter register (or
1222a similar low-latency, high-accuracy clock) on those targets that support it.
1223
1224**Syntax**:
1225
1226.. code-block:: c++
1227
1228 __builtin_readcyclecounter()
1229
1230**Example of Use**:
1231
1232.. code-block:: c++
1233
1234 unsigned long long t0 = __builtin_readcyclecounter();
1235 do_something();
1236 unsigned long long t1 = __builtin_readcyclecounter();
1237 unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
1238
1239**Description**:
1240
1241The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
1242which may be either global or process/thread-specific depending on the target.
1243As the backing counters often overflow quickly (on the order of seconds) this
1244should only be used for timing small intervals. When not supported by the
1245target, the return value is always zero. This builtin takes no arguments and
1246produces an unsigned long long result.
1247
Tim Northoveref7c6e72013-05-23 19:14:12 +00001248Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
1249that even if present, its use may depend on run-time privilege or other OS
1250controlled state.
Sean Silva3872b462012-12-12 23:44:55 +00001251
1252.. _langext-__builtin_shufflevector:
1253
1254``__builtin_shufflevector``
1255---------------------------
1256
1257``__builtin_shufflevector`` is used to express generic vector
1258permutation/shuffle/swizzle operations. This builtin is also very important
1259for the implementation of various target-specific header files like
1260``<xmmintrin.h>``.
1261
1262**Syntax**:
1263
1264.. code-block:: c++
1265
1266 __builtin_shufflevector(vec1, vec2, index1, index2, ...)
1267
1268**Examples**:
1269
1270.. code-block:: c++
1271
Craig Topper6f4f8082013-08-03 17:40:38 +00001272 // identity operation - return 4-element vector v1.
1273 __builtin_shufflevector(v1, v1, 0, 1, 2, 3)
Sean Silva3872b462012-12-12 23:44:55 +00001274
1275 // "Splat" element 0 of V1 into a 4-element result.
1276 __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
1277
1278 // Reverse 4-element vector V1.
1279 __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
1280
1281 // Concatenate every other element of 4-element vectors V1 and V2.
1282 __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
1283
1284 // Concatenate every other element of 8-element vectors V1 and V2.
1285 __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
1286
Craig Topper6f4f8082013-08-03 17:40:38 +00001287 // Shuffle v1 with some elements being undefined
1288 __builtin_shufflevector(v1, v1, 3, -1, 1, -1)
1289
Sean Silva3872b462012-12-12 23:44:55 +00001290**Description**:
1291
1292The first two arguments to ``__builtin_shufflevector`` are vectors that have
1293the same element type. The remaining arguments are a list of integers that
1294specify the elements indices of the first two vectors that should be extracted
1295and returned in a new vector. These element indices are numbered sequentially
1296starting with the first vector, continuing into the second vector. Thus, if
1297``vec1`` is a 4-element vector, index 5 would refer to the second element of
Craig Topper6f4f8082013-08-03 17:40:38 +00001298``vec2``. An index of -1 can be used to indicate that the corresponding element
1299in the returned vector is a don't care and can be optimized by the backend.
Sean Silva3872b462012-12-12 23:44:55 +00001300
1301The result of ``__builtin_shufflevector`` is a vector with the same element
1302type as ``vec1``/``vec2`` but that has an element count equal to the number of
1303indices specified.
1304
1305Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
1306
Hal Finkel414a1bd2013-09-18 03:29:45 +00001307``__builtin_convertvector``
1308---------------------------
1309
1310``__builtin_convertvector`` is used to express generic vector
1311type-conversion operations. The input vector and the output vector
1312type must have the same number of elements.
1313
1314**Syntax**:
1315
1316.. code-block:: c++
1317
1318 __builtin_convertvector(src_vec, dst_vec_type)
1319
1320**Examples**:
1321
1322.. code-block:: c++
1323
1324 typedef double vector4double __attribute__((__vector_size__(32)));
1325 typedef float vector4float __attribute__((__vector_size__(16)));
1326 typedef short vector4short __attribute__((__vector_size__(8)));
1327 vector4float vf; vector4short vs;
1328
1329 // convert from a vector of 4 floats to a vector of 4 doubles.
1330 __builtin_convertvector(vf, vector4double)
1331 // equivalent to:
1332 (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }
1333
1334 // convert from a vector of 4 shorts to a vector of 4 floats.
1335 __builtin_convertvector(vs, vector4float)
1336 // equivalent to:
1337 (vector4float) { (float) vf[0], (float) vf[1], (float) vf[2], (float) vf[3] }
1338
1339**Description**:
1340
1341The first argument to ``__builtin_convertvector`` is a vector, and the second
1342argument is a vector type with the same number of elements as the first
1343argument.
1344
1345The result of ``__builtin_convertvector`` is a vector with the same element
1346type as the second argument, with a value defined in terms of the action of a
1347C-style cast applied to each element of the first argument.
1348
1349Query for this feature with ``__has_builtin(__builtin_convertvector)``.
1350
Sean Silva3872b462012-12-12 23:44:55 +00001351``__builtin_unreachable``
1352-------------------------
1353
1354``__builtin_unreachable`` is used to indicate that a specific point in the
1355program cannot be reached, even if the compiler might otherwise think it can.
1356This is useful to improve optimization and eliminates certain warnings. For
1357example, without the ``__builtin_unreachable`` in the example below, the
1358compiler assumes that the inline asm can fall through and prints a "function
1359declared '``noreturn``' should not return" warning.
1360
1361**Syntax**:
1362
1363.. code-block:: c++
1364
1365 __builtin_unreachable()
1366
1367**Example of use**:
1368
1369.. code-block:: c++
1370
1371 void myabort(void) __attribute__((noreturn));
1372 void myabort(void) {
1373 asm("int3");
1374 __builtin_unreachable();
1375 }
1376
1377**Description**:
1378
1379The ``__builtin_unreachable()`` builtin has completely undefined behavior.
1380Since it has undefined behavior, it is a statement that it is never reached and
1381the optimizer can take advantage of this to produce better code. This builtin
1382takes no arguments and produces a void result.
1383
1384Query for this feature with ``__has_builtin(__builtin_unreachable)``.
1385
1386``__sync_swap``
1387---------------
1388
1389``__sync_swap`` is used to atomically swap integers or pointers in memory.
1390
1391**Syntax**:
1392
1393.. code-block:: c++
1394
1395 type __sync_swap(type *ptr, type value, ...)
1396
1397**Example of Use**:
1398
1399.. code-block:: c++
1400
1401 int old_value = __sync_swap(&value, new_value);
1402
1403**Description**:
1404
1405The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
1406atomic intrinsics to allow code to atomically swap the current value with the
1407new value. More importantly, it helps developers write more efficient and
1408correct code by avoiding expensive loops around
1409``__sync_bool_compare_and_swap()`` or relying on the platform specific
1410implementation details of ``__sync_lock_test_and_set()``. The
1411``__sync_swap()`` builtin is a full barrier.
1412
Richard Smith5154dce2013-07-11 02:27:57 +00001413``__builtin_addressof``
1414-----------------------
1415
1416``__builtin_addressof`` performs the functionality of the built-in ``&``
1417operator, ignoring any ``operator&`` overload. This is useful in constant
1418expressions in C++11, where there is no other way to take the address of an
1419object that overloads ``operator&``.
1420
1421**Example of use**:
1422
1423.. code-block:: c++
1424
1425 template<typename T> constexpr T *addressof(T &value) {
1426 return __builtin_addressof(value);
1427 }
1428
Michael Gottesman377b8c62013-01-13 04:35:31 +00001429Multiprecision Arithmetic Builtins
1430----------------------------------
1431
1432Clang provides a set of builtins which expose multiprecision arithmetic in a
1433manner amenable to C. They all have the following form:
1434
1435.. code-block:: c
1436
1437 unsigned x = ..., y = ..., carryin = ..., carryout;
1438 unsigned sum = __builtin_addc(x, y, carryin, &carryout);
1439
1440Thus one can form a multiprecision addition chain in the following manner:
1441
1442.. code-block:: c
1443
1444 unsigned *x, *y, *z, carryin=0, carryout;
1445 z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
1446 carryin = carryout;
1447 z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
1448 carryin = carryout;
1449 z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
1450 carryin = carryout;
1451 z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
1452
1453The complete list of builtins are:
1454
1455.. code-block:: c
1456
Michael Gottesmanee76e722013-06-18 20:40:40 +00001457 unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
Michael Gottesman377b8c62013-01-13 04:35:31 +00001458 unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
1459 unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
1460 unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
1461 unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
Michael Gottesmanee76e722013-06-18 20:40:40 +00001462 unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
Michael Gottesman377b8c62013-01-13 04:35:31 +00001463 unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
1464 unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
1465 unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
1466 unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
1467
Michael Gottesman98d1ec12013-06-20 23:28:10 +00001468Checked Arithmetic Builtins
1469---------------------------
1470
1471Clang provides a set of builtins that implement checked arithmetic for security
1472critical applications in a manner that is fast and easily expressable in C. As
1473an example of their usage:
1474
1475.. code-block:: c
1476
1477 errorcode_t security_critical_application(...) {
1478 unsigned x, y, result;
1479 ...
1480 if (__builtin_umul_overflow(x, y, &result))
1481 return kErrorCodeHackers;
1482 ...
1483 use_multiply(result);
1484 ...
1485 }
1486
1487A complete enumeration of the builtins are:
1488
1489.. code-block:: c
1490
1491 bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum);
1492 bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);
1493 bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);
1494 bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff);
1495 bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);
1496 bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);
1497 bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod);
1498 bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);
1499 bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);
1500 bool __builtin_sadd_overflow (int x, int y, int *sum);
1501 bool __builtin_saddl_overflow (long x, long y, long *sum);
1502 bool __builtin_saddll_overflow(long long x, long long y, long long *sum);
1503 bool __builtin_ssub_overflow (int x, int y, int *diff);
1504 bool __builtin_ssubl_overflow (long x, long y, long *diff);
1505 bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);
1506 bool __builtin_smul_overflow (int x, int y, int *prod);
1507 bool __builtin_smull_overflow (long x, long y, long *prod);
1508 bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
1509
1510
Sean Silva3872b462012-12-12 23:44:55 +00001511.. _langext-__c11_atomic:
1512
1513__c11_atomic builtins
1514---------------------
1515
1516Clang provides a set of builtins which are intended to be used to implement
1517C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the
1518``_explicit`` form of the corresponding C11 operation, and are named with a
1519``__c11_`` prefix. The supported operations are:
1520
1521* ``__c11_atomic_init``
1522* ``__c11_atomic_thread_fence``
1523* ``__c11_atomic_signal_fence``
1524* ``__c11_atomic_is_lock_free``
1525* ``__c11_atomic_store``
1526* ``__c11_atomic_load``
1527* ``__c11_atomic_exchange``
1528* ``__c11_atomic_compare_exchange_strong``
1529* ``__c11_atomic_compare_exchange_weak``
1530* ``__c11_atomic_fetch_add``
1531* ``__c11_atomic_fetch_sub``
1532* ``__c11_atomic_fetch_and``
1533* ``__c11_atomic_fetch_or``
1534* ``__c11_atomic_fetch_xor``
1535
Tim Northover09df2b02013-07-16 09:47:53 +00001536Low-level ARM exclusive memory builtins
1537---------------------------------------
1538
1539Clang provides overloaded builtins giving direct access to the three key ARM
1540instructions for implementing atomic operations.
1541
1542.. code-block:: c
Sean Silva74106d32013-09-09 19:50:40 +00001543
Tim Northover09df2b02013-07-16 09:47:53 +00001544 T __builtin_arm_ldrex(const volatile T *addr);
1545 int __builtin_arm_strex(T val, volatile T *addr);
1546 void __builtin_arm_clrex(void);
1547
1548The types ``T`` currently supported are:
Stephen Hines651f13c2014-04-23 16:59:28 -07001549* Integer types with width at most 64 bits (or 128 bits on ARM64).
Tim Northover09df2b02013-07-16 09:47:53 +00001550* Floating-point types
1551* Pointer types.
1552
1553Note that the compiler does not guarantee it will not insert stores which clear
1554the exclusive monitor in between an ``ldrex`` and its paired ``strex``. In
1555practice this is only usually a risk when the extra store is on the same cache
1556line as the variable being modified and Clang will only insert stack stores on
1557its own, so it is best not to use these operations on variables with automatic
1558storage duration.
1559
1560Also, loads and stores may be implicit in code written between the ``ldrex`` and
1561``strex``. Clang will not necessarily mitigate the effects of these either, so
1562care should be exercised.
1563
1564For these reasons the higher level atomic primitives should be preferred where
1565possible.
1566
Sean Silva3872b462012-12-12 23:44:55 +00001567Non-standard C++11 Attributes
1568=============================
1569
Richard Smith6f488192013-02-14 00:13:34 +00001570Clang's non-standard C++11 attributes live in the ``clang`` attribute
1571namespace.
Sean Silva3872b462012-12-12 23:44:55 +00001572
Stephen Hines651f13c2014-04-23 16:59:28 -07001573Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which
Richard Smith6f488192013-02-14 00:13:34 +00001574are accepted with the ``__attribute__((foo))`` syntax are also accepted as
1575``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
1576(see the list of `GCC function attributes
1577<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
1578attributes <http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
1579`GCC type attributes
Richard Smith9e0a65e2013-07-11 00:27:05 +00001580<http://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
Richard Smith6f488192013-02-14 00:13:34 +00001581implementation, these attributes must appertain to the *declarator-id* in a
1582declaration, which means they must go either at the start of the declaration or
1583immediately after the name being declared.
1584
1585For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
1586also applies the GNU ``noreturn`` attribute to ``f``.
1587
1588.. code-block:: c++
1589
1590 [[gnu::unused]] int a, f [[gnu::noreturn]] ();
1591
Sean Silva3872b462012-12-12 23:44:55 +00001592Target-Specific Extensions
1593==========================
1594
1595Clang supports some language features conditionally on some targets.
1596
1597X86/X86-64 Language Extensions
1598------------------------------
1599
1600The X86 backend has these language extensions:
1601
1602Memory references off the GS segment
1603^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1604
1605Annotating a pointer with address space #256 causes it to be code generated
1606relative to the X86 GS segment register, and address space #257 causes it to be
1607relative to the X86 FS segment. Note that this is a very very low-level
1608feature that should only be used if you know what you're doing (for example in
1609an OS kernel).
1610
1611Here is an example:
1612
1613.. code-block:: c++
1614
1615 #define GS_RELATIVE __attribute__((address_space(256)))
1616 int foo(int GS_RELATIVE *P) {
1617 return *P;
1618 }
1619
1620Which compiles to (on X86-32):
1621
1622.. code-block:: gas
1623
1624 _foo:
1625 movl 4(%esp), %eax
1626 movl %gs:(%eax), %eax
1627 ret
1628
Jordan Rose3115f5b62012-12-15 00:37:01 +00001629Extensions for Static Analysis
Dmitri Gribenko1228d662012-12-15 14:25:25 +00001630==============================
Sean Silva3872b462012-12-12 23:44:55 +00001631
1632Clang supports additional attributes that are useful for documenting program
Jordan Rose3115f5b62012-12-15 00:37:01 +00001633invariants and rules for static analysis tools, such as the `Clang Static
1634Analyzer <http://clang-analyzer.llvm.org/>`_. These attributes are documented
1635in the analyzer's `list of source-level annotations
1636<http://clang-analyzer.llvm.org/annotations.html>`_.
Sean Silva3872b462012-12-12 23:44:55 +00001637
Sean Silva3872b462012-12-12 23:44:55 +00001638
Jordan Rose3115f5b62012-12-15 00:37:01 +00001639Extensions for Dynamic Analysis
Dmitri Gribenko1228d662012-12-15 14:25:25 +00001640===============================
Sean Silva3872b462012-12-12 23:44:55 +00001641
Sean Silva3872b462012-12-12 23:44:55 +00001642Use ``__has_feature(address_sanitizer)`` to check if the code is being built
Dmitri Gribenko1228d662012-12-15 14:25:25 +00001643with :doc:`AddressSanitizer`.
Sean Silva3872b462012-12-12 23:44:55 +00001644
Kostya Serebryany85aee962013-02-26 06:58:27 +00001645Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
1646with :doc:`ThreadSanitizer`.
1647
Kostya Serebryany85aee962013-02-26 06:58:27 +00001648Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
1649with :doc:`MemorySanitizer`.