blob: 110b016888466c818ea144faff6c11a848debe3d [file] [log] [blame]
Sean Silva709c44d2012-12-12 23:44:55 +00001=========================
2Clang Language Extensions
3=========================
4
5.. contents::
6 :local:
Sean Silva13d43fe2013-01-02 21:09:58 +00007 :depth: 1
Sean Silva709c44d2012-12-12 23:44:55 +00008
Sean Silvaf380e0e2013-01-02 21:03:11 +00009.. toctree::
10 :hidden:
11
12 ObjectiveCLiterals
13 BlockLanguageSpec
Michael Gottesman6fd58462013-01-07 22:24:45 +000014 Block-ABI-Apple
15 AutomaticReferenceCounting
Sean Silvaf380e0e2013-01-02 21:03:11 +000016
Sean Silva709c44d2012-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 Silva173d2522013-01-02 13:07:47 +000099to the language standard, such as e.g. :doc:`AddressSanitizer
100<AddressSanitizer>`.
Sean Silva709c44d2012-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
Aaron Ballmana4bb4b92014-01-09 23:11:13 +0000116an 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 Silva709c44d2012-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
Aaron Ballmana4bb4b92014-01-09 23:11:13 +0000137
Sean Silva709c44d2012-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 Gribenko764ea242013-01-17 17:04:54 +0000144failing ``#include`` directive. Include file checking macros must be used
145as expressions in ``#if`` or ``#elif`` preprocessing directives.
Sean Silva709c44d2012-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 Smithccfc9ff2013-07-11 00:27:05 +0000163To test for this feature, use ``#if defined(__has_include)``:
164
165.. code-block:: c++
166
Sean Silva709c44d2012-12-12 23:44:55 +0000167 // To avoid problem with non-clang compilers not having this macro.
Richard Smithccfc9ff2013-07-11 00:27:05 +0000168 #if defined(__has_include)
169 #if __has_include("myinclude.h")
Sean Silva709c44d2012-12-12 23:44:55 +0000170 # include "myinclude.h"
171 #endif
Richard Smithccfc9ff2013-07-11 00:27:05 +0000172 #endif
Sean Silva709c44d2012-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 Smithccfc9ff2013-07-11 00:27:05 +0000193 #if defined(__has_include_next)
194 #if __has_include_next("myinclude.h")
Sean Silva709c44d2012-12-12 23:44:55 +0000195 # include_next "myinclude.h"
196 #endif
Richard Smithccfc9ff2013-07-11 00:27:05 +0000197 #endif
Sean Silva709c44d2012-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
429Availability attribute
430======================
431
432Clang introduces the ``availability`` attribute, which can be placed on
433declarations to describe the lifecycle of that declaration relative to
434operating system versions. Consider the function declaration for a
435hypothetical function ``f``:
436
437.. code-block:: c++
438
439 void f(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
440
441The availability attribute states that ``f`` was introduced in Mac OS X 10.4,
442deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7. This information
443is used by Clang to determine when it is safe to use ``f``: for example, if
444Clang is instructed to compile code for Mac OS X 10.5, a call to ``f()``
445succeeds. If Clang is instructed to compile code for Mac OS X 10.6, the call
446succeeds but Clang emits a warning specifying that the function is deprecated.
447Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call
448fails because ``f()`` is no longer available.
449
Douglas Gregor250ee632013-01-16 01:12:31 +0000450The availability attribute is a comma-separated list starting with the
Sean Silva709c44d2012-12-12 23:44:55 +0000451platform name and then including clauses specifying important milestones in the
452declaration's lifetime (in any order) along with additional information. Those
453clauses can be:
454
455introduced=\ *version*
456 The first version in which this declaration was introduced.
457
458deprecated=\ *version*
459 The first version in which this declaration was deprecated, meaning that
460 users should migrate away from this API.
461
462obsoleted=\ *version*
463 The first version in which this declaration was obsoleted, meaning that it
464 was removed completely and can no longer be used.
465
466unavailable
467 This declaration is never available on this platform.
468
469message=\ *string-literal*
470 Additional message text that Clang will provide when emitting a warning or
471 error about use of a deprecated or obsoleted declaration. Useful to direct
472 users to replacement APIs.
473
474Multiple availability attributes can be placed on a declaration, which may
475correspond to different platforms. Only the availability attribute with the
476platform corresponding to the target platform will be used; any others will be
477ignored. If no availability attribute specifies availability for the current
478target platform, the availability attributes are ignored. Supported platforms
479are:
480
481``ios``
482 Apple's iOS operating system. The minimum deployment target is specified by
483 the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
484 command-line arguments.
485
486``macosx``
487 Apple's Mac OS X operating system. The minimum deployment target is
488 specified by the ``-mmacosx-version-min=*version*`` command-line argument.
489
490A declaration can be used even when deploying back to a platform version prior
491to when the declaration was introduced. When this happens, the declaration is
492`weakly linked
493<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
494as if the ``weak_import`` attribute were added to the declaration. A
495weakly-linked declaration may or may not be present a run-time, and a program
496can determine whether the declaration is present by checking whether the
497address of that declaration is non-NULL.
498
Dmitri Gribenkofb5b2242013-01-16 01:17:05 +0000499If there are multiple declarations of the same entity, the availability
Douglas Gregor250ee632013-01-16 01:12:31 +0000500attributes must either match on a per-platform basis or later
501declarations must not have availability attributes for that
502platform. For example:
503
504.. code-block:: c
505
506 void g(void) __attribute__((availability(macosx,introduced=10.4)));
507 void g(void) __attribute__((availability(macosx,introduced=10.4))); // okay, matches
508 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
509 void g(void); // okay, inherits both macosx and ios availability from above.
510 void g(void) __attribute__((availability(macosx,introduced=10.5))); // error: mismatch
511
512When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
513
514.. code-block:: objc
515
516 @interface A
517 - (id)method __attribute__((availability(macosx,introduced=10.4)));
518 - (id)method2 __attribute__((availability(macosx,introduced=10.4)));
519 @end
520
521 @interface B : A
522 - (id)method __attribute__((availability(macosx,introduced=10.3))); // okay: method moved into base class later
523 - (id)method __attribute__((availability(macosx,introduced=10.5))); // error: this method was available via the base class in 10.4
524 @end
525
Sean Silva709c44d2012-12-12 23:44:55 +0000526Checks for Standard Language Features
527=====================================
528
529The ``__has_feature`` macro can be used to query if certain standard language
530features are enabled. The ``__has_extension`` macro can be used to query if
531language features are available as an extension when compiling for a standard
532which does not provide them. The features which can be tested are listed here.
533
534C++98
535-----
536
537The features listed below are part of the C++98 standard. These features are
538enabled by default when compiling C++ code.
539
540C++ exceptions
541^^^^^^^^^^^^^^
542
543Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
544enabled. For example, compiling code with ``-fno-exceptions`` disables C++
545exceptions.
546
547C++ RTTI
548^^^^^^^^
549
550Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For
551example, compiling code with ``-fno-rtti`` disables the use of RTTI.
552
553C++11
554-----
555
556The features listed below are part of the C++11 standard. As a result, all
557these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
558when compiling C++ code.
559
560C++11 SFINAE includes access control
561^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
562
563Use ``__has_feature(cxx_access_control_sfinae)`` or
564``__has_extension(cxx_access_control_sfinae)`` to determine whether
565access-control errors (e.g., calling a private constructor) are considered to
566be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
567<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
568
569C++11 alias templates
570^^^^^^^^^^^^^^^^^^^^^
571
572Use ``__has_feature(cxx_alias_templates)`` or
573``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
574alias declarations and alias templates is enabled.
575
576C++11 alignment specifiers
577^^^^^^^^^^^^^^^^^^^^^^^^^^
578
579Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
580determine if support for alignment specifiers using ``alignas`` is enabled.
581
582C++11 attributes
583^^^^^^^^^^^^^^^^
584
585Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
586determine if support for attribute parsing with C++11's square bracket notation
587is enabled.
588
589C++11 generalized constant expressions
590^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
591
592Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
593constant expressions (e.g., ``constexpr``) is enabled.
594
595C++11 ``decltype()``
596^^^^^^^^^^^^^^^^^^^^
597
598Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
599determine if support for the ``decltype()`` specifier is enabled. C++11's
600``decltype`` does not require type-completeness of a function call expression.
601Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
602``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
603support for this feature is enabled.
604
605C++11 default template arguments in function templates
606^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
607
608Use ``__has_feature(cxx_default_function_template_args)`` or
609``__has_extension(cxx_default_function_template_args)`` to determine if support
610for default template arguments in function templates is enabled.
611
612C++11 ``default``\ ed functions
613^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
614
615Use ``__has_feature(cxx_defaulted_functions)`` or
616``__has_extension(cxx_defaulted_functions)`` to determine if support for
617defaulted function definitions (with ``= default``) is enabled.
618
619C++11 delegating constructors
620^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
621
622Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
623delegating constructors is enabled.
624
625C++11 ``deleted`` functions
626^^^^^^^^^^^^^^^^^^^^^^^^^^^
627
628Use ``__has_feature(cxx_deleted_functions)`` or
629``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
630function definitions (with ``= delete``) is enabled.
631
632C++11 explicit conversion functions
633^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
634
635Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
636``explicit`` conversion functions is enabled.
637
638C++11 generalized initializers
639^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
640
641Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
642generalized initializers (using braced lists and ``std::initializer_list``) is
643enabled.
644
645C++11 implicit move constructors/assignment operators
646^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
647
648Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
649generate move constructors and move assignment operators where needed.
650
651C++11 inheriting constructors
652^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
653
654Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
Richard Smith25b555a2013-04-19 17:00:31 +0000655inheriting constructors is enabled.
Sean Silva709c44d2012-12-12 23:44:55 +0000656
657C++11 inline namespaces
658^^^^^^^^^^^^^^^^^^^^^^^
659
660Use ``__has_feature(cxx_inline_namespaces)`` or
661``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
662namespaces is enabled.
663
664C++11 lambdas
665^^^^^^^^^^^^^
666
667Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
668determine if support for lambdas is enabled.
669
670C++11 local and unnamed types as template arguments
671^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
672
673Use ``__has_feature(cxx_local_type_template_args)`` or
674``__has_extension(cxx_local_type_template_args)`` to determine if support for
675local and unnamed types as template arguments is enabled.
676
677C++11 noexcept
678^^^^^^^^^^^^^^
679
680Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
681determine if support for noexcept exception specifications is enabled.
682
683C++11 in-class non-static data member initialization
684^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
685
686Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
687initialization of non-static data members is enabled.
688
689C++11 ``nullptr``
690^^^^^^^^^^^^^^^^^
691
692Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
693determine if support for ``nullptr`` is enabled.
694
695C++11 ``override control``
696^^^^^^^^^^^^^^^^^^^^^^^^^^
697
698Use ``__has_feature(cxx_override_control)`` or
699``__has_extension(cxx_override_control)`` to determine if support for the
700override control keywords is enabled.
701
702C++11 reference-qualified functions
703^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
704
705Use ``__has_feature(cxx_reference_qualified_functions)`` or
706``__has_extension(cxx_reference_qualified_functions)`` to determine if support
707for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
708applied to ``*this``) is enabled.
709
710C++11 range-based ``for`` loop
711^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
712
713Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
714determine if support for the range-based for loop is enabled.
715
716C++11 raw string literals
717^^^^^^^^^^^^^^^^^^^^^^^^^
718
719Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
720string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
721
722C++11 rvalue references
723^^^^^^^^^^^^^^^^^^^^^^^
724
725Use ``__has_feature(cxx_rvalue_references)`` or
726``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
727references is enabled.
728
729C++11 ``static_assert()``
730^^^^^^^^^^^^^^^^^^^^^^^^^
731
732Use ``__has_feature(cxx_static_assert)`` or
733``__has_extension(cxx_static_assert)`` to determine if support for compile-time
734assertions using ``static_assert`` is enabled.
735
Richard Smith25b555a2013-04-19 17:00:31 +0000736C++11 ``thread_local``
737^^^^^^^^^^^^^^^^^^^^^^
738
739Use ``__has_feature(cxx_thread_local)`` to determine if support for
740``thread_local`` variables is enabled.
741
Sean Silva709c44d2012-12-12 23:44:55 +0000742C++11 type inference
743^^^^^^^^^^^^^^^^^^^^
744
745Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
746determine C++11 type inference is supported using the ``auto`` specifier. If
747this is disabled, ``auto`` will instead be a storage class specifier, as in C
748or C++98.
749
750C++11 strongly typed enumerations
751^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
752
753Use ``__has_feature(cxx_strong_enums)`` or
754``__has_extension(cxx_strong_enums)`` to determine if support for strongly
755typed, scoped enumerations is enabled.
756
757C++11 trailing return type
758^^^^^^^^^^^^^^^^^^^^^^^^^^
759
760Use ``__has_feature(cxx_trailing_return)`` or
761``__has_extension(cxx_trailing_return)`` to determine if support for the
762alternate function declaration syntax with trailing return type is enabled.
763
764C++11 Unicode string literals
765^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
766
767Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
768string literals is enabled.
769
770C++11 unrestricted unions
771^^^^^^^^^^^^^^^^^^^^^^^^^
772
773Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
774unrestricted unions is enabled.
775
776C++11 user-defined literals
777^^^^^^^^^^^^^^^^^^^^^^^^^^^
778
779Use ``__has_feature(cxx_user_literals)`` to determine if support for
780user-defined literals is enabled.
781
782C++11 variadic templates
783^^^^^^^^^^^^^^^^^^^^^^^^
784
785Use ``__has_feature(cxx_variadic_templates)`` or
786``__has_extension(cxx_variadic_templates)`` to determine if support for
787variadic templates is enabled.
788
Richard Smith0a715422013-05-07 19:32:56 +0000789C++1y
790-----
791
792The features listed below are part of the committee draft for the C++1y
793standard. As a result, all these features are enabled with the ``-std=c++1y``
794or ``-std=gnu++1y`` option when compiling C++ code.
795
796C++1y binary literals
797^^^^^^^^^^^^^^^^^^^^^
798
799Use ``__has_feature(cxx_binary_literals)`` or
800``__has_extension(cxx_binary_literals)`` to determine whether
801binary literals (for instance, ``0b10010``) are recognized. Clang supports this
802feature as an extension in all language modes.
803
804C++1y contextual conversions
805^^^^^^^^^^^^^^^^^^^^^^^^^^^^
806
807Use ``__has_feature(cxx_contextual_conversions)`` or
808``__has_extension(cxx_contextual_conversions)`` to determine if the C++1y rules
809are used when performing an implicit conversion for an array bound in a
810*new-expression*, the operand of a *delete-expression*, an integral constant
Richard Smithc0f7b812013-07-24 17:41:31 +0000811expression, or a condition in a ``switch`` statement.
Richard Smith0a715422013-05-07 19:32:56 +0000812
813C++1y decltype(auto)
814^^^^^^^^^^^^^^^^^^^^
815
816Use ``__has_feature(cxx_decltype_auto)`` or
817``__has_extension(cxx_decltype_auto)`` to determine if support
818for the ``decltype(auto)`` placeholder type is enabled.
819
820C++1y default initializers for aggregates
821^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
822
823Use ``__has_feature(cxx_aggregate_nsdmi)`` or
824``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
825for default initializers in aggregate members is enabled.
826
827C++1y generalized lambda capture
828^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
829
Richard Smith4fb09722013-07-24 17:51:13 +0000830Use ``__has_feature(cxx_init_capture)`` or
831``__has_extension(cxx_init_capture)`` to determine if support for
832lambda captures with explicit initializers is enabled
Richard Smith0a715422013-05-07 19:32:56 +0000833(for instance, ``[n(0)] { return ++n; }``).
834Clang does not yet support this feature.
835
836C++1y generic lambdas
837^^^^^^^^^^^^^^^^^^^^^
838
839Use ``__has_feature(cxx_generic_lambda)`` or
840``__has_extension(cxx_generic_lambda)`` to determine if support for generic
841(polymorphic) lambdas is enabled
842(for instance, ``[] (auto x) { return x + 1; }``).
843Clang does not yet support this feature.
844
845C++1y relaxed constexpr
846^^^^^^^^^^^^^^^^^^^^^^^
847
848Use ``__has_feature(cxx_relaxed_constexpr)`` or
849``__has_extension(cxx_relaxed_constexpr)`` to determine if variable
850declarations, local variable modification, and control flow constructs
851are permitted in ``constexpr`` functions.
Richard Smith0a715422013-05-07 19:32:56 +0000852
853C++1y return type deduction
854^^^^^^^^^^^^^^^^^^^^^^^^^^^
855
856Use ``__has_feature(cxx_return_type_deduction)`` or
857``__has_extension(cxx_return_type_deduction)`` to determine if support
858for return type deduction for functions (using ``auto`` as a return type)
859is enabled.
Richard Smith0a715422013-05-07 19:32:56 +0000860
861C++1y runtime-sized arrays
862^^^^^^^^^^^^^^^^^^^^^^^^^^
863
864Use ``__has_feature(cxx_runtime_array)`` or
865``__has_extension(cxx_runtime_array)`` to determine if support
866for arrays of runtime bound (a restricted form of variable-length arrays)
867is enabled.
868Clang's implementation of this feature is incomplete.
869
870C++1y variable templates
871^^^^^^^^^^^^^^^^^^^^^^^^
872
873Use ``__has_feature(cxx_variable_templates)`` or
874``__has_extension(cxx_variable_templates)`` to determine if support for
875templated variable declarations is enabled.
876Clang does not yet support this feature.
877
Sean Silva709c44d2012-12-12 23:44:55 +0000878C11
879---
880
881The features listed below are part of the C11 standard. As a result, all these
882features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
883compiling C code. Additionally, because these features are all
884backward-compatible, they are available as extensions in all language modes.
885
886C11 alignment specifiers
887^^^^^^^^^^^^^^^^^^^^^^^^
888
889Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
890if support for alignment specifiers using ``_Alignas`` is enabled.
891
892C11 atomic operations
893^^^^^^^^^^^^^^^^^^^^^
894
895Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
896if support for atomic types using ``_Atomic`` is enabled. Clang also provides
897:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
898the ``<stdatomic.h>`` operations on ``_Atomic`` types.
899
900C11 generic selections
901^^^^^^^^^^^^^^^^^^^^^^
902
903Use ``__has_feature(c_generic_selections)`` or
904``__has_extension(c_generic_selections)`` to determine if support for generic
905selections is enabled.
906
907As an extension, the C11 generic selection expression is available in all
908languages supported by Clang. The syntax is the same as that given in the C11
909standard.
910
911In C, type compatibility is decided according to the rules given in the
912appropriate standard, but in C++, which lacks the type compatibility rules used
913in C, types are considered compatible only if they are equivalent.
914
915C11 ``_Static_assert()``
916^^^^^^^^^^^^^^^^^^^^^^^^
917
918Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
919to determine if support for compile-time assertions using ``_Static_assert`` is
920enabled.
921
Richard Smith25b555a2013-04-19 17:00:31 +0000922C11 ``_Thread_local``
923^^^^^^^^^^^^^^^^^^^^^
924
Ed Schouten401aeba2013-09-14 16:17:20 +0000925Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)``
926to determine if support for ``_Thread_local`` variables is enabled.
Richard Smith25b555a2013-04-19 17:00:31 +0000927
Sean Silva709c44d2012-12-12 23:44:55 +0000928Checks for Type Traits
929======================
930
931Clang supports the `GNU C++ type traits
932<http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
933`Microsoft Visual C++ Type traits
934<http://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_. For each
935supported type trait ``__X``, ``__has_extension(X)`` indicates the presence of
936the type trait. For example:
937
938.. code-block:: c++
939
940 #if __has_extension(is_convertible_to)
941 template<typename From, typename To>
942 struct is_convertible_to {
943 static const bool value = __is_convertible_to(From, To);
944 };
945 #else
946 // Emulate type trait
947 #endif
948
949The following type traits are supported by Clang:
950
951* ``__has_nothrow_assign`` (GNU, Microsoft)
952* ``__has_nothrow_copy`` (GNU, Microsoft)
953* ``__has_nothrow_constructor`` (GNU, Microsoft)
954* ``__has_trivial_assign`` (GNU, Microsoft)
955* ``__has_trivial_copy`` (GNU, Microsoft)
956* ``__has_trivial_constructor`` (GNU, Microsoft)
957* ``__has_trivial_destructor`` (GNU, Microsoft)
958* ``__has_virtual_destructor`` (GNU, Microsoft)
959* ``__is_abstract`` (GNU, Microsoft)
960* ``__is_base_of`` (GNU, Microsoft)
961* ``__is_class`` (GNU, Microsoft)
962* ``__is_convertible_to`` (Microsoft)
963* ``__is_empty`` (GNU, Microsoft)
964* ``__is_enum`` (GNU, Microsoft)
965* ``__is_interface_class`` (Microsoft)
966* ``__is_pod`` (GNU, Microsoft)
967* ``__is_polymorphic`` (GNU, Microsoft)
968* ``__is_union`` (GNU, Microsoft)
969* ``__is_literal(type)``: Determines whether the given type is a literal type
970* ``__is_final``: Determines whether the given type is declared with a
971 ``final`` class-virt-specifier.
972* ``__underlying_type(type)``: Retrieves the underlying type for a given
973 ``enum`` type. This trait is required to implement the C++11 standard
974 library.
975* ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value
976 of type ``totype`` can be assigned to from a value of type ``fromtype`` such
977 that no non-trivial functions are called as part of that assignment. This
978 trait is required to implement the C++11 standard library.
979* ``__is_trivially_constructible(type, argtypes...)``: Determines whether a
980 value of type ``type`` can be direct-initialized with arguments of types
981 ``argtypes...`` such that no non-trivial functions are called as part of
982 that initialization. This trait is required to implement the C++11 standard
983 library.
984
985Blocks
986======
987
988The syntax and high level language feature description is in
Michael Gottesman6fd58462013-01-07 22:24:45 +0000989:doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
990the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
Sean Silva709c44d2012-12-12 23:44:55 +0000991
992Query for this feature with ``__has_extension(blocks)``.
993
994Objective-C Features
995====================
996
997Related result types
998--------------------
999
1000According to Cocoa conventions, Objective-C methods with certain names
1001("``init``", "``alloc``", etc.) always return objects that are an instance of
1002the receiving class's type. Such methods are said to have a "related result
1003type", meaning that a message send to one of these methods will have the same
1004static type as an instance of the receiver class. For example, given the
1005following classes:
1006
1007.. code-block:: objc
1008
1009 @interface NSObject
1010 + (id)alloc;
1011 - (id)init;
1012 @end
1013
1014 @interface NSArray : NSObject
1015 @end
1016
1017and this common initialization pattern
1018
1019.. code-block:: objc
1020
1021 NSArray *array = [[NSArray alloc] init];
1022
1023the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
1024``alloc`` implicitly has a related result type. Similarly, the type of the
1025expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
1026related result type and its receiver is known to have the type ``NSArray *``.
1027If neither ``alloc`` nor ``init`` had a related result type, the expressions
1028would have had type ``id``, as declared in the method signature.
1029
1030A method with a related result type can be declared by using the type
1031``instancetype`` as its result type. ``instancetype`` is a contextual keyword
1032that is only permitted in the result type of an Objective-C method, e.g.
1033
1034.. code-block:: objc
1035
1036 @interface A
1037 + (instancetype)constructAnA;
1038 @end
1039
1040The related result type can also be inferred for some methods. To determine
1041whether a method has an inferred related result type, the first word in the
1042camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
1043and the method will have a related result type if its return type is compatible
1044with the type of its class and if:
1045
1046* the first word is "``alloc``" or "``new``", and the method is a class method,
1047 or
1048
1049* the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
1050 and the method is an instance method.
1051
1052If a method with a related result type is overridden by a subclass method, the
1053subclass method must also return a type that is compatible with the subclass
1054type. For example:
1055
1056.. code-block:: objc
1057
1058 @interface NSString : NSObject
1059 - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
1060 @end
1061
1062Related result types only affect the type of a message send or property access
1063via the given method. In all other respects, a method with a related result
1064type is treated the same way as method that returns ``id``.
1065
1066Use ``__has_feature(objc_instancetype)`` to determine whether the
1067``instancetype`` contextual keyword is available.
1068
1069Automatic reference counting
1070----------------------------
1071
Sean Silva173d2522013-01-02 13:07:47 +00001072Clang provides support for :doc:`automated reference counting
1073<AutomaticReferenceCounting>` in Objective-C, which eliminates the need
Sean Silva709c44d2012-12-12 23:44:55 +00001074for manual ``retain``/``release``/``autorelease`` message sends. There are two
1075feature macros associated with automatic reference counting:
1076``__has_feature(objc_arc)`` indicates the availability of automated reference
1077counting in general, while ``__has_feature(objc_arc_weak)`` indicates that
1078automated reference counting also includes support for ``__weak`` pointers to
1079Objective-C objects.
1080
Sean Silva173d2522013-01-02 13:07:47 +00001081.. _objc-fixed-enum:
1082
Sean Silva709c44d2012-12-12 23:44:55 +00001083Enumerations with a fixed underlying type
1084-----------------------------------------
1085
1086Clang provides support for C++11 enumerations with a fixed underlying type
1087within Objective-C. For example, one can write an enumeration type as:
1088
1089.. code-block:: c++
1090
1091 typedef enum : unsigned char { Red, Green, Blue } Color;
1092
1093This specifies that the underlying type, which is used to store the enumeration
1094value, is ``unsigned char``.
1095
1096Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
1097underlying types is available in Objective-C.
1098
1099Interoperability with C++11 lambdas
1100-----------------------------------
1101
1102Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
1103permitting a lambda to be implicitly converted to a block pointer with the
1104corresponding signature. For example, consider an API such as ``NSArray``'s
1105array-sorting method:
1106
1107.. code-block:: objc
1108
1109 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
1110
1111``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
1112(^)(id, id)``, and parameters of this type are generally provided with block
1113literals as arguments. However, one can also use a C++11 lambda so long as it
1114provides the same signature (in this case, accepting two parameters of type
1115``id`` and returning an ``NSComparisonResult``):
1116
1117.. code-block:: objc
1118
1119 NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
1120 @"String 02"];
1121 const NSStringCompareOptions comparisonOptions
1122 = NSCaseInsensitiveSearch | NSNumericSearch |
1123 NSWidthInsensitiveSearch | NSForcedOrderingSearch;
1124 NSLocale *currentLocale = [NSLocale currentLocale];
1125 NSArray *sorted
1126 = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
1127 NSRange string1Range = NSMakeRange(0, [s1 length]);
1128 return [s1 compare:s2 options:comparisonOptions
1129 range:string1Range locale:currentLocale];
1130 }];
1131 NSLog(@"sorted: %@", sorted);
1132
1133This code relies on an implicit conversion from the type of the lambda
1134expression (an unnamed, local class type called the *closure type*) to the
1135corresponding block pointer type. The conversion itself is expressed by a
1136conversion operator in that closure type that produces a block pointer with the
1137same signature as the lambda itself, e.g.,
1138
1139.. code-block:: objc
1140
1141 operator NSComparisonResult (^)(id, id)() const;
1142
1143This conversion function returns a new block that simply forwards the two
1144parameters to the lambda object (which it captures by copy), then returns the
1145result. The returned block is first copied (with ``Block_copy``) and then
1146autoreleased. As an optimization, if a lambda expression is immediately
1147converted to a block pointer (as in the first example, above), then the block
1148is not copied and autoreleased: rather, it is given the same lifetime as a
1149block literal written at that point in the program, which avoids the overhead
1150of copying a block to the heap in the common case.
1151
1152The conversion from a lambda to a block pointer is only available in
1153Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
1154management (autorelease).
1155
1156Object Literals and Subscripting
1157--------------------------------
1158
Sean Silva173d2522013-01-02 13:07:47 +00001159Clang provides support for :doc:`Object Literals and Subscripting
1160<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
Sean Silva709c44d2012-12-12 23:44:55 +00001161programming patterns, makes programs more concise, and improves the safety of
1162container creation. There are several feature macros associated with object
1163literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
1164availability of array literals; ``__has_feature(objc_dictionary_literals)``
1165tests the availability of dictionary literals;
1166``__has_feature(objc_subscripting)`` tests the availability of object
1167subscripting.
1168
1169Objective-C Autosynthesis of Properties
1170---------------------------------------
1171
1172Clang provides support for autosynthesis of declared properties. Using this
1173feature, clang provides default synthesis of those properties not declared
1174@dynamic and not having user provided backing getter and setter methods.
1175``__has_feature(objc_default_synthesize_properties)`` checks for availability
1176of this feature in version of clang being used.
1177
Jordan Rose32e94892012-12-15 00:37:01 +00001178.. _langext-objc_method_family:
1179
Ted Kremenekc3481f42013-10-23 22:14:59 +00001180
Ted Kremenek7f7a4832013-10-23 22:41:52 +00001181Objective-C requiring a call to ``super`` in an override
1182--------------------------------------------------------
Ted Kremenekf2ee81d2013-10-23 22:15:01 +00001183
Ted Kremenek7f7a4832013-10-23 22:41:52 +00001184Some Objective-C classes allow a subclass to override a particular method in a
Warren Hunte0bc9802013-10-24 00:59:24 +00001185parent class but expect that the overriding method also calls the overridden
1186method in the parent class. For these cases, we provide an attribute to
1187designate that a method requires a "call to ``super``" in the overriding
1188method in the subclass.
Ted Kremenekf2ee81d2013-10-23 22:15:01 +00001189
Warren Hunte0bc9802013-10-24 00:59:24 +00001190**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
1191be placed at the end of a method declaration:
Ted Kremenekf2ee81d2013-10-23 22:15:01 +00001192
1193.. code-block:: objc
1194
1195 - (void)foo __attribute__((objc_requires_super));
1196
Warren Hunte0bc9802013-10-24 00:59:24 +00001197This attribute can only be applied the method declarations within a class, and
1198not a protocol. Currently this attribute does not enforce any placement of
1199where the call occurs in the overriding method (such as in the case of
1200``-dealloc`` where the call must appear at the end). It checks only that it
1201exists.
Ted Kremenekf2ee81d2013-10-23 22:15:01 +00001202
1203Note that on both OS X and iOS that the Foundation framework provides a
Ted Kremenek620cde32013-10-23 22:25:59 +00001204convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
Ted Kremenekf2ee81d2013-10-23 22:15:01 +00001205attribute:
1206
1207.. code-block:: objc
1208
1209 - (void)foo NS_REQUIRES_SUPER;
1210
1211This macro is conditionally defined depending on the compiler's support for
1212this attribute. If the compiler does not support the attribute the macro
1213expands to nothing.
1214
1215Operationally, when a method has this annotation the compiler will warn if the
1216implementation of an override in a subclass does not call super. For example:
1217
1218.. code-block:: objc
1219
1220 warning: method possibly missing a [super AnnotMeth] call
1221 - (void) AnnotMeth{};
1222 ^
1223
Ted Kremenekc3481f42013-10-23 22:14:59 +00001224Objective-C Method Families
1225---------------------------
Jordan Rose32e94892012-12-15 00:37:01 +00001226
1227Many methods in Objective-C have conventional meanings determined by their
1228selectors. It is sometimes useful to be able to mark a method as having a
1229particular conventional meaning despite not having the right selector, or as
1230not having the conventional meaning that its selector would suggest. For these
1231use cases, we provide an attribute to specifically describe the "method family"
1232that a method belongs to.
1233
1234**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
1235``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
1236attribute can only be placed at the end of a method declaration:
1237
1238.. code-block:: objc
1239
1240 - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
1241
1242Users who do not wish to change the conventional meaning of a method, and who
1243merely want to document its non-standard retain and release semantics, should
1244use the :ref:`retaining behavior attributes <langext-objc-retain-release>`
1245described below.
1246
1247Query for this feature with ``__has_attribute(objc_method_family)``.
1248
1249.. _langext-objc-retain-release:
1250
1251Objective-C retaining behavior attributes
1252-----------------------------------------
1253
1254In Objective-C, functions and methods are generally assumed to follow the
1255`Cocoa Memory Management
1256<http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
1257conventions for ownership of object arguments and
1258return values. However, there are exceptions, and so Clang provides attributes
1259to allow these exceptions to be documented. This are used by ARC and the
1260`static analyzer <http://clang-analyzer.llvm.org>`_ Some exceptions may be
1261better described using the :ref:`objc_method_family
1262<langext-objc_method_family>` attribute instead.
1263
1264**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
1265``ns_returns_autoreleased``, ``cf_returns_retained``, and
1266``cf_returns_not_retained`` attributes can be placed on methods and functions
1267that return Objective-C or CoreFoundation objects. They are commonly placed at
1268the end of a function prototype or method declaration:
1269
1270.. code-block:: objc
1271
1272 id foo() __attribute__((ns_returns_retained));
1273
1274 - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
1275
1276The ``*_returns_retained`` attributes specify that the returned object has a +1
1277retain count. The ``*_returns_not_retained`` attributes specify that the return
1278object has a +0 retain count, even if the normal convention for its selector
1279would be +1. ``ns_returns_autoreleased`` specifies that the returned object is
1280+0, but is guaranteed to live at least as long as the next flush of an
1281autorelease pool.
1282
1283**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
1284an parameter declaration; they specify that the argument is expected to have a
1285+1 retain count, which will be balanced in some way by the function or method.
1286The ``ns_consumes_self`` attribute can only be placed on an Objective-C
1287method; it specifies that the method expects its ``self`` parameter to have a
1288+1 retain count, which it will balance in some way.
1289
1290.. code-block:: objc
1291
1292 void foo(__attribute__((ns_consumed)) NSString *string);
1293
1294 - (void) bar __attribute__((ns_consumes_self));
1295 - (void) baz:(id) __attribute__((ns_consumed)) x;
1296
1297Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
1298<http://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
1299
1300Query for these features with ``__has_attribute(ns_consumed)``,
1301``__has_attribute(ns_returns_retained)``, etc.
1302
1303
Ted Kremenek84342d62013-10-15 04:28:42 +00001304Objective-C++ ABI: protocol-qualifier mangling of parameters
1305------------------------------------------------------------
1306
1307Starting with LLVM 3.4, Clang produces a new mangling for parameters whose
1308type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such
1309parameters to be differentiated from those with the regular unqualified ``id``
1310type.
1311
1312This was a non-backward compatible mangling change to the ABI. This change
1313allows proper overloading, and also prevents mangling conflicts with template
1314parameters of protocol-qualified type.
1315
1316Query the presence of this new mangling with
1317``__has_feature(objc_protocol_qualifier_mangling)``.
1318
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001319.. _langext-overloading:
1320
Sean Silva709c44d2012-12-12 23:44:55 +00001321Function Overloading in C
1322=========================
1323
1324Clang provides support for C++ function overloading in C. Function overloading
1325in C is introduced using the ``overloadable`` attribute. For example, one
1326might provide several overloaded versions of a ``tgsin`` function that invokes
1327the appropriate standard function computing the sine of a value with ``float``,
1328``double``, or ``long double`` precision:
1329
1330.. code-block:: c
1331
1332 #include <math.h>
1333 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
1334 double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
1335 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
1336
1337Given these declarations, one can call ``tgsin`` with a ``float`` value to
1338receive a ``float`` result, with a ``double`` to receive a ``double`` result,
1339etc. Function overloading in C follows the rules of C++ function overloading
1340to pick the best overload given the call arguments, with a few C-specific
1341semantics:
1342
1343* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
1344 floating-point promotion (per C99) rather than as a floating-point conversion
1345 (as in C++).
1346
1347* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
1348 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
1349 compatible types.
1350
1351* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
1352 and ``U`` are compatible types. This conversion is given "conversion" rank.
1353
1354The declaration of ``overloadable`` functions is restricted to function
1355declarations and definitions. Most importantly, if any function with a given
1356name is given the ``overloadable`` attribute, then all function declarations
1357and definitions with that name (and in that scope) must have the
1358``overloadable`` attribute. This rule even applies to redeclarations of
1359functions whose original declaration had the ``overloadable`` attribute, e.g.,
1360
1361.. code-block:: c
1362
1363 int f(int) __attribute__((overloadable));
1364 float f(float); // error: declaration of "f" must have the "overloadable" attribute
1365
1366 int g(int) __attribute__((overloadable));
1367 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
1368
1369Functions marked ``overloadable`` must have prototypes. Therefore, the
1370following code is ill-formed:
1371
1372.. code-block:: c
1373
1374 int h() __attribute__((overloadable)); // error: h does not have a prototype
1375
1376However, ``overloadable`` functions are allowed to use a ellipsis even if there
1377are no named parameters (as is permitted in C++). This feature is particularly
1378useful when combined with the ``unavailable`` attribute:
1379
1380.. code-block:: c++
1381
1382 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
1383
1384Functions declared with the ``overloadable`` attribute have their names mangled
1385according to the same rules as C++ function names. For example, the three
1386``tgsin`` functions in our motivating example get the mangled names
1387``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
1388caveats to this use of name mangling:
1389
1390* Future versions of Clang may change the name mangling of functions overloaded
1391 in C, so you should not depend on an specific mangling. To be completely
1392 safe, we strongly urge the use of ``static inline`` with ``overloadable``
1393 functions.
1394
1395* The ``overloadable`` attribute has almost no meaning when used in C++,
1396 because names will already be mangled and functions are already overloadable.
1397 However, when an ``overloadable`` function occurs within an ``extern "C"``
1398 linkage specification, it's name *will* be mangled in the same way as it
1399 would in C.
1400
1401Query for this feature with ``__has_extension(attribute_overloadable)``.
1402
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001403Controlling Overload Resolution
1404===============================
1405
1406Clang introduces the ``enable_if`` attribute, which can be placed on function
1407declarations to control which overload is selected based on the values of the
1408function's arguments. When combined with the
1409:ref:``overloadable<langext-overloading>`` attribute, this feature is also
1410available in C.
1411
1412.. code-block:: c++
1413
1414 int isdigit(int c);
1415 int isdigit(int c) __attribute__((enable_if(c >= -1 && c <= 255, "'c' must have the value of an unsigned char or EOF")));
1416
1417 void foo(char c) {
1418 isdigit(c);
1419 isdigit(10);
1420 isdigit(-10); // results in a compile-time error.
1421 }
1422
1423The enable_if attribute takes two arguments, the first is an expression written
1424in terms of the function parameters, the second is a string explaining why this
1425overload candidate could not be selected to be displayed in diagnostics. The
1426expression is part of the function signature for the purposes of determining
1427whether it is a redeclaration (following the rules used when determining
1428whether a C++ template specialization is ODR-equivalent), but is not part of
1429the type.
1430
1431An enable_if expression will be evaluated by substituting the values of the
1432parameters from the call site into the arguments in the expression and
1433determining whether the result is true. If the result is false or could not be
1434determined through constant expression evaluation, then this overload will not
1435be chosen and the reason supplied in the string will be given to the user if
1436their code does not compile as a result.
1437
1438Because the enable_if expression is an unevaluated context, there are no global
1439state changes, nor the ability to pass information from the enable_if
1440expression to the function body. For example, suppose we want calls to
1441strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
1442strbuf) only if the size of strbuf can be determined:
1443
1444.. code-block:: c++
1445
1446 __attribute__((always_inline))
1447 static inline size_t strnlen(const char *s, size_t maxlen)
1448 __attribute__((overloadable))
1449 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
1450 "chosen when the buffer size is known but 'maxlen' is not")))
1451 {
1452 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
1453 }
1454
1455Multiple enable_if attributes may be applied to a single declaration. In this
1456case, the enable_if expressions are evaluated from left to right in the
1457following manner. First, the candidates whose enable_if expressions evaluate to
1458false or cannot be evaluated are discarded. If the remaining candidates do not
1459share ODR-equivalent enable_if expressions, the overload resolution is
1460ambiguous. Otherwise, enable_if overload resolution continues with the next
1461enable_if attribute on the candidates that have not been discarded and have
1462remaining enable_if attributes. In this way, we pick the most specific
1463overload out of a number of viable overloads using enable_if.
1464
1465.. code-block:: c++
1466 void f() __attribute__((enable_if(true, ""))); // #1
1467 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
1468
1469 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
1470 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
1471
1472In this example, a call to f() is always resolved to #2, as the first enable_if
1473expression is ODR-equivalent for both declarations, but #1 does not have another
1474enable_if expression to continue evaluating, so the next round of evaluation has
1475only a single candidate. In a call to g(1, 1), the call is ambiguous even though
1476#2 has more enable_if attributes, because the first enable_if expressions are
1477not ODR-equivalent.
1478
1479Query for this feature with ``__has_attribute(enable_if)``.
1480
Sean Silva709c44d2012-12-12 23:44:55 +00001481Initializer lists for complex numbers in C
1482==========================================
1483
1484clang supports an extension which allows the following in C:
1485
1486.. code-block:: c++
1487
1488 #include <math.h>
1489 #include <complex.h>
1490 complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
1491
1492This construct is useful because there is no way to separately initialize the
1493real and imaginary parts of a complex variable in standard C, given that clang
1494does not support ``_Imaginary``. (Clang also supports the ``__real__`` and
1495``__imag__`` extensions from gcc, which help in some cases, but are not usable
1496in static initializers.)
1497
1498Note that this extension does not allow eliding the braces; the meaning of the
1499following two lines is different:
1500
1501.. code-block:: c++
1502
1503 complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
1504 complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
1505
1506This extension also works in C++ mode, as far as that goes, but does not apply
1507to the C++ ``std::complex``. (In C++11, list initialization allows the same
1508syntax to be used with ``std::complex`` with the same meaning.)
1509
1510Builtin Functions
1511=================
1512
1513Clang supports a number of builtin library functions with the same syntax as
1514GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
1515``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
1516``__sync_fetch_and_add``, etc. In addition to the GCC builtins, Clang supports
1517a number of builtins that GCC does not, which are listed here.
1518
1519Please note that Clang does not and will not support all of the GCC builtins
1520for vector operations. Instead of using builtins, you should use the functions
1521defined in target-specific header files like ``<xmmintrin.h>``, which define
1522portable wrappers for these. Many of the Clang versions of these functions are
1523implemented directly in terms of :ref:`extended vector support
1524<langext-vectors>` instead of builtins, in order to reduce the number of
1525builtins that we need to implement.
1526
1527``__builtin_readcyclecounter``
1528------------------------------
1529
1530``__builtin_readcyclecounter`` is used to access the cycle counter register (or
1531a similar low-latency, high-accuracy clock) on those targets that support it.
1532
1533**Syntax**:
1534
1535.. code-block:: c++
1536
1537 __builtin_readcyclecounter()
1538
1539**Example of Use**:
1540
1541.. code-block:: c++
1542
1543 unsigned long long t0 = __builtin_readcyclecounter();
1544 do_something();
1545 unsigned long long t1 = __builtin_readcyclecounter();
1546 unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
1547
1548**Description**:
1549
1550The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
1551which may be either global or process/thread-specific depending on the target.
1552As the backing counters often overflow quickly (on the order of seconds) this
1553should only be used for timing small intervals. When not supported by the
1554target, the return value is always zero. This builtin takes no arguments and
1555produces an unsigned long long result.
1556
Tim Northoverbfe2e5f72013-05-23 19:14:12 +00001557Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
1558that even if present, its use may depend on run-time privilege or other OS
1559controlled state.
Sean Silva709c44d2012-12-12 23:44:55 +00001560
1561.. _langext-__builtin_shufflevector:
1562
1563``__builtin_shufflevector``
1564---------------------------
1565
1566``__builtin_shufflevector`` is used to express generic vector
1567permutation/shuffle/swizzle operations. This builtin is also very important
1568for the implementation of various target-specific header files like
1569``<xmmintrin.h>``.
1570
1571**Syntax**:
1572
1573.. code-block:: c++
1574
1575 __builtin_shufflevector(vec1, vec2, index1, index2, ...)
1576
1577**Examples**:
1578
1579.. code-block:: c++
1580
Craig Topper50ad5b72013-08-03 17:40:38 +00001581 // identity operation - return 4-element vector v1.
1582 __builtin_shufflevector(v1, v1, 0, 1, 2, 3)
Sean Silva709c44d2012-12-12 23:44:55 +00001583
1584 // "Splat" element 0 of V1 into a 4-element result.
1585 __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
1586
1587 // Reverse 4-element vector V1.
1588 __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
1589
1590 // Concatenate every other element of 4-element vectors V1 and V2.
1591 __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
1592
1593 // Concatenate every other element of 8-element vectors V1 and V2.
1594 __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
1595
Craig Topper50ad5b72013-08-03 17:40:38 +00001596 // Shuffle v1 with some elements being undefined
1597 __builtin_shufflevector(v1, v1, 3, -1, 1, -1)
1598
Sean Silva709c44d2012-12-12 23:44:55 +00001599**Description**:
1600
1601The first two arguments to ``__builtin_shufflevector`` are vectors that have
1602the same element type. The remaining arguments are a list of integers that
1603specify the elements indices of the first two vectors that should be extracted
1604and returned in a new vector. These element indices are numbered sequentially
1605starting with the first vector, continuing into the second vector. Thus, if
1606``vec1`` is a 4-element vector, index 5 would refer to the second element of
Craig Topper50ad5b72013-08-03 17:40:38 +00001607``vec2``. An index of -1 can be used to indicate that the corresponding element
1608in the returned vector is a don't care and can be optimized by the backend.
Sean Silva709c44d2012-12-12 23:44:55 +00001609
1610The result of ``__builtin_shufflevector`` is a vector with the same element
1611type as ``vec1``/``vec2`` but that has an element count equal to the number of
1612indices specified.
1613
1614Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
1615
Hal Finkelc4d7c822013-09-18 03:29:45 +00001616``__builtin_convertvector``
1617---------------------------
1618
1619``__builtin_convertvector`` is used to express generic vector
1620type-conversion operations. The input vector and the output vector
1621type must have the same number of elements.
1622
1623**Syntax**:
1624
1625.. code-block:: c++
1626
1627 __builtin_convertvector(src_vec, dst_vec_type)
1628
1629**Examples**:
1630
1631.. code-block:: c++
1632
1633 typedef double vector4double __attribute__((__vector_size__(32)));
1634 typedef float vector4float __attribute__((__vector_size__(16)));
1635 typedef short vector4short __attribute__((__vector_size__(8)));
1636 vector4float vf; vector4short vs;
1637
1638 // convert from a vector of 4 floats to a vector of 4 doubles.
1639 __builtin_convertvector(vf, vector4double)
1640 // equivalent to:
1641 (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }
1642
1643 // convert from a vector of 4 shorts to a vector of 4 floats.
1644 __builtin_convertvector(vs, vector4float)
1645 // equivalent to:
1646 (vector4float) { (float) vf[0], (float) vf[1], (float) vf[2], (float) vf[3] }
1647
1648**Description**:
1649
1650The first argument to ``__builtin_convertvector`` is a vector, and the second
1651argument is a vector type with the same number of elements as the first
1652argument.
1653
1654The result of ``__builtin_convertvector`` is a vector with the same element
1655type as the second argument, with a value defined in terms of the action of a
1656C-style cast applied to each element of the first argument.
1657
1658Query for this feature with ``__has_builtin(__builtin_convertvector)``.
1659
Sean Silva709c44d2012-12-12 23:44:55 +00001660``__builtin_unreachable``
1661-------------------------
1662
1663``__builtin_unreachable`` is used to indicate that a specific point in the
1664program cannot be reached, even if the compiler might otherwise think it can.
1665This is useful to improve optimization and eliminates certain warnings. For
1666example, without the ``__builtin_unreachable`` in the example below, the
1667compiler assumes that the inline asm can fall through and prints a "function
1668declared '``noreturn``' should not return" warning.
1669
1670**Syntax**:
1671
1672.. code-block:: c++
1673
1674 __builtin_unreachable()
1675
1676**Example of use**:
1677
1678.. code-block:: c++
1679
1680 void myabort(void) __attribute__((noreturn));
1681 void myabort(void) {
1682 asm("int3");
1683 __builtin_unreachable();
1684 }
1685
1686**Description**:
1687
1688The ``__builtin_unreachable()`` builtin has completely undefined behavior.
1689Since it has undefined behavior, it is a statement that it is never reached and
1690the optimizer can take advantage of this to produce better code. This builtin
1691takes no arguments and produces a void result.
1692
1693Query for this feature with ``__has_builtin(__builtin_unreachable)``.
1694
1695``__sync_swap``
1696---------------
1697
1698``__sync_swap`` is used to atomically swap integers or pointers in memory.
1699
1700**Syntax**:
1701
1702.. code-block:: c++
1703
1704 type __sync_swap(type *ptr, type value, ...)
1705
1706**Example of Use**:
1707
1708.. code-block:: c++
1709
1710 int old_value = __sync_swap(&value, new_value);
1711
1712**Description**:
1713
1714The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
1715atomic intrinsics to allow code to atomically swap the current value with the
1716new value. More importantly, it helps developers write more efficient and
1717correct code by avoiding expensive loops around
1718``__sync_bool_compare_and_swap()`` or relying on the platform specific
1719implementation details of ``__sync_lock_test_and_set()``. The
1720``__sync_swap()`` builtin is a full barrier.
1721
Richard Smith6cbd65d2013-07-11 02:27:57 +00001722``__builtin_addressof``
1723-----------------------
1724
1725``__builtin_addressof`` performs the functionality of the built-in ``&``
1726operator, ignoring any ``operator&`` overload. This is useful in constant
1727expressions in C++11, where there is no other way to take the address of an
1728object that overloads ``operator&``.
1729
1730**Example of use**:
1731
1732.. code-block:: c++
1733
1734 template<typename T> constexpr T *addressof(T &value) {
1735 return __builtin_addressof(value);
1736 }
1737
Michael Gottesmanc5cc9f12013-01-13 04:35:31 +00001738Multiprecision Arithmetic Builtins
1739----------------------------------
1740
1741Clang provides a set of builtins which expose multiprecision arithmetic in a
1742manner amenable to C. They all have the following form:
1743
1744.. code-block:: c
1745
1746 unsigned x = ..., y = ..., carryin = ..., carryout;
1747 unsigned sum = __builtin_addc(x, y, carryin, &carryout);
1748
1749Thus one can form a multiprecision addition chain in the following manner:
1750
1751.. code-block:: c
1752
1753 unsigned *x, *y, *z, carryin=0, carryout;
1754 z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
1755 carryin = carryout;
1756 z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
1757 carryin = carryout;
1758 z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
1759 carryin = carryout;
1760 z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
1761
1762The complete list of builtins are:
1763
1764.. code-block:: c
1765
Michael Gottesman15343992013-06-18 20:40:40 +00001766 unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
Michael Gottesmanc5cc9f12013-01-13 04:35:31 +00001767 unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
1768 unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
1769 unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
1770 unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
Michael Gottesman15343992013-06-18 20:40:40 +00001771 unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
Michael Gottesmanc5cc9f12013-01-13 04:35:31 +00001772 unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
1773 unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
1774 unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
1775 unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
1776
Michael Gottesman930ecdb2013-06-20 23:28:10 +00001777Checked Arithmetic Builtins
1778---------------------------
1779
1780Clang provides a set of builtins that implement checked arithmetic for security
1781critical applications in a manner that is fast and easily expressable in C. As
1782an example of their usage:
1783
1784.. code-block:: c
1785
1786 errorcode_t security_critical_application(...) {
1787 unsigned x, y, result;
1788 ...
1789 if (__builtin_umul_overflow(x, y, &result))
1790 return kErrorCodeHackers;
1791 ...
1792 use_multiply(result);
1793 ...
1794 }
1795
1796A complete enumeration of the builtins are:
1797
1798.. code-block:: c
1799
1800 bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum);
1801 bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);
1802 bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);
1803 bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff);
1804 bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);
1805 bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);
1806 bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod);
1807 bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);
1808 bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);
1809 bool __builtin_sadd_overflow (int x, int y, int *sum);
1810 bool __builtin_saddl_overflow (long x, long y, long *sum);
1811 bool __builtin_saddll_overflow(long long x, long long y, long long *sum);
1812 bool __builtin_ssub_overflow (int x, int y, int *diff);
1813 bool __builtin_ssubl_overflow (long x, long y, long *diff);
1814 bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);
1815 bool __builtin_smul_overflow (int x, int y, int *prod);
1816 bool __builtin_smull_overflow (long x, long y, long *prod);
1817 bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
1818
1819
Sean Silva709c44d2012-12-12 23:44:55 +00001820.. _langext-__c11_atomic:
1821
1822__c11_atomic builtins
1823---------------------
1824
1825Clang provides a set of builtins which are intended to be used to implement
1826C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the
1827``_explicit`` form of the corresponding C11 operation, and are named with a
1828``__c11_`` prefix. The supported operations are:
1829
1830* ``__c11_atomic_init``
1831* ``__c11_atomic_thread_fence``
1832* ``__c11_atomic_signal_fence``
1833* ``__c11_atomic_is_lock_free``
1834* ``__c11_atomic_store``
1835* ``__c11_atomic_load``
1836* ``__c11_atomic_exchange``
1837* ``__c11_atomic_compare_exchange_strong``
1838* ``__c11_atomic_compare_exchange_weak``
1839* ``__c11_atomic_fetch_add``
1840* ``__c11_atomic_fetch_sub``
1841* ``__c11_atomic_fetch_and``
1842* ``__c11_atomic_fetch_or``
1843* ``__c11_atomic_fetch_xor``
1844
Tim Northover6aacd492013-07-16 09:47:53 +00001845Low-level ARM exclusive memory builtins
1846---------------------------------------
1847
1848Clang provides overloaded builtins giving direct access to the three key ARM
1849instructions for implementing atomic operations.
1850
1851.. code-block:: c
Sean Silvaa928c242013-09-09 19:50:40 +00001852
Tim Northover6aacd492013-07-16 09:47:53 +00001853 T __builtin_arm_ldrex(const volatile T *addr);
1854 int __builtin_arm_strex(T val, volatile T *addr);
1855 void __builtin_arm_clrex(void);
1856
1857The types ``T`` currently supported are:
1858* Integer types with width at most 64 bits.
1859* Floating-point types
1860* Pointer types.
1861
1862Note that the compiler does not guarantee it will not insert stores which clear
1863the exclusive monitor in between an ``ldrex`` and its paired ``strex``. In
1864practice this is only usually a risk when the extra store is on the same cache
1865line as the variable being modified and Clang will only insert stack stores on
1866its own, so it is best not to use these operations on variables with automatic
1867storage duration.
1868
1869Also, loads and stores may be implicit in code written between the ``ldrex`` and
1870``strex``. Clang will not necessarily mitigate the effects of these either, so
1871care should be exercised.
1872
1873For these reasons the higher level atomic primitives should be preferred where
1874possible.
1875
Sean Silva709c44d2012-12-12 23:44:55 +00001876Non-standard C++11 Attributes
1877=============================
1878
Richard Smithf6d2d3b2013-02-14 00:13:34 +00001879Clang's non-standard C++11 attributes live in the ``clang`` attribute
1880namespace.
Sean Silva709c44d2012-12-12 23:44:55 +00001881
1882The ``clang::fallthrough`` attribute
1883------------------------------------
1884
1885The ``clang::fallthrough`` attribute is used along with the
1886``-Wimplicit-fallthrough`` argument to annotate intentional fall-through
1887between switch labels. It can only be applied to a null statement placed at a
1888point of execution between any statement and the next switch label. It is
1889common to mark these places with a specific comment, but this attribute is
1890meant to replace comments with a more strict annotation, which can be checked
1891by the compiler. This attribute doesn't change semantics of the code and can
1892be used wherever an intended fall-through occurs. It is designed to mimic
1893control-flow statements like ``break;``, so it can be placed in most places
1894where ``break;`` can, but only if there are no statements on the execution path
1895between it and the next switch label.
1896
1897Here is an example:
1898
1899.. code-block:: c++
1900
1901 // compile with -Wimplicit-fallthrough
1902 switch (n) {
1903 case 22:
1904 case 33: // no warning: no statements between case labels
1905 f();
1906 case 44: // warning: unannotated fall-through
1907 g();
1908 [[clang::fallthrough]];
1909 case 55: // no warning
1910 if (x) {
1911 h();
1912 break;
1913 }
1914 else {
1915 i();
1916 [[clang::fallthrough]];
1917 }
1918 case 66: // no warning
1919 p();
1920 [[clang::fallthrough]]; // warning: fallthrough annotation does not
1921 // directly precede case label
1922 q();
1923 case 77: // warning: unannotated fall-through
1924 r();
1925 }
1926
Richard Smithf6d2d3b2013-02-14 00:13:34 +00001927``gnu::`` attributes
1928--------------------
1929
1930Clang also supports GCC's ``gnu`` attribute namespace. All GCC attributes which
1931are accepted with the ``__attribute__((foo))`` syntax are also accepted as
1932``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
1933(see the list of `GCC function attributes
1934<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
1935attributes <http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
1936`GCC type attributes
Richard Smithccfc9ff2013-07-11 00:27:05 +00001937<http://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
Richard Smithf6d2d3b2013-02-14 00:13:34 +00001938implementation, these attributes must appertain to the *declarator-id* in a
1939declaration, which means they must go either at the start of the declaration or
1940immediately after the name being declared.
1941
1942For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
1943also applies the GNU ``noreturn`` attribute to ``f``.
1944
1945.. code-block:: c++
1946
1947 [[gnu::unused]] int a, f [[gnu::noreturn]] ();
1948
Sean Silva709c44d2012-12-12 23:44:55 +00001949Target-Specific Extensions
1950==========================
1951
1952Clang supports some language features conditionally on some targets.
1953
1954X86/X86-64 Language Extensions
1955------------------------------
1956
1957The X86 backend has these language extensions:
1958
1959Memory references off the GS segment
1960^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1961
1962Annotating a pointer with address space #256 causes it to be code generated
1963relative to the X86 GS segment register, and address space #257 causes it to be
1964relative to the X86 FS segment. Note that this is a very very low-level
1965feature that should only be used if you know what you're doing (for example in
1966an OS kernel).
1967
1968Here is an example:
1969
1970.. code-block:: c++
1971
1972 #define GS_RELATIVE __attribute__((address_space(256)))
1973 int foo(int GS_RELATIVE *P) {
1974 return *P;
1975 }
1976
1977Which compiles to (on X86-32):
1978
1979.. code-block:: gas
1980
1981 _foo:
1982 movl 4(%esp), %eax
1983 movl %gs:(%eax), %eax
1984 ret
1985
Tim Northovera484bc02013-10-01 14:34:25 +00001986ARM Language Extensions
1987-----------------------
1988
1989Interrupt attribute
1990^^^^^^^^^^^^^^^^^^^
1991
Alp Toker3b557ba2013-12-03 06:53:39 +00001992Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
1993ARM targets. This attribute may be attached to a function definition and
Tim Northovera484bc02013-10-01 14:34:25 +00001994instructs the backend to generate appropriate function entry/exit code so that
1995it can be used directly as an interrupt service routine.
1996
1997 The parameter passed to the interrupt attribute is optional, but if
1998provided it must be a string literal with one of the following values: "IRQ",
1999"FIQ", "SWI", "ABORT", "UNDEF".
2000
2001The semantics are as follows:
2002
2003- If the function is AAPCS, Clang instructs the backend to realign the stack to
2004 8 bytes on entry. This is a general requirement of the AAPCS at public
2005 interfaces, but may not hold when an exception is taken. Doing this allows
2006 other AAPCS functions to be called.
2007- If the CPU is M-class this is all that needs to be done since the architecture
2008 itself is designed in such a way that functions obeying the normal AAPCS ABI
2009 constraints are valid exception handlers.
2010- If the CPU is not M-class, the prologue and epilogue are modified to save all
2011 non-banked registers that are used, so that upon return the user-mode state
2012 will not be corrupted. Note that to avoid unnecessary overhead, only
2013 general-purpose (integer) registers are saved in this way. If VFP operations
2014 are needed, that state must be saved manually.
2015
2016 Specifically, interrupt kinds other than "FIQ" will save all core registers
2017 except "lr" and "sp". "FIQ" interrupts will save r0-r7.
2018- If the CPU is not M-class, the return instruction is changed to one of the
2019 canonical sequences permitted by the architecture for exception return. Where
2020 possible the function itself will make the necessary "lr" adjustments so that
2021 the "preferred return address" is selected.
2022
Tim Northovera77b7b82013-10-01 14:39:43 +00002023 Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
Tim Northovera484bc02013-10-01 14:34:25 +00002024 handler, where the offset from "lr" to the preferred return address depends on
2025 the execution state of the code which generated the exception. In this case
2026 a sequence equivalent to "movs pc, lr" will be used.
2027
Jordan Rose32e94892012-12-15 00:37:01 +00002028Extensions for Static Analysis
Dmitri Gribenkoace09a22012-12-15 14:25:25 +00002029==============================
Sean Silva709c44d2012-12-12 23:44:55 +00002030
2031Clang supports additional attributes that are useful for documenting program
Jordan Rose32e94892012-12-15 00:37:01 +00002032invariants and rules for static analysis tools, such as the `Clang Static
2033Analyzer <http://clang-analyzer.llvm.org/>`_. These attributes are documented
2034in the analyzer's `list of source-level annotations
2035<http://clang-analyzer.llvm.org/annotations.html>`_.
Sean Silva709c44d2012-12-12 23:44:55 +00002036
Sean Silva709c44d2012-12-12 23:44:55 +00002037
Jordan Rose32e94892012-12-15 00:37:01 +00002038Extensions for Dynamic Analysis
Dmitri Gribenkoace09a22012-12-15 14:25:25 +00002039===============================
Sean Silva709c44d2012-12-12 23:44:55 +00002040
2041.. _langext-address_sanitizer:
2042
2043AddressSanitizer
2044----------------
2045
2046Use ``__has_feature(address_sanitizer)`` to check if the code is being built
Dmitri Gribenkoace09a22012-12-15 14:25:25 +00002047with :doc:`AddressSanitizer`.
Sean Silva709c44d2012-12-12 23:44:55 +00002048
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00002049Use ``__attribute__((no_sanitize_address))``
2050on a function declaration
Sean Silva709c44d2012-12-12 23:44:55 +00002051to specify that address safety instrumentation (e.g. AddressSanitizer) should
2052not be applied to that function.
2053
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00002054.. _langext-thread_sanitizer:
2055
2056ThreadSanitizer
2057----------------
2058
2059Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
2060with :doc:`ThreadSanitizer`.
2061
2062Use ``__attribute__((no_sanitize_thread))`` on a function declaration
2063to specify that checks for data races on plain (non-atomic) memory accesses
2064should not be inserted by ThreadSanitizer.
Dmitry Vyukovae4ea1d2013-10-17 08:06:19 +00002065The function is still instrumented by the tool to avoid false positives and
2066provide meaningful stack traces.
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00002067
2068.. _langext-memory_sanitizer:
2069
2070MemorySanitizer
2071----------------
2072Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
2073with :doc:`MemorySanitizer`.
2074
2075Use ``__attribute__((no_sanitize_memory))`` on a function declaration
2076to specify that checks for uninitialized memory should not be inserted
2077(e.g. by MemorySanitizer). The function may still be instrumented by the tool
2078to avoid false positives in other places.
2079
2080
Sean Silva709c44d2012-12-12 23:44:55 +00002081Thread-Safety Annotation Checking
2082=================================
2083
2084Clang supports additional attributes for checking basic locking policies in
2085multithreaded programs. Clang currently parses the following list of
2086attributes, although **the implementation for these annotations is currently in
2087development.** For more details, see the `GCC implementation
2088<http://gcc.gnu.org/wiki/ThreadSafetyAnnotation>`_.
2089
2090``no_thread_safety_analysis``
2091-----------------------------
2092
2093Use ``__attribute__((no_thread_safety_analysis))`` on a function declaration to
2094specify that the thread safety analysis should not be run on that function.
2095This attribute provides an escape hatch (e.g. for situations when it is
2096difficult to annotate the locking policy).
2097
2098``lockable``
2099------------
2100
2101Use ``__attribute__((lockable))`` on a class definition to specify that it has
2102a lockable type (e.g. a Mutex class). This annotation is primarily used to
2103check consistency.
2104
2105``scoped_lockable``
2106-------------------
2107
2108Use ``__attribute__((scoped_lockable))`` on a class definition to specify that
2109it has a "scoped" lockable type. Objects of this type will acquire the lock
2110upon construction and release it upon going out of scope. This annotation is
2111primarily used to check consistency.
2112
2113``guarded_var``
2114---------------
2115
2116Use ``__attribute__((guarded_var))`` on a variable declaration to specify that
2117the variable must be accessed while holding some lock.
2118
2119``pt_guarded_var``
2120------------------
2121
2122Use ``__attribute__((pt_guarded_var))`` on a pointer declaration to specify
2123that the pointer must be dereferenced while holding some lock.
2124
2125``guarded_by(l)``
2126-----------------
2127
2128Use ``__attribute__((guarded_by(l)))`` on a variable declaration to specify
2129that the variable must be accessed while holding lock ``l``.
2130
2131``pt_guarded_by(l)``
2132--------------------
2133
2134Use ``__attribute__((pt_guarded_by(l)))`` on a pointer declaration to specify
2135that the pointer must be dereferenced while holding lock ``l``.
2136
2137``acquired_before(...)``
2138------------------------
2139
2140Use ``__attribute__((acquired_before(...)))`` on a declaration of a lockable
2141variable to specify that the lock must be acquired before all attribute
2142arguments. Arguments must be lockable type, and there must be at least one
2143argument.
2144
2145``acquired_after(...)``
2146-----------------------
2147
2148Use ``__attribute__((acquired_after(...)))`` on a declaration of a lockable
2149variable to specify that the lock must be acquired after all attribute
2150arguments. Arguments must be lockable type, and there must be at least one
2151argument.
2152
2153``exclusive_lock_function(...)``
2154--------------------------------
2155
2156Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration
2157to specify that the function acquires all listed locks exclusively. This
2158attribute takes zero or more arguments: either of lockable type or integers
2159indexing into function parameters of lockable type. If no arguments are given,
2160the acquired lock is implicitly ``this`` of the enclosing object.
2161
2162``shared_lock_function(...)``
2163-----------------------------
2164
2165Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to
2166specify that the function acquires all listed locks, although the locks may be
2167shared (e.g. read locks). This attribute takes zero or more arguments: either
2168of lockable type or integers indexing into function parameters of lockable
2169type. If no arguments are given, the acquired lock is implicitly ``this`` of
2170the enclosing object.
2171
2172``exclusive_trylock_function(...)``
2173-----------------------------------
2174
2175Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration
2176to specify that the function will try (without blocking) to acquire all listed
2177locks exclusively. This attribute takes one or more arguments. The first
2178argument is an integer or boolean value specifying the return value of a
2179successful lock acquisition. The remaining arugments are either of lockable
2180type or integers indexing into function parameters of lockable type. If only
2181one argument is given, the acquired lock is implicitly ``this`` of the
2182enclosing object.
2183
2184``shared_trylock_function(...)``
2185--------------------------------
2186
2187Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to
2188specify that the function will try (without blocking) to acquire all listed
2189locks, although the locks may be shared (e.g. read locks). This attribute
2190takes one or more arguments. The first argument is an integer or boolean value
2191specifying the return value of a successful lock acquisition. The remaining
2192arugments are either of lockable type or integers indexing into function
2193parameters of lockable type. If only one argument is given, the acquired lock
2194is implicitly ``this`` of the enclosing object.
2195
2196``unlock_function(...)``
2197------------------------
2198
2199Use ``__attribute__((unlock_function(...)))`` on a function declaration to
2200specify that the function release all listed locks. This attribute takes zero
2201or more arguments: either of lockable type or integers indexing into function
2202parameters of lockable type. If no arguments are given, the acquired lock is
2203implicitly ``this`` of the enclosing object.
2204
2205``lock_returned(l)``
2206--------------------
2207
2208Use ``__attribute__((lock_returned(l)))`` on a function declaration to specify
2209that the function returns lock ``l`` (``l`` must be of lockable type). This
2210annotation is used to aid in resolving lock expressions.
2211
2212``locks_excluded(...)``
2213-----------------------
2214
2215Use ``__attribute__((locks_excluded(...)))`` on a function declaration to
2216specify that the function must not be called with the listed locks. Arguments
2217must be lockable type, and there must be at least one argument.
2218
2219``exclusive_locks_required(...)``
2220---------------------------------
2221
2222Use ``__attribute__((exclusive_locks_required(...)))`` on a function
2223declaration to specify that the function must be called while holding the
2224listed exclusive locks. Arguments must be lockable type, and there must be at
2225least one argument.
2226
2227``shared_locks_required(...)``
2228------------------------------
2229
2230Use ``__attribute__((shared_locks_required(...)))`` on a function declaration
2231to specify that the function must be called while holding the listed shared
2232locks. Arguments must be lockable type, and there must be at least one
2233argument.
2234
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00002235Consumed Annotation Checking
2236============================
2237
2238Clang supports additional attributes for checking basic resource management
2239properties, specifically for unique objects that have a single owning reference.
2240The following attributes are currently supported, although **the implementation
2241for these annotations is currently in development and are subject to change.**
2242
Chris Wailes155df712013-10-21 20:54:06 +00002243``consumable``
2244--------------
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00002245
Chris Wailes155df712013-10-21 20:54:06 +00002246Each class that uses any of the following annotations must first be marked
2247using the consumable attribute. Failure to do so will result in a warning.
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00002248
Chris Wailes155df712013-10-21 20:54:06 +00002249``set_typestate(new_state)``
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00002250----------------------------
2251
Chris Wailes155df712013-10-21 20:54:06 +00002252Annotate methods that transition an object into a new state with
2253``__attribute__((set_typestate(new_state)))``. The new new state must be
2254unconsumed, consumed, or unknown.
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00002255
Chris Wailes155df712013-10-21 20:54:06 +00002256``callable_when(...)``
2257----------------------
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00002258
Chris Wailes155df712013-10-21 20:54:06 +00002259Use ``__attribute__((callable_when(...)))`` to indicate what states a method
2260may be called in. Valid states are unconsumed, consumed, or unknown. Each
2261argument to this attribute must be a quoted string. E.g.:
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00002262
Chris Wailes155df712013-10-21 20:54:06 +00002263``__attribute__((callable_when("unconsumed", "unknown")))``
2264
2265``tests_typestate(tested_state)``
2266---------------------------------
2267
2268Use ``__attribute__((tests_typestate(tested_state)))`` to indicate that a method
2269returns true if the object is in the specified state..
2270
2271``param_typestate(expected_state)``
2272-----------------------------------
2273
2274This attribute specifies expectations about function parameters. Calls to an
2275function with annotated parameters will issue a warning if the corresponding
2276argument isn't in the expected state. The attribute is also used to set the
2277initial state of the parameter when analyzing the function's body.
2278
2279``return_typestate(ret_state)``
2280-------------------------------
2281
2282The ``return_typestate`` attribute can be applied to functions or parameters.
2283When applied to a function the attribute specifies the state of the returned
2284value. The function's body is checked to ensure that it always returns a value
2285in the specified state. On the caller side, values returned by the annotated
2286function are initialized to the given state.
2287
2288If the attribute is applied to a function parameter it modifies the state of
2289an argument after a call to the function returns. The function's body is
2290checked to ensure that the parameter is in the expected state before returning.
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00002291
Sean Silva709c44d2012-12-12 23:44:55 +00002292Type Safety Checking
2293====================
2294
2295Clang supports additional attributes to enable checking type safety properties
Richard Smith36ee4fc2013-07-11 00:34:42 +00002296that can't be enforced by the C type system. Use cases include:
Sean Silva709c44d2012-12-12 23:44:55 +00002297
2298* MPI library implementations, where these attributes enable checking that
Richard Smith36ee4fc2013-07-11 00:34:42 +00002299 the buffer type matches the passed ``MPI_Datatype``;
2300* for HDF5 library there is a similar use case to MPI;
Sean Silva709c44d2012-12-12 23:44:55 +00002301* checking types of variadic functions' arguments for functions like
2302 ``fcntl()`` and ``ioctl()``.
2303
2304You can detect support for these attributes with ``__has_attribute()``. For
2305example:
2306
2307.. code-block:: c++
2308
2309 #if defined(__has_attribute)
2310 # if __has_attribute(argument_with_type_tag) && \
2311 __has_attribute(pointer_with_type_tag) && \
2312 __has_attribute(type_tag_for_datatype)
2313 # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
2314 /* ... other macros ... */
2315 # endif
2316 #endif
2317
2318 #if !defined(ATTR_MPI_PWT)
2319 # define ATTR_MPI_PWT(buffer_idx, type_idx)
2320 #endif
2321
2322 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
2323 ATTR_MPI_PWT(1,3);
2324
2325``argument_with_type_tag(...)``
2326-------------------------------
2327
2328Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
2329type_tag_idx)))`` on a function declaration to specify that the function
2330accepts a type tag that determines the type of some other argument.
2331``arg_kind`` is an identifier that should be used when annotating all
2332applicable type tags.
2333
2334This attribute is primarily useful for checking arguments of variadic functions
Richard Smith36ee4fc2013-07-11 00:34:42 +00002335(``pointer_with_type_tag`` can be used in most non-variadic cases).
Sean Silva709c44d2012-12-12 23:44:55 +00002336
2337For example:
2338
2339.. code-block:: c++
2340
2341 int fcntl(int fd, int cmd, ...)
2342 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
2343
2344``pointer_with_type_tag(...)``
2345------------------------------
2346
2347Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
2348on a function declaration to specify that the function accepts a type tag that
2349determines the pointee type of some other pointer argument.
2350
2351For example:
2352
2353.. code-block:: c++
2354
2355 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
2356 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
2357
2358``type_tag_for_datatype(...)``
2359------------------------------
2360
2361Clang supports annotating type tags of two forms.
2362
2363* **Type tag that is an expression containing a reference to some declared
2364 identifier.** Use ``__attribute__((type_tag_for_datatype(kind, type)))`` on a
2365 declaration with that identifier:
2366
2367 .. code-block:: c++
2368
2369 extern struct mpi_datatype mpi_datatype_int
2370 __attribute__(( type_tag_for_datatype(mpi,int) ));
2371 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
2372
2373* **Type tag that is an integral literal.** Introduce a ``static const``
2374 variable with a corresponding initializer value and attach
2375 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration,
2376 for example:
2377
2378 .. code-block:: c++
2379
2380 #define MPI_INT ((MPI_Datatype) 42)
2381 static const MPI_Datatype mpi_datatype_int
2382 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42
2383
2384The attribute also accepts an optional third argument that determines how the
2385expression is compared to the type tag. There are two supported flags:
2386
2387* ``layout_compatible`` will cause types to be compared according to
2388 layout-compatibility rules (C++11 [class.mem] p 17, 18). This is
2389 implemented to support annotating types like ``MPI_DOUBLE_INT``.
2390
2391 For example:
2392
2393 .. code-block:: c++
2394
2395 /* In mpi.h */
2396 struct internal_mpi_double_int { double d; int i; };
2397 extern struct mpi_datatype mpi_datatype_double_int
2398 __attribute__(( type_tag_for_datatype(mpi, struct internal_mpi_double_int, layout_compatible) ));
2399
2400 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
2401
2402 /* In user code */
2403 struct my_pair { double a; int b; };
2404 struct my_pair *buffer;
2405 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning
2406
2407 struct my_int_pair { int a; int b; }
2408 struct my_int_pair *buffer2;
2409 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning: actual buffer element
2410 // type 'struct my_int_pair'
2411 // doesn't match specified MPI_Datatype
2412
2413* ``must_be_null`` specifies that the expression should be a null pointer
2414 constant, for example:
2415
2416 .. code-block:: c++
2417
2418 /* In mpi.h */
2419 extern struct mpi_datatype mpi_datatype_null
2420 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
2421
2422 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
2423
2424 /* In user code */
2425 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
2426 // was specified but buffer
2427 // is not a null pointer
2428
Dmitri Gribenkodc81f512013-01-13 16:37:18 +00002429Format String Checking
2430======================
2431
2432Clang supports the ``format`` attribute, which indicates that the function
2433accepts a ``printf`` or ``scanf``-like format string and corresponding
2434arguments or a ``va_list`` that contains these arguments.
2435
2436Please see `GCC documentation about format attribute
2437<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
2438about attribute syntax.
2439
2440Clang implements two kinds of checks with this attribute.
2441
2442#. Clang checks that the function with the ``format`` attribute is called with
2443 a format string that uses format specifiers that are allowed, and that
2444 arguments match the format string. This is the ``-Wformat`` warning, it is
2445 on by default.
2446
2447#. Clang checks that the format string argument is a literal string. This is
2448 the ``-Wformat-nonliteral`` warning, it is off by default.
2449
2450 Clang implements this mostly the same way as GCC, but there is a difference
2451 for functions that accept a ``va_list`` argument (for example, ``vprintf``).
2452 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
2453 fuctions. Clang does not warn if the format string comes from a function
Richard Smithfabbcd92013-02-14 00:22:00 +00002454 parameter, where the function is annotated with a compatible attribute,
Dmitri Gribenkodc81f512013-01-13 16:37:18 +00002455 otherwise it warns. For example:
2456
2457 .. code-block:: c
2458
2459 __attribute__((__format__ (__scanf__, 1, 3)))
2460 void foo(const char* s, char *buf, ...) {
2461 va_list ap;
2462 va_start(ap, buf);
2463
2464 vprintf(s, ap); // warning: format string is not a string literal
2465 }
2466
2467 In this case we warn because ``s`` contains a format string for a
Richard Smithfabbcd92013-02-14 00:22:00 +00002468 ``scanf``-like function, but it is passed to a ``printf``-like function.
Dmitri Gribenkodc81f512013-01-13 16:37:18 +00002469
2470 If the attribute is removed, clang still warns, because the format string is
2471 not a string literal.
2472
Richard Smithfabbcd92013-02-14 00:22:00 +00002473 Another example:
Dmitri Gribenkodc81f512013-01-13 16:37:18 +00002474
Richard Smithd06a8702013-02-14 00:23:04 +00002475 .. code-block:: c
Dmitri Gribenkodc81f512013-01-13 16:37:18 +00002476
2477 __attribute__((__format__ (__printf__, 1, 3)))
2478 void foo(const char* s, char *buf, ...) {
2479 va_list ap;
2480 va_start(ap, buf);
2481
2482 vprintf(s, ap); // warning
2483 }
2484
Richard Smithfabbcd92013-02-14 00:22:00 +00002485 In this case Clang does not warn because the format string ``s`` and
2486 the corresponding arguments are annotated. If the arguments are
2487 incorrect, the caller of ``foo`` will receive a warning.