1 //==--- AttrDocs.td - Attribute documentation ----------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===---------------------------------------------------------------------===//
9 // To test that the documentation builds cleanly, you must run clang-tblgen to
10 // convert the .td file into a .rst file, and then run sphinx to convert the
11 // .rst file into an HTML file. After completing testing, you should revert the
12 // generated .rst file so that the modified version does not get checked in to
15 // To run clang-tblgen to generate the .rst file:
16 // clang-tblgen -gen-attr-docs -I <root>/llvm/tools/clang/include
17 // <root>/llvm/tools/clang/include/clang/Basic/Attr.td -o
18 // <root>/llvm/tools/clang/docs/AttributeReference.rst
20 // To run sphinx to generate the .html files (note that sphinx-build must be
21 // available on the PATH):
22 // Windows (from within the clang\docs directory):
24 // Non-Windows (from within the clang\docs directory):
25 // make -f Makefile.sphinx html
27 def GlobalDocumentation {
29 -------------------------------------------------------------------
30 NOTE: This file is automatically generated by running clang-tblgen
31 -gen-attr-docs. Do not edit this file by hand!!
32 -------------------------------------------------------------------
47 This page lists the attributes currently supported by Clang.
51 def SectionDocs : Documentation {
52 let Category = DocCatVariable;
54 The ``section`` attribute allows you to specify a specific section a
55 global variable or function should be in after translation.
57 let Heading = "section, __declspec(allocate)";
60 def InitSegDocs : Documentation {
61 let Category = DocCatVariable;
63 The attribute applied by ``pragma init_seg()`` controls the section into
64 which global initialization function pointers are emitted. It is only
65 available with ``-fms-extensions``. Typically, this function pointer is
66 emitted into ``.CRT$XCU`` on Windows. The user can change the order of
67 initialization by using a different section name with the same
68 ``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
69 after the standard ``.CRT$XCU`` sections. See the init_seg_
70 documentation on MSDN for more information.
72 .. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx
76 def TLSModelDocs : Documentation {
77 let Category = DocCatVariable;
79 The ``tls_model`` attribute allows you to specify which thread-local storage
80 model to use. It accepts the following strings:
87 TLS models are mutually exclusive.
91 def DLLExportDocs : Documentation {
92 let Category = DocCatVariable;
94 The ``__declspec(dllexport)`` attribute declares a variable, function, or
95 Objective-C interface to be exported from the module. It is available under the
96 ``-fdeclspec`` flag for compatibility with various compilers. The primary use
97 is for COFF object files which explicitly specify what interfaces are available
98 for external use. See the dllexport_ documentation on MSDN for more
101 .. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
105 def DLLImportDocs : Documentation {
106 let Category = DocCatVariable;
108 The ``__declspec(dllimport)`` attribute declares a variable, function, or
109 Objective-C interface to be imported from an external module. It is available
110 under the ``-fdeclspec`` flag for compatibility with various compilers. The
111 primary use is for COFF object files which explicitly specify what interfaces
112 are imported from external modules. See the dllimport_ documentation on MSDN
113 for more information.
115 .. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
119 def ThreadDocs : Documentation {
120 let Category = DocCatVariable;
122 The ``__declspec(thread)`` attribute declares a variable with thread local
123 storage. It is available under the ``-fms-extensions`` flag for MSVC
124 compatibility. See the documentation for `__declspec(thread)`_ on MSDN.
126 .. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
128 In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
129 GNU ``__thread`` keyword. The variable must not have a destructor and must have
130 a constant initializer, if any. The attribute only applies to variables
131 declared with static storage duration, such as globals, class static data
132 members, and static locals.
136 def NoEscapeDocs : Documentation {
137 let Category = DocCatVariable;
139 ``noescape`` placed on a function parameter of a pointer type is used to inform
140 the compiler that the pointer cannot escape: that is, no reference to the object
141 the pointer points to that is derived from the parameter value will survive
142 after the function returns. Users are responsible for making sure parameters
143 annotated with ``noescape`` do not actuallly escape.
151 void nonescapingFunc(__attribute__((noescape)) int *p) {
155 void escapingFunc(__attribute__((noescape)) int *p) {
159 Additionally, when the parameter is a `block pointer
160 <https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction
161 applies to copies of the block. For example:
165 typedef void (^BlockTy)();
168 void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
172 void escapingFunc(__attribute__((noescape)) BlockTy block) {
173 g0 = block; // Not OK.
174 g1 = Block_copy(block); // Not OK either.
180 def CarriesDependencyDocs : Documentation {
181 let Category = DocCatFunction;
183 The ``carries_dependency`` attribute specifies dependency propagation into and
186 When specified on a function or Objective-C method, the ``carries_dependency``
187 attribute means that the return value carries a dependency out of the function,
188 so that the implementation need not constrain ordering upon return from that
189 function. Implementations of the function and its caller may choose to preserve
190 dependencies instead of emitting memory ordering instructions such as fences.
192 Note, this attribute does not change the meaning of the program, but may result
193 in generation of more efficient code.
197 def CPUSpecificCPUDispatchDocs : Documentation {
198 let Category = DocCatFunction;
200 The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
201 resolve multiversioned functions. This form of multiversioning provides a
202 mechanism for declaring versions across translation units and manually
203 specifying the resolved function list. A specified CPU defines a set of minimum
204 features that are required for the function to be called. The result of this is
205 that future processors execute the most restrictive version of the function the
206 new processor can execute.
208 Function versions are defined with ``cpu_specific``, which takes one or more CPU
209 names as a parameter. For example:
213 // Declares and defines the ivybridge version of single_cpu.
214 __attribute__((cpu_specific(ivybridge)))
215 void single_cpu(void){}
217 // Declares and defines the atom version of single_cpu.
218 __attribute__((cpu_specific(atom)))
219 void single_cpu(void){}
221 // Declares and defines both the ivybridge and atom version of multi_cpu.
222 __attribute__((cpu_specific(ivybridge, atom)))
223 void multi_cpu(void){}
225 A dispatching (or resolving) function can be declared anywhere in a project's
226 source code with ``cpu_dispatch``. This attribute takes one or more CPU names
227 as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
228 are not expected to be defined, only declared. If such a marked function has a
229 definition, any side effects of the function are ignored; trivial function
230 bodies are permissible for ICC compatibility.
234 // Creates a resolver for single_cpu above.
235 __attribute__((cpu_dispatch(ivybridge, atom)))
236 void single_cpu(void){}
238 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
240 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
241 void multi_cpu(void){}
243 Note that it is possible to have a resolving function that dispatches based on
244 more or fewer options than are present in the program. Specifying fewer will
245 result in the omitted options not being considered during resolution. Specifying
246 a version for resolution that isn't defined in the program will result in a
249 It is also possible to specify a CPU name of ``generic`` which will be resolved
250 if the executing processor doesn't satisfy the features required in the CPU
251 name. The behavior of a program executing on a processor that doesn't satisfy
252 any option of a multiversioned function is undefined.
256 def SYCLKernelDocs : Documentation {
257 let Category = DocCatFunction;
259 The ``sycl_kernel`` attribute specifies that a function template will be used
260 to outline device code and to generate an OpenCL kernel.
261 Here is a code example of the SYCL program, which demonstrates the compiler's
265 int foo(int x) { return ++x; }
267 using namespace cl::sycl;
269 buffer<int, 1> a(range<1>{1024});
270 Q.submit([&](handler& cgh) {
271 auto A = a.get_access<access::mode::write>(cgh);
272 cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) {
273 A[index] = index[0] + foo(42);
277 A C++ function object passed to the ``parallel_for`` is called a "SYCL kernel".
278 A SYCL kernel defines the entry point to the "device part" of the code. The
279 compiler will emit all symbols accessible from a "kernel". In this code
280 example, the compiler will emit "foo" function. More details about the
281 compilation of functions for the device part can be found in the SYCL 1.2.1
282 specification Section 6.4.
283 To show to the compiler entry point to the "device part" of the code, the SYCL
284 runtime can use the ``sycl_kernel`` attribute in the following way:
289 template <typename KernelName, typename KernelType/*, ...*/>
290 __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) {
295 template <typename KernelName, typename KernelType, int Dims>
296 void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) {
297 #ifdef __SYCL_DEVICE_ONLY__
298 sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc);
300 // Host implementation
307 The compiler will also generate an OpenCL kernel using the function marked with
308 the ``sycl_kernel`` attribute.
309 Here is the list of SYCL device compiler expectations with regard to the
310 function marked with the ``sycl_kernel`` attribute:
312 - The function must be a template with at least two type template parameters.
313 The compiler generates an OpenCL kernel and uses the first template parameter
314 as a unique name for the generated OpenCL kernel. The host application uses
315 this unique name to invoke the OpenCL kernel generated for the SYCL kernel
316 specialized by this name and second template parameter ``KernelType`` (which
317 might be an unnamed function object type).
318 - The function must have at least one parameter. The first parameter is
319 required to be a function object type (named or unnamed i.e. lambda). The
320 compiler uses function object type fields to generate OpenCL kernel
322 - The function must return void. The compiler reuses the body of marked functions to
323 generate the OpenCL kernel body, and the OpenCL kernel must return `void`.
325 The SYCL kernel in the previous code sample meets these expectations.
329 def C11NoReturnDocs : Documentation {
330 let Category = DocCatFunction;
332 A function declared as ``_Noreturn`` shall not return to its caller. The
333 compiler will generate a diagnostic for a function declared as ``_Noreturn``
334 that appears to be capable of returning to its caller. Despite being a type
335 specifier, the ``_Noreturn`` attribute cannot be specified on a function
340 def CXX11NoReturnDocs : Documentation {
341 let Category = DocCatFunction;
343 A function declared as ``[[noreturn]]`` shall not return to its caller. The
344 compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
345 that appears to be capable of returning to its caller.
349 def AssertCapabilityDocs : Documentation {
350 let Category = DocCatFunction;
351 let Heading = "assert_capability, assert_shared_capability";
353 Marks a function that dynamically tests whether a capability is held, and halts
354 the program if it is not held.
358 def AcquireCapabilityDocs : Documentation {
359 let Category = DocCatFunction;
360 let Heading = "acquire_capability, acquire_shared_capability";
362 Marks a function as acquiring a capability.
366 def TryAcquireCapabilityDocs : Documentation {
367 let Category = DocCatFunction;
368 let Heading = "try_acquire_capability, try_acquire_shared_capability";
370 Marks a function that attempts to acquire a capability. This function may fail to
371 actually acquire the capability; they accept a Boolean value determining
372 whether acquiring the capability means success (true), or failing to acquire
373 the capability means success (false).
377 def ReleaseCapabilityDocs : Documentation {
378 let Category = DocCatFunction;
379 let Heading = "release_capability, release_shared_capability";
381 Marks a function as releasing a capability.
385 def AssumeAlignedDocs : Documentation {
386 let Category = DocCatFunction;
388 Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function
389 declaration to specify that the return value of the function (which must be a
390 pointer type) has the specified offset, in bytes, from an address with the
391 specified alignment. The offset is taken to be zero if omitted.
395 // The returned pointer value has 32-byte alignment.
396 void *a() __attribute__((assume_aligned (32)));
398 // The returned pointer value is 4 bytes greater than an address having
399 // 32-byte alignment.
400 void *b() __attribute__((assume_aligned (32, 4)));
402 Note that this attribute provides information to the compiler regarding a
403 condition that the code already ensures is true. It does not cause the compiler
404 to enforce the provided alignment assumption.
408 def AllocSizeDocs : Documentation {
409 let Category = DocCatFunction;
411 The ``alloc_size`` attribute can be placed on functions that return pointers in
412 order to hint to the compiler how many bytes of memory will be available at the
413 returned pointer. ``alloc_size`` takes one or two arguments.
415 - ``alloc_size(N)`` implies that argument number N equals the number of
416 available bytes at the returned pointer.
417 - ``alloc_size(N, M)`` implies that the product of argument number N and
418 argument number M equals the number of available bytes at the returned
421 Argument numbers are 1-based.
423 An example of how to use ``alloc_size``
427 void *my_malloc(int a) __attribute__((alloc_size(1)));
428 void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
431 void *const p = my_malloc(100);
432 assert(__builtin_object_size(p, 0) == 100);
433 void *const a = my_calloc(20, 5);
434 assert(__builtin_object_size(a, 0) == 100);
437 .. Note:: This attribute works differently in clang than it does in GCC.
438 Specifically, clang will only trace ``const`` pointers (as above); we give up
439 on pointers that are not marked as ``const``. In the vast majority of cases,
440 this is unimportant, because LLVM has support for the ``alloc_size``
441 attribute. However, this may cause mildly unintuitive behavior when used with
442 other attributes, such as ``enable_if``.
446 def CodeSegDocs : Documentation {
447 let Category = DocCatFunction;
449 The ``__declspec(code_seg)`` attribute enables the placement of code into separate
450 named segments that can be paged or locked in memory individually. This attribute
451 is used to control the placement of instantiated templates and compiler-generated
452 code. See the documentation for `__declspec(code_seg)`_ on MSDN.
454 .. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx
458 def AllocAlignDocs : Documentation {
459 let Category = DocCatFunction;
461 Use ``__attribute__((alloc_align(<alignment>))`` on a function
462 declaration to specify that the return value of the function (which must be a
463 pointer type) is at least as aligned as the value of the indicated parameter. The
464 parameter is given by its index in the list of formal parameters; the first
465 parameter has index 1 unless the function is a C++ non-static member function,
466 in which case the first parameter has index 2 to account for the implicit ``this``
471 // The returned pointer has the alignment specified by the first parameter.
472 void *a(size_t align) __attribute__((alloc_align(1)));
474 // The returned pointer has the alignment specified by the second parameter.
475 void *b(void *v, size_t align) __attribute__((alloc_align(2)));
477 // The returned pointer has the alignment specified by the second visible
478 // parameter, however it must be adjusted for the implicit 'this' parameter.
479 void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
481 Note that this attribute merely informs the compiler that a function always
482 returns a sufficiently aligned pointer. It does not cause the compiler to
483 emit code to enforce that alignment. The behavior is undefined if the returned
484 poitner is not sufficiently aligned.
488 def EnableIfDocs : Documentation {
489 let Category = DocCatFunction;
491 .. Note:: Some features of this attribute are experimental. The meaning of
492 multiple enable_if attributes on a single declaration is subject to change in
493 a future version of clang. Also, the ABI is not standardized and the name
494 mangling may change in future versions. To avoid that, use asm labels.
496 The ``enable_if`` attribute can be placed on function declarations to control
497 which overload is selected based on the values of the function's arguments.
498 When combined with the ``overloadable`` attribute, this feature is also
504 int isdigit(int c) __attribute__((enable_if(c <= -1 || c > 255, "chosen when 'c' is out of range"))) __attribute__((unavailable("'c' must have the value of an unsigned char or EOF")));
509 isdigit(-10); // results in a compile-time error.
512 The enable_if attribute takes two arguments, the first is an expression written
513 in terms of the function parameters, the second is a string explaining why this
514 overload candidate could not be selected to be displayed in diagnostics. The
515 expression is part of the function signature for the purposes of determining
516 whether it is a redeclaration (following the rules used when determining
517 whether a C++ template specialization is ODR-equivalent), but is not part of
520 The enable_if expression is evaluated as if it were the body of a
521 bool-returning constexpr function declared with the arguments of the function
522 it is being applied to, then called with the parameters at the call site. If the
523 result is false or could not be determined through constant expression
524 evaluation, then this overload will not be chosen and the provided string may
525 be used in a diagnostic if the compile fails as a result.
527 Because the enable_if expression is an unevaluated context, there are no global
528 state changes, nor the ability to pass information from the enable_if
529 expression to the function body. For example, suppose we want calls to
530 strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
531 strbuf) only if the size of strbuf can be determined:
535 __attribute__((always_inline))
536 static inline size_t strnlen(const char *s, size_t maxlen)
537 __attribute__((overloadable))
538 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
539 "chosen when the buffer size is known but 'maxlen' is not")))
541 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
544 Multiple enable_if attributes may be applied to a single declaration. In this
545 case, the enable_if expressions are evaluated from left to right in the
546 following manner. First, the candidates whose enable_if expressions evaluate to
547 false or cannot be evaluated are discarded. If the remaining candidates do not
548 share ODR-equivalent enable_if expressions, the overload resolution is
549 ambiguous. Otherwise, enable_if overload resolution continues with the next
550 enable_if attribute on the candidates that have not been discarded and have
551 remaining enable_if attributes. In this way, we pick the most specific
552 overload out of a number of viable overloads using enable_if.
556 void f() __attribute__((enable_if(true, ""))); // #1
557 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
559 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
560 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
562 In this example, a call to f() is always resolved to #2, as the first enable_if
563 expression is ODR-equivalent for both declarations, but #1 does not have another
564 enable_if expression to continue evaluating, so the next round of evaluation has
565 only a single candidate. In a call to g(1, 1), the call is ambiguous even though
566 #2 has more enable_if attributes, because the first enable_if expressions are
569 Query for this feature with ``__has_attribute(enable_if)``.
571 Note that functions with one or more ``enable_if`` attributes may not have
572 their address taken, unless all of the conditions specified by said
573 ``enable_if`` are constants that evaluate to ``true``. For example:
577 const int TrueConstant = 1;
578 const int FalseConstant = 0;
579 int f(int a) __attribute__((enable_if(a > 0, "")));
580 int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
581 int h(int a) __attribute__((enable_if(1, "")));
582 int i(int a) __attribute__((enable_if(TrueConstant, "")));
583 int j(int a) __attribute__((enable_if(FalseConstant, "")));
587 ptr = &f; // error: 'a > 0' is not always true
588 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
589 ptr = &h; // OK: 1 is a truthy constant
590 ptr = &i; // OK: 'TrueConstant' is a truthy constant
591 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
594 Because ``enable_if`` evaluation happens during overload resolution,
595 ``enable_if`` may give unintuitive results when used with templates, depending
596 on when overloads are resolved. In the example below, clang will emit a
597 diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``:
601 double foo(int i) __attribute__((enable_if(i > 0, "")));
602 void *foo(int i) __attribute__((enable_if(i <= 0, "")));
604 auto bar() { return foo(I); }
606 template <typename T>
607 auto baz() { return foo(T::number); }
609 struct WithNumber { constexpr static int number = 1; };
611 bar<sizeof(WithNumber)>();
615 This is because, in ``bar``, ``foo`` is resolved prior to template
616 instantiation, so the value for ``I`` isn't known (thus, both ``enable_if``
617 conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during
618 template instantiation, so the value for ``T::number`` is known.
622 def DiagnoseIfDocs : Documentation {
623 let Category = DocCatFunction;
625 The ``diagnose_if`` attribute can be placed on function declarations to emit
626 warnings or errors at compile-time if calls to the attributed function meet
627 certain user-defined criteria. For example:
632 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
634 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
636 int val = abs(1); // warning: Redundant abs call
637 int val2 = must_abs(1); // error: Redundant abs call
639 int val4 = must_abs(val); // Because run-time checks are not emitted for
640 // diagnose_if attributes, this executes without
644 ``diagnose_if`` is closely related to ``enable_if``, with a few key differences:
646 * Overload resolution is not aware of ``diagnose_if`` attributes: they're
647 considered only after we select the best candidate from a given candidate set.
648 * Function declarations that differ only in their ``diagnose_if`` attributes are
649 considered to be redeclarations of the same function (not overloads).
650 * If the condition provided to ``diagnose_if`` cannot be evaluated, no
651 diagnostic will be emitted.
653 Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``.
655 As a result of bullet number two, ``diagnose_if`` attributes will stack on the
656 same function. For example:
660 int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
661 int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
663 int bar = foo(); // warning: diag1
665 int (*fooptr)(void) = foo; // warning: diag1
668 constexpr int supportsAPILevel(int N) { return N < 5; }
670 __attribute__((diagnose_if(!supportsAPILevel(10),
671 "Upgrade to API level 10 to use baz", "error")));
673 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
675 int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
676 int v = baz(0); // error: Upgrade to API level 10 to use baz
678 Query for this feature with ``__has_attribute(diagnose_if)``.
682 def PassObjectSizeDocs : Documentation {
683 let Category = DocCatVariable; // Technically it's a parameter doc, but eh.
684 let Heading = "pass_object_size, pass_dynamic_object_size";
686 .. Note:: The mangling of functions with parameters that are annotated with
687 ``pass_object_size`` is subject to change. You can get around this by
688 using ``__asm__("foo")`` to explicitly name your functions, thus preserving
689 your ABI; also, non-overloadable C functions with ``pass_object_size`` are
692 The ``pass_object_size(Type)`` attribute can be placed on function parameters to
693 instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite
694 of said function, and implicitly pass the result of this call in as an invisible
695 argument of type ``size_t`` directly after the parameter annotated with
696 ``pass_object_size``. Clang will also replace any calls to
697 ``__builtin_object_size(param, Type)`` in the function by said implicit
704 int bzero1(char *const p __attribute__((pass_object_size(0))))
705 __attribute__((noinline)) {
707 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
715 int n = bzero1(&chars[0]);
716 assert(n == sizeof(chars));
720 If successfully evaluating ``__builtin_object_size(param, Type)`` at the
721 callsite is not possible, then the "failed" value is passed in. So, using the
722 definition of ``bzero1`` from above, the following code would exit cleanly:
726 int main2(int argc, char *argv[]) {
727 int n = bzero1(argv);
732 ``pass_object_size`` plays a part in overload resolution. If two overload
733 candidates are otherwise equally good, then the overload with one or more
734 parameters with ``pass_object_size`` is preferred. This implies that the choice
735 between two identical overloads both with ``pass_object_size`` on one or more
736 parameters will always be ambiguous; for this reason, having two such overloads
737 is illegal. For example:
741 #define PS(N) __attribute__((pass_object_size(N)))
743 void Foo(char *a, char *b); // Overload A
744 // OK -- overload A has no parameters with pass_object_size.
745 void Foo(char *a PS(0), char *b PS(0)); // Overload B
746 // Error -- Same signature (sans pass_object_size) as overload B, and both
747 // overloads have one or more parameters with the pass_object_size attribute.
748 void Foo(void *a PS(0), void *b);
751 void Bar(void *a PS(0)); // Overload C
753 void Bar(char *c PS(1)); // Overload D
756 char known[10], *unknown;
757 Foo(unknown, unknown); // Calls overload B
758 Foo(known, unknown); // Calls overload B
759 Foo(unknown, known); // Calls overload B
760 Foo(known, known); // Calls overload B
762 Bar(known); // Calls overload D
763 Bar(unknown); // Calls overload D
766 Currently, ``pass_object_size`` is a bit restricted in terms of its usage:
768 * Only one use of ``pass_object_size`` is allowed per parameter.
770 * It is an error to take the address of a function with ``pass_object_size`` on
771 any of its parameters. If you wish to do this, you can create an overload
772 without ``pass_object_size`` on any parameters.
774 * It is an error to apply the ``pass_object_size`` attribute to parameters that
775 are not pointers. Additionally, any parameter that ``pass_object_size`` is
776 applied to must be marked ``const`` at its function's definition.
778 Clang also supports the ``pass_dynamic_object_size`` attribute, which behaves
779 identically to ``pass_object_size``, but evaluates a call to
780 ``__builtin_dynamic_object_size`` at the callee instead of
781 ``__builtin_object_size``. ``__builtin_dynamic_object_size`` provides some extra
782 runtime checks when the object size can't be determined at compile-time. You can
783 read more about ``__builtin_dynamic_object_size`` `here
784 <https://clang.llvm.org/docs/LanguageExtensions.html#evaluating-object-size-dynamically>`_.
789 def OverloadableDocs : Documentation {
790 let Category = DocCatFunction;
792 Clang provides support for C++ function overloading in C. Function overloading
793 in C is introduced using the ``overloadable`` attribute. For example, one
794 might provide several overloaded versions of a ``tgsin`` function that invokes
795 the appropriate standard function computing the sine of a value with ``float``,
796 ``double``, or ``long double`` precision:
801 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
802 double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
803 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
805 Given these declarations, one can call ``tgsin`` with a ``float`` value to
806 receive a ``float`` result, with a ``double`` to receive a ``double`` result,
807 etc. Function overloading in C follows the rules of C++ function overloading
808 to pick the best overload given the call arguments, with a few C-specific
811 * Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
812 floating-point promotion (per C99) rather than as a floating-point conversion
815 * A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
816 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
819 * A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
820 and ``U`` are compatible types. This conversion is given "conversion" rank.
822 * If no viable candidates are otherwise available, we allow a conversion from a
823 pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are
824 incompatible. This conversion is ranked below all other types of conversions.
825 Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient
826 for ``T`` and ``U`` to be incompatible.
828 The declaration of ``overloadable`` functions is restricted to function
829 declarations and definitions. If a function is marked with the ``overloadable``
830 attribute, then all declarations and definitions of functions with that name,
831 except for at most one (see the note below about unmarked overloads), must have
832 the ``overloadable`` attribute. In addition, redeclarations of a function with
833 the ``overloadable`` attribute must have the ``overloadable`` attribute, and
834 redeclarations of a function without the ``overloadable`` attribute must *not*
835 have the ``overloadable`` attribute. e.g.,
839 int f(int) __attribute__((overloadable));
840 float f(float); // error: declaration of "f" must have the "overloadable" attribute
841 int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
843 int g(int) __attribute__((overloadable));
844 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
847 int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
848 // have the "overloadable" attribute
850 Functions marked ``overloadable`` must have prototypes. Therefore, the
851 following code is ill-formed:
855 int h() __attribute__((overloadable)); // error: h does not have a prototype
857 However, ``overloadable`` functions are allowed to use a ellipsis even if there
858 are no named parameters (as is permitted in C++). This feature is particularly
859 useful when combined with the ``unavailable`` attribute:
863 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
865 Functions declared with the ``overloadable`` attribute have their names mangled
866 according to the same rules as C++ function names. For example, the three
867 ``tgsin`` functions in our motivating example get the mangled names
868 ``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
869 caveats to this use of name mangling:
871 * Future versions of Clang may change the name mangling of functions overloaded
872 in C, so you should not depend on an specific mangling. To be completely
873 safe, we strongly urge the use of ``static inline`` with ``overloadable``
876 * The ``overloadable`` attribute has almost no meaning when used in C++,
877 because names will already be mangled and functions are already overloadable.
878 However, when an ``overloadable`` function occurs within an ``extern "C"``
879 linkage specification, it's name *will* be mangled in the same way as it
882 For the purpose of backwards compatibility, at most one function with the same
883 name as other ``overloadable`` functions may omit the ``overloadable``
884 attribute. In this case, the function without the ``overloadable`` attribute
885 will not have its name mangled.
891 // Notes with mangled names assume Itanium mangling.
893 int f(double) __attribute__((overloadable));
895 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
896 // was marked with overloadable).
897 f(1.0); // Emits a call to _Z1fd.
900 Support for unmarked overloads is not present in some versions of clang. You may
901 query for it using ``__has_extension(overloadable_unmarked)``.
903 Query for this attribute with ``__has_attribute(overloadable)``.
907 def ObjCMethodFamilyDocs : Documentation {
908 let Category = DocCatFunction;
910 Many methods in Objective-C have conventional meanings determined by their
911 selectors. It is sometimes useful to be able to mark a method as having a
912 particular conventional meaning despite not having the right selector, or as
913 not having the conventional meaning that its selector would suggest. For these
914 use cases, we provide an attribute to specifically describe the "method family"
915 that a method belongs to.
917 **Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
918 ``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
919 attribute can only be placed at the end of a method declaration:
923 - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
925 Users who do not wish to change the conventional meaning of a method, and who
926 merely want to document its non-standard retain and release semantics, should
927 use the retaining behavior attributes (``ns_returns_retained``,
928 ``ns_returns_not_retained``, etc).
930 Query for this feature with ``__has_attribute(objc_method_family)``.
934 def RetainBehaviorDocs : Documentation {
935 let Category = DocCatFunction;
937 The behavior of a function with respect to reference counting for Foundation
938 (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
939 convention (e.g. functions starting with "get" are assumed to return at
942 It can be overriden using a family of the following attributes. In
943 Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
944 a function communicates that the object is returned at ``+1``, and the caller
945 is responsible for freeing it.
946 Similiarly, the annotation ``__attribute__((ns_returns_not_retained))``
947 specifies that the object is returned at ``+0`` and the ownership remains with
949 The annotation ``__attribute__((ns_consumes_self))`` specifies that
950 the Objective-C method call consumes the reference to ``self``, e.g. by
951 attaching it to a supplied parameter.
952 Additionally, parameters can have an annotation
953 ``__attribute__((ns_consumed))``, which specifies that passing an owned object
954 as that parameter effectively transfers the ownership, and the caller is no
955 longer responsible for it.
956 These attributes affect code generation when interacting with ARC code, and
957 they are used by the Clang Static Analyzer.
959 In C programs using CoreFoundation, a similar set of attributes:
960 ``__attribute__((cf_returns_not_retained))``,
961 ``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
962 have the same respective semantics when applied to CoreFoundation objects.
963 These attributes affect code generation when interacting with ARC code, and
964 they are used by the Clang Static Analyzer.
966 Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
967 the same attribute family is present:
968 ``__attribute__((os_returns_not_retained))``,
969 ``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
970 with the same respective semantics.
971 Similar to ``__attribute__((ns_consumes_self))``,
972 ``__attribute__((os_consumes_this))`` specifies that the method call consumes
973 the reference to "this" (e.g., when attaching it to a different object supplied
975 Out parameters (parameters the function is meant to write into,
976 either via pointers-to-pointers or references-to-pointers)
977 may be annotated with ``__attribute__((os_returns_retained))``
978 or ``__attribute__((os_returns_not_retained))`` which specifies that the object
979 written into the out parameter should (or respectively should not) be released
981 Since often out parameters may or may not be written depending on the exit
982 code of the function,
983 annotations ``__attribute__((os_returns_retained_on_zero))``
984 and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
985 an out parameter at ``+1`` is written if and only if the function returns a zero
986 (respectively non-zero) error code.
987 Observe that return-code-dependent out parameter annotations are only
988 available for retained out parameters, as non-retained object do not have to be
989 released by the callee.
990 These attributes are only used by the Clang Static Analyzer.
992 The family of attributes ``X_returns_X_retained`` can be added to functions,
993 C++ methods, and Objective-C methods and properties.
994 Attributes ``X_consumed`` can be added to parameters of methods, functions,
995 and Objective-C methods.
999 def NoDebugDocs : Documentation {
1000 let Category = DocCatVariable;
1002 The ``nodebug`` attribute allows you to suppress debugging information for a
1003 function or method, or for a variable that is not a parameter or a non-static
1008 def NoDuplicateDocs : Documentation {
1009 let Category = DocCatFunction;
1011 The ``noduplicate`` attribute can be placed on function declarations to control
1012 whether function calls to this function can be duplicated or not as a result of
1013 optimizations. This is required for the implementation of functions with
1014 certain special requirements, like the OpenCL "barrier" function, that might
1015 need to be run concurrently by all the threads that are executing in lockstep
1016 on the hardware. For example this attribute applied on the function
1017 "nodupfunc" in the code below avoids that:
1021 void nodupfunc() __attribute__((noduplicate));
1022 // Setting it as a C++11 attribute is also valid
1023 // void nodupfunc() [[clang::noduplicate]];
1034 gets possibly modified by some optimizations into code similar to this:
1046 where the call to "nodupfunc" is duplicated and sunk into the two branches
1051 def ConvergentDocs : Documentation {
1052 let Category = DocCatFunction;
1054 The ``convergent`` attribute can be placed on a function declaration. It is
1055 translated into the LLVM ``convergent`` attribute, which indicates that the call
1056 instructions of a function with this attribute cannot be made control-dependent
1057 on any additional values.
1059 In languages designed for SPMD/SIMT programming model, e.g. OpenCL or CUDA,
1060 the call instructions of a function with this attribute must be executed by
1061 all work items or threads in a work group or sub group.
1063 This attribute is different from ``noduplicate`` because it allows duplicating
1064 function calls if it can be proved that the duplicated function calls are
1065 not made control-dependent on any additional values, e.g., unrolling a loop
1066 executed by all work items.
1071 void convfunc(void) __attribute__((convergent));
1072 // Setting it as a C++11 attribute is also valid in a C++ program.
1073 // void convfunc(void) [[clang::convergent]];
1078 def NoSplitStackDocs : Documentation {
1079 let Category = DocCatFunction;
1081 The ``no_split_stack`` attribute disables the emission of the split stack
1082 preamble for a particular function. It has no effect if ``-fsplit-stack``
1087 def NoUniqueAddressDocs : Documentation {
1088 let Category = DocCatField;
1090 The ``no_unique_address`` attribute allows tail padding in a non-static data
1091 member to overlap other members of the enclosing class (and in the special
1092 case when the type is empty, permits it to fully overlap other members).
1093 The field is laid out as if a base class were encountered at the corresponding
1094 point within the class (except that it does not share a vptr with the enclosing
1101 template<typename T, typename Alloc> struct my_vector {
1103 [[no_unique_address]] Alloc alloc;
1106 static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*));
1108 ``[[no_unique_address]]`` is a standard C++20 attribute. Clang supports its use
1113 def ObjCRequiresSuperDocs : Documentation {
1114 let Category = DocCatFunction;
1116 Some Objective-C classes allow a subclass to override a particular method in a
1117 parent class but expect that the overriding method also calls the overridden
1118 method in the parent class. For these cases, we provide an attribute to
1119 designate that a method requires a "call to ``super``" in the overriding
1120 method in the subclass.
1122 **Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
1123 be placed at the end of a method declaration:
1125 .. code-block:: objc
1127 - (void)foo __attribute__((objc_requires_super));
1129 This attribute can only be applied the method declarations within a class, and
1130 not a protocol. Currently this attribute does not enforce any placement of
1131 where the call occurs in the overriding method (such as in the case of
1132 ``-dealloc`` where the call must appear at the end). It checks only that it
1135 Note that on both OS X and iOS that the Foundation framework provides a
1136 convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
1139 .. code-block:: objc
1141 - (void)foo NS_REQUIRES_SUPER;
1143 This macro is conditionally defined depending on the compiler's support for
1144 this attribute. If the compiler does not support the attribute the macro
1147 Operationally, when a method has this annotation the compiler will warn if the
1148 implementation of an override in a subclass does not call super. For example:
1150 .. code-block:: objc
1152 warning: method possibly missing a [super AnnotMeth] call
1153 - (void) AnnotMeth{};
1158 def ObjCRuntimeNameDocs : Documentation {
1159 let Category = DocCatDecl;
1161 By default, the Objective-C interface or protocol identifier is used
1162 in the metadata name for that object. The `objc_runtime_name`
1163 attribute allows annotated interfaces or protocols to use the
1164 specified string argument in the object's metadata name instead of the
1167 **Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute
1168 can only be placed before an @protocol or @interface declaration:
1170 .. code-block:: objc
1172 __attribute__((objc_runtime_name("MyLocalName")))
1179 def ObjCRuntimeVisibleDocs : Documentation {
1180 let Category = DocCatDecl;
1182 This attribute specifies that the Objective-C class to which it applies is
1183 visible to the Objective-C runtime but not to the linker. Classes annotated
1184 with this attribute cannot be subclassed and cannot have categories defined for
1189 def ObjCClassStubDocs : Documentation {
1190 let Category = DocCatType;
1192 This attribute specifies that the Objective-C class to which it applies is
1193 instantiated at runtime.
1195 Unlike ``__attribute__((objc_runtime_visible))``, a class having this attribute
1196 still has a "class stub" that is visible to the linker. This allows categories
1197 to be defined. Static message sends with the class as a receiver use a special
1198 access pattern to ensure the class is lazily instantiated from the class stub.
1200 Classes annotated with this attribute cannot be subclassed and cannot have
1201 implementations defined for them. This attribute is intended for use in
1202 Swift-generated headers for classes defined in Swift.
1204 Adding or removing this attribute to a class is an ABI-breaking change.
1208 def ObjCBoxableDocs : Documentation {
1209 let Category = DocCatDecl;
1211 Structs and unions marked with the ``objc_boxable`` attribute can be used
1212 with the Objective-C boxed expression syntax, ``@(...)``.
1214 **Usage**: ``__attribute__((objc_boxable))``. This attribute
1215 can only be placed on a declaration of a trivially-copyable struct or union:
1217 .. code-block:: objc
1219 struct __attribute__((objc_boxable)) some_struct {
1222 union __attribute__((objc_boxable)) some_union {
1226 typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
1231 NSValue *boxed = @(ss);
1236 def AvailabilityDocs : Documentation {
1237 let Category = DocCatFunction;
1239 The ``availability`` attribute can be placed on declarations to describe the
1240 lifecycle of that declaration relative to operating system versions. Consider
1241 the function declaration for a hypothetical function ``f``:
1245 void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
1247 The availability attribute states that ``f`` was introduced in macOS 10.4,
1248 deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
1249 is used by Clang to determine when it is safe to use ``f``: for example, if
1250 Clang is instructed to compile code for macOS 10.5, a call to ``f()``
1251 succeeds. If Clang is instructed to compile code for macOS 10.6, the call
1252 succeeds but Clang emits a warning specifying that the function is deprecated.
1253 Finally, if Clang is instructed to compile code for macOS 10.7, the call
1254 fails because ``f()`` is no longer available.
1256 The availability attribute is a comma-separated list starting with the
1257 platform name and then including clauses specifying important milestones in the
1258 declaration's lifetime (in any order) along with additional information. Those
1261 introduced=\ *version*
1262 The first version in which this declaration was introduced.
1264 deprecated=\ *version*
1265 The first version in which this declaration was deprecated, meaning that
1266 users should migrate away from this API.
1268 obsoleted=\ *version*
1269 The first version in which this declaration was obsoleted, meaning that it
1270 was removed completely and can no longer be used.
1273 This declaration is never available on this platform.
1275 message=\ *string-literal*
1276 Additional message text that Clang will provide when emitting a warning or
1277 error about use of a deprecated or obsoleted declaration. Useful to direct
1278 users to replacement APIs.
1280 replacement=\ *string-literal*
1281 Additional message text that Clang will use to provide Fix-It when emitting
1282 a warning about use of a deprecated declaration. The Fix-It will replace
1283 the deprecated declaration with the new declaration specified.
1285 Multiple availability attributes can be placed on a declaration, which may
1286 correspond to different platforms. For most platforms, the availability
1287 attribute with the platform corresponding to the target platform will be used;
1288 any others will be ignored. However, the availability for ``watchOS`` and
1289 ``tvOS`` can be implicitly inferred from an ``iOS`` availability attribute.
1290 Any explicit availability attributes for those platforms are still prefered over
1291 the implicitly inferred availability attributes. If no availability attribute
1292 specifies availability for the current target platform, the availability
1293 attributes are ignored. Supported platforms are:
1296 Apple's iOS operating system. The minimum deployment target is specified by
1297 the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
1298 command-line arguments.
1301 Apple's macOS operating system. The minimum deployment target is
1302 specified by the ``-mmacosx-version-min=*version*`` command-line argument.
1303 ``macosx`` is supported for backward-compatibility reasons, but it is
1307 Apple's tvOS operating system. The minimum deployment target is specified by
1308 the ``-mtvos-version-min=*version*`` command-line argument.
1311 Apple's watchOS operating system. The minimum deployment target is specified by
1312 the ``-mwatchos-version-min=*version*`` command-line argument.
1314 A declaration can typically be used even when deploying back to a platform
1315 version prior to when the declaration was introduced. When this happens, the
1316 declaration is `weakly linked
1317 <https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
1318 as if the ``weak_import`` attribute were added to the declaration. A
1319 weakly-linked declaration may or may not be present a run-time, and a program
1320 can determine whether the declaration is present by checking whether the
1321 address of that declaration is non-NULL.
1323 The flag ``strict`` disallows using API when deploying back to a
1324 platform version prior to when the declaration was introduced. An
1325 attempt to use such API before its introduction causes a hard error.
1326 Weakly-linking is almost always a better API choice, since it allows
1327 users to query availability at runtime.
1329 If there are multiple declarations of the same entity, the availability
1330 attributes must either match on a per-platform basis or later
1331 declarations must not have availability attributes for that
1332 platform. For example:
1336 void g(void) __attribute__((availability(macos,introduced=10.4)));
1337 void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
1338 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
1339 void g(void); // okay, inherits both macos and ios availability from above.
1340 void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
1342 When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
1344 .. code-block:: objc
1347 - (id)method __attribute__((availability(macos,introduced=10.4)));
1348 - (id)method2 __attribute__((availability(macos,introduced=10.4)));
1352 - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
1353 - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
1356 Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from
1357 ``<os/availability.h>`` can simplify the spelling:
1359 .. code-block:: objc
1362 - (id)method API_AVAILABLE(macos(10.11)));
1363 - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1366 Availability attributes can also be applied using a ``#pragma clang attribute``.
1367 Any explicit availability attribute whose platform corresponds to the target
1368 platform is applied to a declaration regardless of the availability attributes
1369 specified in the pragma. For example, in the code below,
1370 ``hasExplicitAvailabilityAttribute`` will use the ``macOS`` availability
1371 attribute that is specified with the declaration, whereas
1372 ``getsThePragmaAvailabilityAttribute`` will use the ``macOS`` availability
1373 attribute that is applied by the pragma.
1377 #pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)
1378 void getsThePragmaAvailabilityAttribute(void);
1379 void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4)));
1380 #pragma clang attribute pop
1382 For platforms like ``watchOS`` and ``tvOS``, whose availability attributes can
1383 be implicitly inferred from an ``iOS`` availability attribute, the logic is
1384 slightly more complex. The explicit and the pragma-applied availability
1385 attributes whose platform corresponds to the target platform are applied as
1386 described in the previous paragraph. However, the implicitly inferred attributes
1387 are applied to a declaration only when there is no explicit or pragma-applied
1388 availability attribute whose platform corresponds to the target platform. For
1389 example, the function below will receive the ``tvOS`` availability from the
1390 pragma rather than using the inferred ``iOS`` availability from the declaration:
1394 #pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)
1395 void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0)));
1396 #pragma clang attribute pop
1398 The compiler is also able to apply implicly inferred attributes from a pragma
1399 as well. For example, when targeting ``tvOS``, the function below will receive
1400 a ``tvOS`` availability attribute that is implicitly inferred from the ``iOS``
1401 availability attribute applied by the pragma:
1405 #pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)
1406 void infersTVOSAvailabilityFromPragma(void);
1407 #pragma clang attribute pop
1409 The implicit attributes that are inferred from explicitly specified attributes
1410 whose platform corresponds to the target platform are applied to the declaration
1411 even if there is an availability attribute that can be inferred from a pragma.
1412 For example, the function below will receive the ``tvOS, introduced=11.0``
1413 availability that is inferred from the attribute on the declaration rather than
1414 inferring availability from the pragma:
1418 #pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)
1419 void infersTVOSAvailabilityFromAttributeNextToDeclaration(void)
1420 __attribute__((availability(iOS,introduced=11.0)));
1421 #pragma clang attribute pop
1423 Also see the documentation for `@available
1424 <http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_
1428 def ExternalSourceSymbolDocs : Documentation {
1429 let Category = DocCatDecl;
1431 The ``external_source_symbol`` attribute specifies that a declaration originates
1432 from an external source and describes the nature of that source.
1434 The fact that Clang is capable of recognizing declarations that were defined
1435 externally can be used to provide better tooling support for mixed-language
1436 projects or projects that rely on auto-generated code. For instance, an IDE that
1437 uses Clang and that supports mixed-language projects can use this attribute to
1438 provide a correct 'jump-to-definition' feature. For a concrete example,
1439 consider a protocol that's defined in a Swift file:
1441 .. code-block:: swift
1443 @objc public protocol SwiftProtocol {
1447 This protocol can be used from Objective-C code by including a header file that
1448 was generated by the Swift compiler. The declarations in that header can use
1449 the ``external_source_symbol`` attribute to make Clang aware of the fact
1450 that ``SwiftProtocol`` actually originates from a Swift module:
1452 .. code-block:: objc
1454 __attribute__((external_source_symbol(language="Swift",defined_in="module")))
1455 @protocol SwiftProtocol
1460 Consequently, when 'jump-to-definition' is performed at a location that
1461 references ``SwiftProtocol``, the IDE can jump to the original definition in
1462 the Swift source file rather than jumping to the Objective-C declaration in the
1463 auto-generated header file.
1465 The ``external_source_symbol`` attribute is a comma-separated list that includes
1466 clauses that describe the origin and the nature of the particular declaration.
1467 Those clauses can be:
1469 language=\ *string-literal*
1470 The name of the source language in which this declaration was defined.
1472 defined_in=\ *string-literal*
1473 The name of the source container in which the declaration was defined. The
1474 exact definition of source container is language-specific, e.g. Swift's
1475 source containers are modules, so ``defined_in`` should specify the Swift
1478 generated_declaration
1479 This declaration was automatically generated by some tool.
1481 The clauses can be specified in any order. The clauses that are listed above are
1482 all optional, but the attribute has to have at least one clause.
1486 def ConstInitDocs : Documentation {
1487 let Category = DocCatVariable;
1488 let Heading = "require_constant_initialization, constinit (C++20)";
1490 This attribute specifies that the variable to which it is attached is intended
1491 to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_
1492 according to the rules of [basic.start.static]. The variable is required to
1493 have static or thread storage duration. If the initialization of the variable
1494 is not a constant initializer an error will be produced. This attribute may
1495 only be used in C++; the ``constinit`` spelling is only accepted in C++20
1498 Note that in C++03 strict constant expression checking is not done. Instead
1499 the attribute reports if Clang can emit the variable as a constant, even if it's
1500 not technically a 'constant initializer'. This behavior is non-portable.
1502 Static storage duration variables with constant initializers avoid hard-to-find
1503 bugs caused by the indeterminate order of dynamic initialization. They can also
1504 be safely used during dynamic initialization across translation units.
1506 This attribute acts as a compile time assertion that the requirements
1507 for constant initialization have been met. Since these requirements change
1508 between dialects and have subtle pitfalls it's important to fail fast instead
1509 of silently falling back on dynamic initialization.
1511 The first use of the attribute on a variable must be part of, or precede, the
1512 initializing declaration of the variable. C++20 requires the ``constinit``
1513 spelling of the attribute to be present on the initializing declaration if it
1514 is used anywhere. The other spellings can be specified on a forward declaration
1515 and omitted on a later initializing declaration.
1520 #define SAFE_STATIC [[clang::require_constant_initialization]]
1523 ~T(); // non-trivial
1525 SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
1526 SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
1527 // copy initialization is not a constant expression on a non-literal type.
1531 def WarnMaybeUnusedDocs : Documentation {
1532 let Category = DocCatVariable;
1533 let Heading = "maybe_unused, unused";
1535 When passing the ``-Wunused`` flag to Clang, entities that are unused by the
1536 program may be diagnosed. The ``[[maybe_unused]]`` (or
1537 ``__attribute__((unused))``) attribute can be used to silence such diagnostics
1538 when the entity cannot be removed. For instance, a local variable may exist
1539 solely for use in an ``assert()`` statement, which makes the local variable
1540 unused when ``NDEBUG`` is defined.
1542 The attribute may be applied to the declaration of a class, a typedef, a
1543 variable, a function or method, a function parameter, an enumeration, an
1544 enumerator, a non-static data member, or a label.
1549 [[maybe_unused]] void f([[maybe_unused]] bool thing1,
1550 [[maybe_unused]] bool thing2) {
1551 [[maybe_unused]] bool b = thing1 && thing2;
1557 def WarnUnusedResultsDocs : Documentation {
1558 let Category = DocCatFunction;
1559 let Heading = "nodiscard, warn_unused_result";
1561 Clang supports the ability to diagnose when the results of a function call
1562 expression are discarded under suspicious circumstances. A diagnostic is
1563 generated when a function or its return type is marked with ``[[nodiscard]]``
1564 (or ``__attribute__((warn_unused_result))``) and the function call appears as a
1565 potentially-evaluated discarded-value expression that is not explicitly cast to
1568 A string literal may optionally be provided to the attribute, which will be
1569 reproduced in any resulting diagnostics. Redeclarations using different forms
1570 of the attribute (with or without the string literal or with different string
1571 literal contents) are allowed. If there are redeclarations of the entity with
1572 differing string literals, it is unspecified which one will be used by Clang
1573 in any resulting diagnostics.
1576 struct [[nodiscard]] error_info { /*...*/ };
1577 error_info enable_missile_safety_mode();
1579 void launch_missiles();
1580 void test_missiles() {
1581 enable_missile_safety_mode(); // diagnoses
1585 void f() { foo(); } // Does not diagnose, error_info is a reference.
1587 Additionally, discarded temporaries resulting from a call to a constructor
1588 marked with ``[[nodiscard]]`` or a constructor of a type marked
1589 ``[[nodiscard]]`` will also diagnose. This also applies to type conversions that
1590 use the annotated ``[[nodiscard]]`` constructor or result in an annotated type.
1593 struct [[nodiscard]] marked_type {/*..*/ };
1594 struct marked_ctor {
1595 [[nodiscard]] marked_ctor();
1600 operator marked_type() const;
1601 [[nodiscard]] operator int() const;
1605 marked_type(); // diagnoses.
1606 marked_ctor(); // diagnoses.
1607 marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard.
1610 static_cast<marked_type>(s); // diagnoses
1611 (int)s; // diagnoses
1616 def FallthroughDocs : Documentation {
1617 let Category = DocCatStmt;
1618 let Heading = "fallthrough";
1620 The ``fallthrough`` (or ``clang::fallthrough``) attribute is used
1621 to annotate intentional fall-through
1622 between switch labels. It can only be applied to a null statement placed at a
1623 point of execution between any statement and the next switch label. It is
1624 common to mark these places with a specific comment, but this attribute is
1625 meant to replace comments with a more strict annotation, which can be checked
1626 by the compiler. This attribute doesn't change semantics of the code and can
1627 be used wherever an intended fall-through occurs. It is designed to mimic
1628 control-flow statements like ``break;``, so it can be placed in most places
1629 where ``break;`` can, but only if there are no statements on the execution path
1630 between it and the next switch label.
1632 By default, Clang does not warn on unannotated fallthrough from one ``switch``
1633 case to another. Diagnostics on fallthrough without a corresponding annotation
1634 can be enabled with the ``-Wimplicit-fallthrough`` argument.
1640 // compile with -Wimplicit-fallthrough
1643 case 33: // no warning: no statements between case labels
1645 case 44: // warning: unannotated fall-through
1647 [[clang::fallthrough]];
1648 case 55: // no warning
1655 [[clang::fallthrough]];
1657 case 66: // no warning
1659 [[clang::fallthrough]]; // warning: fallthrough annotation does not
1660 // directly precede case label
1662 case 77: // warning: unannotated fall-through
1668 def ARMInterruptDocs : Documentation {
1669 let Category = DocCatFunction;
1670 let Heading = "interrupt (ARM)";
1672 Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
1673 ARM targets. This attribute may be attached to a function definition and
1674 instructs the backend to generate appropriate function entry/exit code so that
1675 it can be used directly as an interrupt service routine.
1677 The parameter passed to the interrupt attribute is optional, but if
1678 provided it must be a string literal with one of the following values: "IRQ",
1679 "FIQ", "SWI", "ABORT", "UNDEF".
1681 The semantics are as follows:
1683 - If the function is AAPCS, Clang instructs the backend to realign the stack to
1684 8 bytes on entry. This is a general requirement of the AAPCS at public
1685 interfaces, but may not hold when an exception is taken. Doing this allows
1686 other AAPCS functions to be called.
1687 - If the CPU is M-class this is all that needs to be done since the architecture
1688 itself is designed in such a way that functions obeying the normal AAPCS ABI
1689 constraints are valid exception handlers.
1690 - If the CPU is not M-class, the prologue and epilogue are modified to save all
1691 non-banked registers that are used, so that upon return the user-mode state
1692 will not be corrupted. Note that to avoid unnecessary overhead, only
1693 general-purpose (integer) registers are saved in this way. If VFP operations
1694 are needed, that state must be saved manually.
1696 Specifically, interrupt kinds other than "FIQ" will save all core registers
1697 except "lr" and "sp". "FIQ" interrupts will save r0-r7.
1698 - If the CPU is not M-class, the return instruction is changed to one of the
1699 canonical sequences permitted by the architecture for exception return. Where
1700 possible the function itself will make the necessary "lr" adjustments so that
1701 the "preferred return address" is selected.
1703 Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
1704 handler, where the offset from "lr" to the preferred return address depends on
1705 the execution state of the code which generated the exception. In this case
1706 a sequence equivalent to "movs pc, lr" will be used.
1710 def BPFPreserveAccessIndexDocs : Documentation {
1711 let Category = DocCatFunction;
1713 Clang supports the ``__attribute__((preserve_access_index))``
1714 attribute for the BPF target. This attribute may be attached to a
1715 struct or union declaration, where if -g is specified, it enables
1716 preserving struct or union member access debuginfo indicies of this
1717 struct or union, similar to clang ``__builtin_preserve_acceess_index()``.
1721 def MipsInterruptDocs : Documentation {
1722 let Category = DocCatFunction;
1723 let Heading = "interrupt (MIPS)";
1725 Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on
1726 MIPS targets. This attribute may be attached to a function definition and instructs
1727 the backend to generate appropriate function entry/exit code so that it can be used
1728 directly as an interrupt service routine.
1730 By default, the compiler will produce a function prologue and epilogue suitable for
1731 an interrupt service routine that handles an External Interrupt Controller (eic)
1732 generated interrupt. This behaviour can be explicitly requested with the "eic"
1735 Otherwise, for use with vectored interrupt mode, the argument passed should be
1736 of the form "vector=LEVEL" where LEVEL is one of the following values:
1737 "sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
1738 then set the interrupt mask to the corresponding level which will mask all
1739 interrupts up to and including the argument.
1741 The semantics are as follows:
1743 - The prologue is modified so that the Exception Program Counter (EPC) and
1744 Status coprocessor registers are saved to the stack. The interrupt mask is
1745 set so that the function can only be interrupted by a higher priority
1746 interrupt. The epilogue will restore the previous values of EPC and Status.
1748 - The prologue and epilogue are modified to save and restore all non-kernel
1749 registers as necessary.
1751 - The FPU is disabled in the prologue, as the floating pointer registers are not
1752 spilled to the stack.
1754 - The function return sequence is changed to use an exception return instruction.
1756 - The parameter sets the interrupt mask for the function corresponding to the
1757 interrupt level specified. If no mask is specified the interrupt mask
1762 def MicroMipsDocs : Documentation {
1763 let Category = DocCatFunction;
1765 Clang supports the GNU style ``__attribute__((micromips))`` and
1766 ``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
1767 may be attached to a function definition and instructs the backend to generate
1768 or not to generate microMIPS code for that function.
1770 These attributes override the `-mmicromips` and `-mno-micromips` options
1771 on the command line.
1775 def MipsLongCallStyleDocs : Documentation {
1776 let Category = DocCatFunction;
1777 let Heading = "long_call, far";
1779 Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
1780 and ``__attribute__((near))`` attributes on MIPS targets. These attributes may
1781 only be added to function declarations and change the code generated
1782 by the compiler when directly calling the function. The ``near`` attribute
1783 allows calls to the function to be made using the ``jal`` instruction, which
1784 requires the function to be located in the same naturally aligned 256MB
1785 segment as the caller. The ``long_call`` and ``far`` attributes are synonyms
1786 and require the use of a different call sequence that works regardless
1787 of the distance between the functions.
1789 These attributes have no effect for position-independent code.
1791 These attributes take priority over command line switches such
1792 as ``-mlong-calls`` and ``-mno-long-calls``.
1796 def MipsShortCallStyleDocs : Documentation {
1797 let Category = DocCatFunction;
1798 let Heading = "short_call, near";
1800 Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
1801 ``__attribute__((short__call))``, and ``__attribute__((near))`` attributes
1802 on MIPS targets. These attributes may only be added to function declarations
1803 and change the code generated by the compiler when directly calling
1804 the function. The ``short_call`` and ``near`` attributes are synonyms and
1805 allow calls to the function to be made using the ``jal`` instruction, which
1806 requires the function to be located in the same naturally aligned 256MB segment
1807 as the caller. The ``long_call`` and ``far`` attributes are synonyms and
1808 require the use of a different call sequence that works regardless
1809 of the distance between the functions.
1811 These attributes have no effect for position-independent code.
1813 These attributes take priority over command line switches such
1814 as ``-mlong-calls`` and ``-mno-long-calls``.
1818 def RISCVInterruptDocs : Documentation {
1819 let Category = DocCatFunction;
1820 let Heading = "interrupt (RISCV)";
1822 Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV
1823 targets. This attribute may be attached to a function definition and instructs
1824 the backend to generate appropriate function entry/exit code so that it can be
1825 used directly as an interrupt service routine.
1827 Permissible values for this parameter are ``user``, ``supervisor``,
1828 and ``machine``. If there is no parameter, then it defaults to machine.
1830 Repeated interrupt attribute on the same declaration will cause a warning
1831 to be emitted. In case of repeated declarations, the last one prevails.
1834 https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
1835 https://riscv.org/specifications/privileged-isa/
1836 The RISC-V Instruction Set Manual Volume II: Privileged Architecture
1841 def AVRInterruptDocs : Documentation {
1842 let Category = DocCatFunction;
1843 let Heading = "interrupt (AVR)";
1845 Clang supports the GNU style ``__attribute__((interrupt))`` attribute on
1846 AVR targets. This attribute may be attached to a function definition and instructs
1847 the backend to generate appropriate function entry/exit code so that it can be used
1848 directly as an interrupt service routine.
1850 On the AVR, the hardware globally disables interrupts when an interrupt is executed.
1851 The first instruction of an interrupt handler declared with this attribute is a SEI
1852 instruction to re-enable interrupts. See also the signal attribute that
1853 does not insert a SEI instruction.
1857 def AVRSignalDocs : Documentation {
1858 let Category = DocCatFunction;
1860 Clang supports the GNU style ``__attribute__((signal))`` attribute on
1861 AVR targets. This attribute may be attached to a function definition and instructs
1862 the backend to generate appropriate function entry/exit code so that it can be used
1863 directly as an interrupt service routine.
1865 Interrupt handler functions defined with the signal attribute do not re-enable interrupts.
1869 def TargetDocs : Documentation {
1870 let Category = DocCatFunction;
1872 Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute.
1873 This attribute may be attached to a function definition and instructs
1874 the backend to use different code generation options than were passed on the
1877 The current set of options correspond to the existing "subtarget features" for
1878 the target with or without a "-mno-" in front corresponding to the absence
1879 of the feature, as well as ``arch="CPU"`` which will change the default "CPU"
1882 For AArch64, the attribute also allows the "branch-protection=<args>" option,
1883 where the permissible arguments and their effect on code generation are the same
1884 as for the command-line option ``-mbranch-protection``.
1886 Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
1887 "avx", "xop" and largely correspond to the machine specific options handled by
1890 Additionally, this attribute supports function multiversioning for ELF based
1891 x86/x86-64 targets, which can be used to create multiple implementations of the
1892 same function that will be resolved at runtime based on the priority of their
1893 ``target`` attribute strings. A function is considered a multiversioned function
1894 if either two declarations of the function have different ``target`` attribute
1895 strings, or if it has a ``target`` attribute string of ``default``. For
1900 __attribute__((target("arch=atom")))
1901 void foo() {} // will be called on 'atom' processors.
1902 __attribute__((target("default")))
1903 void foo() {} // will be called on any other processors.
1905 All multiversioned functions must contain a ``default`` (fallback)
1906 implementation, otherwise usages of the function are considered invalid.
1907 Additionally, a function may not become multiversioned after its first use.
1911 def MinVectorWidthDocs : Documentation {
1912 let Category = DocCatFunction;
1914 Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This
1915 attribute may be attached to a function and informs the backend that this
1916 function desires vectors of at least this width to be generated. Target-specific
1917 maximum vector widths still apply. This means even if you ask for something
1918 larger than the target supports, you will only get what the target supports.
1919 This attribute is meant to be a hint to control target heuristics that may
1920 generate narrower vectors than what the target hardware supports.
1922 This is currently used by the X86 target to allow some CPUs that support 512-bit
1923 vectors to be limited to using 256-bit vectors to avoid frequency penalties.
1924 This is currently enabled with the ``-prefer-vector-width=256`` command line
1925 option. The ``min_vector_width`` attribute can be used to prevent the backend
1926 from trying to split vector operations to match the ``prefer-vector-width``. All
1927 X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
1928 use of any of the X86-specific vector builtins will implicitly set this
1929 attribute on the calling function. The intent is that explicitly writing vector
1930 code using the X86 intrinsics will prevent ``prefer-vector-width`` from
1935 def DocCatAMDGPUAttributes : DocumentationCategory<"AMD GPU Attributes">;
1937 def AMDGPUFlatWorkGroupSizeDocs : Documentation {
1938 let Category = DocCatAMDGPUAttributes;
1940 The flat work-group size is the number of work-items in the work-group size
1941 specified when the kernel is dispatched. It is the product of the sizes of the
1942 x, y, and z dimension of the work-group.
1945 ``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the
1946 AMDGPU target. This attribute may be attached to a kernel function definition
1947 and is an optimization hint.
1949 ``<min>`` parameter specifies the minimum flat work-group size, and ``<max>``
1950 parameter specifies the maximum flat work-group size (must be greater than
1951 ``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0``
1952 as ``<min>, <max>`` implies the default behavior (``128, 256``).
1954 If specified, the AMDGPU target backend might be able to produce better machine
1955 code for barriers and perform scratch promotion by estimating available group
1958 An error will be given if:
1959 - Specified values violate subtarget specifications;
1960 - Specified values are not compatible with values provided through other
1965 def AMDGPUWavesPerEUDocs : Documentation {
1966 let Category = DocCatAMDGPUAttributes;
1968 A compute unit (CU) is responsible for executing the wavefronts of a work-group.
1969 It is composed of one or more execution units (EU), which are responsible for
1970 executing the wavefronts. An EU can have enough resources to maintain the state
1971 of more than one executing wavefront. This allows an EU to hide latency by
1972 switching between wavefronts in a similar way to symmetric multithreading on a
1973 CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
1974 resources used by a single wavefront have to be limited. For example, the number
1975 of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
1976 but can result in having to spill some register state to memory.
1978 Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))``
1979 attribute for the AMDGPU target. This attribute may be attached to a kernel
1980 function definition and is an optimization hint.
1982 ``<min>`` parameter specifies the requested minimum number of waves per EU, and
1983 *optional* ``<max>`` parameter specifies the requested maximum number of waves
1984 per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted,
1985 then there is no restriction on the maximum number of waves per EU other than
1986 the one dictated by the hardware for which the kernel is compiled. Passing
1987 ``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits).
1989 If specified, this attribute allows an advanced developer to tune the number of
1990 wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
1991 target backend can use this information to limit resources, such as number of
1992 SGPRs, number of VGPRs, size of available group and private memory segments, in
1993 such a way that guarantees that at least ``<min>`` wavefronts and at most
1994 ``<max>`` wavefronts are able to fit within the resources of an EU. Requesting
1995 more wavefronts can hide memory latency but limits available registers which
1996 can result in spilling. Requesting fewer wavefronts can help reduce cache
1997 thrashing, but can reduce memory latency hiding.
1999 This attribute controls the machine code generated by the AMDGPU target backend
2000 to ensure it is capable of meeting the requested values. However, when the
2001 kernel is executed, there may be other reasons that prevent meeting the request,
2002 for example, there may be wavefronts from other kernels executing on the EU.
2004 An error will be given if:
2005 - Specified values violate subtarget specifications;
2006 - Specified values are not compatible with values provided through other
2008 - The AMDGPU target backend is unable to create machine code that can meet the
2013 def AMDGPUNumSGPRNumVGPRDocs : Documentation {
2014 let Category = DocCatAMDGPUAttributes;
2016 Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
2017 ``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
2018 target. These attributes may be attached to a kernel function definition and are
2019 an optimization hint.
2021 If these attributes are specified, then the AMDGPU target backend will attempt
2022 to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
2023 number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
2024 allocation requirements or constraints of the subtarget. Passing ``0`` as
2025 ``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
2027 These attributes can be used to test the AMDGPU target backend. It is
2028 recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
2029 resources such as SGPRs and VGPRs since it is aware of the limits for different
2032 An error will be given if:
2033 - Specified values violate subtarget specifications;
2034 - Specified values are not compatible with values provided through other
2036 - The AMDGPU target backend is unable to create machine code that can meet the
2041 def DocCatCallingConvs : DocumentationCategory<"Calling Conventions"> {
2043 Clang supports several different calling conventions, depending on the target
2044 platform and architecture. The calling convention used for a function determines
2045 how parameters are passed, how results are returned to the caller, and other
2046 low-level details of calling a function.
2050 def PcsDocs : Documentation {
2051 let Category = DocCatCallingConvs;
2053 On ARM targets, this attribute can be used to select calling conventions
2054 similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and
2059 def AArch64VectorPcsDocs : Documentation {
2060 let Category = DocCatCallingConvs;
2062 On AArch64 targets, this attribute changes the calling convention of a
2063 function to preserve additional floating-point and Advanced SIMD registers
2064 relative to the default calling convention used for AArch64.
2066 This means it is more efficient to call such functions from code that performs
2067 extensive floating-point and vector calculations, because fewer live SIMD and FP
2068 registers need to be saved. This property makes it well-suited for e.g.
2069 floating-point or vector math library functions, which are typically leaf
2070 functions that require a small number of registers.
2072 However, using this attribute also means that it is more expensive to call
2073 a function that adheres to the default calling convention from within such
2074 a function. Therefore, it is recommended that this attribute is only used
2077 For more information, see the documentation for `aarch64_vector_pcs`_ on
2078 the Arm Developer website.
2080 .. _`aarch64_vector_pcs`: https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi
2084 def RegparmDocs : Documentation {
2085 let Category = DocCatCallingConvs;
2087 On 32-bit x86 targets, the regparm attribute causes the compiler to pass
2088 the first three integer parameters in EAX, EDX, and ECX instead of on the
2089 stack. This attribute has no effect on variadic functions, and all parameters
2090 are passed via the stack as normal.
2094 def SysVABIDocs : Documentation {
2095 let Category = DocCatCallingConvs;
2097 On Windows x86_64 targets, this attribute changes the calling convention of a
2098 function to match the default convention used on Sys V targets such as Linux,
2099 Mac, and BSD. This attribute has no effect on other targets.
2103 def MSABIDocs : Documentation {
2104 let Category = DocCatCallingConvs;
2106 On non-Windows x86_64 targets, this attribute changes the calling convention of
2107 a function to match the default convention used on Windows x86_64. This
2108 attribute has no effect on Windows targets or non-x86_64 targets.
2112 def StdCallDocs : Documentation {
2113 let Category = DocCatCallingConvs;
2115 On 32-bit x86 targets, this attribute changes the calling convention of a
2116 function to clear parameters off of the stack on return. This convention does
2117 not support variadic calls or unprototyped functions in C, and has no effect on
2118 x86_64 targets. This calling convention is used widely by the Windows API and
2119 COM applications. See the documentation for `__stdcall`_ on MSDN.
2121 .. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx
2125 def FastCallDocs : Documentation {
2126 let Category = DocCatCallingConvs;
2128 On 32-bit x86 targets, this attribute changes the calling convention of a
2129 function to use ECX and EDX as register parameters and clear parameters off of
2130 the stack on return. This convention does not support variadic calls or
2131 unprototyped functions in C, and has no effect on x86_64 targets. This calling
2132 convention is supported primarily for compatibility with existing code. Users
2133 seeking register parameters should use the ``regparm`` attribute, which does
2134 not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN.
2136 .. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx
2140 def RegCallDocs : Documentation {
2141 let Category = DocCatCallingConvs;
2143 On x86 targets, this attribute changes the calling convention to
2144 `__regcall`_ convention. This convention aims to pass as many arguments
2145 as possible in registers. It also tries to utilize registers for the
2146 return value whenever it is possible.
2148 .. _`__regcall`: https://software.intel.com/en-us/node/693069
2152 def ThisCallDocs : Documentation {
2153 let Category = DocCatCallingConvs;
2155 On 32-bit x86 targets, this attribute changes the calling convention of a
2156 function to use ECX for the first parameter (typically the implicit ``this``
2157 parameter of C++ methods) and clear parameters off of the stack on return. This
2158 convention does not support variadic calls or unprototyped functions in C, and
2159 has no effect on x86_64 targets. See the documentation for `__thiscall`_ on
2162 .. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx
2166 def VectorCallDocs : Documentation {
2167 let Category = DocCatCallingConvs;
2169 On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
2170 convention of a function to pass vector parameters in SSE registers.
2172 On 32-bit x86 targets, this calling convention is similar to ``__fastcall``.
2173 The first two integer parameters are passed in ECX and EDX. Subsequent integer
2174 parameters are passed in memory, and callee clears the stack. On x86_64
2175 targets, the callee does *not* clear the stack, and integer parameters are
2176 passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
2179 On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
2180 passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
2181 passed in sequential SSE registers if enough are available. If AVX is enabled,
2182 256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
2183 cannot be passed in registers for any reason is passed by reference, which
2184 allows the caller to align the parameter memory.
2186 See the documentation for `__vectorcall`_ on MSDN for more details.
2188 .. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx
2192 def DocCatConsumed : DocumentationCategory<"Consumed Annotation Checking"> {
2194 Clang supports additional attributes for checking basic resource management
2195 properties, specifically for unique objects that have a single owning reference.
2196 The following attributes are currently supported, although **the implementation
2197 for these annotations is currently in development and are subject to change.**
2201 def SetTypestateDocs : Documentation {
2202 let Category = DocCatConsumed;
2204 Annotate methods that transition an object into a new state with
2205 ``__attribute__((set_typestate(new_state)))``. The new state must be
2206 unconsumed, consumed, or unknown.
2210 def CallableWhenDocs : Documentation {
2211 let Category = DocCatConsumed;
2213 Use ``__attribute__((callable_when(...)))`` to indicate what states a method
2214 may be called in. Valid states are unconsumed, consumed, or unknown. Each
2215 argument to this attribute must be a quoted string. E.g.:
2217 ``__attribute__((callable_when("unconsumed", "unknown")))``
2221 def TestTypestateDocs : Documentation {
2222 let Category = DocCatConsumed;
2224 Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
2225 returns true if the object is in the specified state..
2229 def ParamTypestateDocs : Documentation {
2230 let Category = DocCatConsumed;
2232 This attribute specifies expectations about function parameters. Calls to an
2233 function with annotated parameters will issue a warning if the corresponding
2234 argument isn't in the expected state. The attribute is also used to set the
2235 initial state of the parameter when analyzing the function's body.
2239 def ReturnTypestateDocs : Documentation {
2240 let Category = DocCatConsumed;
2242 The ``return_typestate`` attribute can be applied to functions or parameters.
2243 When applied to a function the attribute specifies the state of the returned
2244 value. The function's body is checked to ensure that it always returns a value
2245 in the specified state. On the caller side, values returned by the annotated
2246 function are initialized to the given state.
2248 When applied to a function parameter it modifies the state of an argument after
2249 a call to the function returns. The function's body is checked to ensure that
2250 the parameter is in the expected state before returning.
2254 def ConsumableDocs : Documentation {
2255 let Category = DocCatConsumed;
2257 Each ``class`` that uses any of the typestate annotations must first be marked
2258 using the ``consumable`` attribute. Failure to do so will result in a warning.
2260 This attribute accepts a single parameter that must be one of the following:
2261 ``unknown``, ``consumed``, or ``unconsumed``.
2265 def NoSanitizeDocs : Documentation {
2266 let Category = DocCatFunction;
2268 Use the ``no_sanitize`` attribute on a function or a global variable
2269 declaration to specify that a particular instrumentation or set of
2270 instrumentations should not be applied. The attribute takes a list of
2271 string literals, which have the same meaning as values accepted by the
2272 ``-fno-sanitize=`` flag. For example,
2273 ``__attribute__((no_sanitize("address", "thread")))`` specifies that
2274 AddressSanitizer and ThreadSanitizer should not be applied to the
2275 function or variable.
2277 See :ref:`Controlling Code Generation <controlling-code-generation>` for a
2278 full list of supported sanitizer flags.
2282 def NoSanitizeAddressDocs : Documentation {
2283 let Category = DocCatFunction;
2284 // This function has multiple distinct spellings, and so it requires a custom
2285 // heading to be specified. The most common spelling is sufficient.
2286 let Heading = "no_sanitize_address, no_address_safety_analysis";
2288 .. _langext-address_sanitizer:
2290 Use ``__attribute__((no_sanitize_address))`` on a function or a global
2291 variable declaration to specify that address safety instrumentation
2292 (e.g. AddressSanitizer) should not be applied.
2296 def NoSanitizeThreadDocs : Documentation {
2297 let Category = DocCatFunction;
2298 let Heading = "no_sanitize_thread";
2300 .. _langext-thread_sanitizer:
2302 Use ``__attribute__((no_sanitize_thread))`` on a function declaration to
2303 specify that checks for data races on plain (non-atomic) memory accesses should
2304 not be inserted by ThreadSanitizer. The function is still instrumented by the
2305 tool to avoid false positives and provide meaningful stack traces.
2309 def NoSanitizeMemoryDocs : Documentation {
2310 let Category = DocCatFunction;
2311 let Heading = "no_sanitize_memory";
2313 .. _langext-memory_sanitizer:
2315 Use ``__attribute__((no_sanitize_memory))`` on a function declaration to
2316 specify that checks for uninitialized memory should not be inserted
2317 (e.g. by MemorySanitizer). The function may still be instrumented by the tool
2318 to avoid false positives in other places.
2322 def CFICanonicalJumpTableDocs : Documentation {
2323 let Category = DocCatFunction;
2324 let Heading = "cfi_canonical_jump_table";
2326 .. _langext-cfi_canonical_jump_table:
2328 Use ``__attribute__((cfi_canonical_jump_table))`` on a function declaration to
2329 make the function's CFI jump table canonical. See :ref:`the CFI documentation
2330 <cfi-canonical-jump-tables>` for more details.
2334 def DocCatTypeSafety : DocumentationCategory<"Type Safety Checking"> {
2336 Clang supports additional attributes to enable checking type safety properties
2337 that can't be enforced by the C type system. To see warnings produced by these
2338 checks, ensure that -Wtype-safety is enabled. Use cases include:
2340 * MPI library implementations, where these attributes enable checking that
2341 the buffer type matches the passed ``MPI_Datatype``;
2342 * for HDF5 library there is a similar use case to MPI;
2343 * checking types of variadic functions' arguments for functions like
2344 ``fcntl()`` and ``ioctl()``.
2346 You can detect support for these attributes with ``__has_attribute()``. For
2351 #if defined(__has_attribute)
2352 # if __has_attribute(argument_with_type_tag) && \
2353 __has_attribute(pointer_with_type_tag) && \
2354 __has_attribute(type_tag_for_datatype)
2355 # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
2356 /* ... other macros ... */
2360 #if !defined(ATTR_MPI_PWT)
2361 # define ATTR_MPI_PWT(buffer_idx, type_idx)
2364 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
2369 def ArgumentWithTypeTagDocs : Documentation {
2370 let Category = DocCatTypeSafety;
2371 let Heading = "argument_with_type_tag";
2373 Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
2374 type_tag_idx)))`` on a function declaration to specify that the function
2375 accepts a type tag that determines the type of some other argument.
2377 This attribute is primarily useful for checking arguments of variadic functions
2378 (``pointer_with_type_tag`` can be used in most non-variadic cases).
2380 In the attribute prototype above:
2381 * ``arg_kind`` is an identifier that should be used when annotating all
2382 applicable type tags.
2383 * ``arg_idx`` provides the position of a function argument. The expected type of
2384 this function argument will be determined by the function argument specified
2385 by ``type_tag_idx``. In the code example below, "3" means that the type of the
2386 function's third argument will be determined by ``type_tag_idx``.
2387 * ``type_tag_idx`` provides the position of a function argument. This function
2388 argument will be a type tag. The type tag will determine the expected type of
2389 the argument specified by ``arg_idx``. In the code example below, "2" means
2390 that the type tag associated with the function's second argument should agree
2391 with the type of the argument specified by ``arg_idx``.
2397 int fcntl(int fd, int cmd, ...)
2398 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
2399 // The function's second argument will be a type tag; this type tag will
2400 // determine the expected type of the function's third argument.
2404 def PointerWithTypeTagDocs : Documentation {
2405 let Category = DocCatTypeSafety;
2406 let Heading = "pointer_with_type_tag";
2408 Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
2409 on a function declaration to specify that the function accepts a type tag that
2410 determines the pointee type of some other pointer argument.
2412 In the attribute prototype above:
2413 * ``ptr_kind`` is an identifier that should be used when annotating all
2414 applicable type tags.
2415 * ``ptr_idx`` provides the position of a function argument; this function
2416 argument will have a pointer type. The expected pointee type of this pointer
2417 type will be determined by the function argument specified by
2418 ``type_tag_idx``. In the code example below, "1" means that the pointee type
2419 of the function's first argument will be determined by ``type_tag_idx``.
2420 * ``type_tag_idx`` provides the position of a function argument; this function
2421 argument will be a type tag. The type tag will determine the expected pointee
2422 type of the pointer argument specified by ``ptr_idx``. In the code example
2423 below, "3" means that the type tag associated with the function's third
2424 argument should agree with the pointee type of the pointer argument specified
2431 typedef int MPI_Datatype;
2432 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
2433 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
2434 // The function's 3rd argument will be a type tag; this type tag will
2435 // determine the expected pointee type of the function's 1st argument.
2439 def TypeTagForDatatypeDocs : Documentation {
2440 let Category = DocCatTypeSafety;
2442 When declaring a variable, use
2443 ``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that
2444 is tied to the ``type`` argument given to the attribute.
2446 In the attribute prototype above:
2447 * ``kind`` is an identifier that should be used when annotating all applicable
2449 * ``type`` indicates the name of the type.
2451 Clang supports annotating type tags of two forms.
2453 * **Type tag that is a reference to a declared identifier.**
2454 Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that
2459 typedef int MPI_Datatype;
2460 extern struct mpi_datatype mpi_datatype_int
2461 __attribute__(( type_tag_for_datatype(mpi,int) ));
2462 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
2463 // &mpi_datatype_int is a type tag. It is tied to type "int".
2465 * **Type tag that is an integral literal.**
2466 Declare a ``static const`` variable with an initializer value and attach
2467 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration:
2471 typedef int MPI_Datatype;
2472 static const MPI_Datatype mpi_datatype_int
2473 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
2474 #define MPI_INT ((MPI_Datatype) 42)
2475 // The number 42 is a type tag. It is tied to type "int".
2478 The ``type_tag_for_datatype`` attribute also accepts an optional third argument
2479 that determines how the type of the function argument specified by either
2480 ``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type
2481 tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the
2482 function argument specified by ``arg_idx`` is compared against the type
2483 associated with the type tag. Also recall that for the ``pointer_with_type_tag``
2484 attribute, the pointee type of the function argument specified by ``ptr_idx`` is
2485 compared against the type associated with the type tag.) There are two supported
2486 values for this optional third argument:
2488 * ``layout_compatible`` will cause types to be compared according to
2489 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
2490 layout-compatibility rules for two standard-layout struct types and for two
2491 standard-layout union types). This is useful when creating a type tag
2492 associated with a struct or union type. For example:
2497 typedef int MPI_Datatype;
2498 struct internal_mpi_double_int { double d; int i; };
2499 extern struct mpi_datatype mpi_datatype_double_int
2500 __attribute__(( type_tag_for_datatype(mpi,
2501 struct internal_mpi_double_int, layout_compatible) ));
2503 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
2505 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
2506 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
2509 struct my_pair { double a; int b; };
2510 struct my_pair *buffer;
2511 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
2512 // layout of my_pair is
2513 // compatible with that of
2514 // internal_mpi_double_int
2516 struct my_int_pair { int a; int b; }
2517 struct my_int_pair *buffer2;
2518 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
2519 // layout of my_int_pair
2520 // does not match that of
2521 // internal_mpi_double_int
2523 * ``must_be_null`` specifies that the function argument specified by either
2524 ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for
2525 the ``pointer_with_type_tag`` attribute) should be a null pointer constant.
2526 The second argument to the ``type_tag_for_datatype`` attribute is ignored. For
2532 typedef int MPI_Datatype;
2533 extern struct mpi_datatype mpi_datatype_null
2534 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
2536 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
2537 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
2538 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
2541 struct my_pair { double a; int b; };
2542 struct my_pair *buffer;
2543 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
2544 // was specified but buffer
2545 // is not a null pointer
2549 def FlattenDocs : Documentation {
2550 let Category = DocCatFunction;
2552 The ``flatten`` attribute causes calls within the attributed function to
2553 be inlined unless it is impossible to do so, for example if the body of the
2554 callee is unavailable or if the callee has the ``noinline`` attribute.
2558 def FormatDocs : Documentation {
2559 let Category = DocCatFunction;
2562 Clang supports the ``format`` attribute, which indicates that the function
2563 accepts a ``printf`` or ``scanf``-like format string and corresponding
2564 arguments or a ``va_list`` that contains these arguments.
2566 Please see `GCC documentation about format attribute
2567 <http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
2568 about attribute syntax.
2570 Clang implements two kinds of checks with this attribute.
2572 #. Clang checks that the function with the ``format`` attribute is called with
2573 a format string that uses format specifiers that are allowed, and that
2574 arguments match the format string. This is the ``-Wformat`` warning, it is
2577 #. Clang checks that the format string argument is a literal string. This is
2578 the ``-Wformat-nonliteral`` warning, it is off by default.
2580 Clang implements this mostly the same way as GCC, but there is a difference
2581 for functions that accept a ``va_list`` argument (for example, ``vprintf``).
2582 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
2583 functions. Clang does not warn if the format string comes from a function
2584 parameter, where the function is annotated with a compatible attribute,
2585 otherwise it warns. For example:
2589 __attribute__((__format__ (__scanf__, 1, 3)))
2590 void foo(const char* s, char *buf, ...) {
2594 vprintf(s, ap); // warning: format string is not a string literal
2597 In this case we warn because ``s`` contains a format string for a
2598 ``scanf``-like function, but it is passed to a ``printf``-like function.
2600 If the attribute is removed, clang still warns, because the format string is
2601 not a string literal.
2607 __attribute__((__format__ (__printf__, 1, 3)))
2608 void foo(const char* s, char *buf, ...) {
2612 vprintf(s, ap); // warning
2615 In this case Clang does not warn because the format string ``s`` and
2616 the corresponding arguments are annotated. If the arguments are
2617 incorrect, the caller of ``foo`` will receive a warning.
2621 def AlignValueDocs : Documentation {
2622 let Category = DocCatType;
2624 The align_value attribute can be added to the typedef of a pointer type or the
2625 declaration of a variable of pointer or reference type. It specifies that the
2626 pointer will point to, or the reference will bind to, only objects with at
2627 least the provided alignment. This alignment value must be some positive power
2632 typedef double * aligned_double_ptr __attribute__((align_value(64)));
2633 void foo(double & x __attribute__((align_value(128)),
2634 aligned_double_ptr y) { ... }
2636 If the pointer value does not have the specified alignment at runtime, the
2637 behavior of the program is undefined.
2641 def FlagEnumDocs : Documentation {
2642 let Category = DocCatDecl;
2644 This attribute can be added to an enumerator to signal to the compiler that it
2645 is intended to be used as a flag type. This will cause the compiler to assume
2646 that the range of the type includes all of the values that you can get by
2647 manipulating bits of the enumerator when issuing warnings.
2651 def AsmLabelDocs : Documentation {
2652 let Category = DocCatDecl;
2654 This attribute can be used on a function or variable to specify its symbol name.
2656 On some targets, all C symbols are prefixed by default with a single character, typically ``_``. This was done historically to distinguish them from symbols used by other languages. (This prefix is also added to the standard Itanium C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true symbol name for a C++ variable declared as ``int cppvar;`` would be ``__Z6cppvar``; note the two underscores.) This prefix is *not* added to the symbol names specified by the ``asm`` attribute; programmers wishing to match a C symbol name must compensate for this.
2658 For example, consider the following C code:
2662 int var1 asm("altvar") = 1; // "altvar" in symbol table.
2663 int var2 = 1; // "_var2" in symbol table.
2665 void func1(void) asm("altfunc");
2666 void func1(void) {} // "altfunc" in symbol table.
2667 void func2(void) {} // "_func2" in symbol table.
2669 Clang's implementation of this attribute is compatible with GCC's, `documented here <https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html>`_.
2671 While it is possible to use this attribute to name a special symbol used internally by the compiler, such as an LLVM intrinsic, this is neither recommended nor supported and may cause the compiler to crash or miscompile. Users who wish to gain access to intrinsic behavior are strongly encouraged to request new builtin functions.
2675 def EnumExtensibilityDocs : Documentation {
2676 let Category = DocCatDecl;
2678 Attribute ``enum_extensibility`` is used to distinguish between enum definitions
2679 that are extensible and those that are not. The attribute can take either
2680 ``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the
2681 enum type takes a value that corresponds to one of the enumerators listed in the
2682 enum definition or, when the enum is annotated with ``flag_enum``, a value that
2683 can be constructed using values corresponding to the enumerators. ``open``
2684 indicates a variable of the enum type can take any values allowed by the
2685 standard and instructs clang to be more lenient when issuing warnings.
2689 enum __attribute__((enum_extensibility(closed))) ClosedEnum {
2693 enum __attribute__((enum_extensibility(open))) OpenEnum {
2697 enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
2698 C0 = 1 << 0, C1 = 1 << 1
2701 enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
2702 D0 = 1 << 0, D1 = 1 << 1
2708 enum ClosedFlagEnum cfe;
2709 enum OpenFlagEnum ofe;
2711 ce = A1; // no warnings
2712 ce = 100; // warning issued
2713 oe = B1; // no warnings
2714 oe = 100; // no warnings
2715 cfe = C0 | C1; // no warnings
2716 cfe = C0 | C1 | 4; // warning issued
2717 ofe = D0 | D1; // no warnings
2718 ofe = D0 | D1 | 4; // no warnings
2724 def EmptyBasesDocs : Documentation {
2725 let Category = DocCatDecl;
2727 The empty_bases attribute permits the compiler to utilize the
2728 empty-base-optimization more frequently.
2729 This attribute only applies to struct, class, and union types.
2730 It is only supported when using the Microsoft C++ ABI.
2734 def LayoutVersionDocs : Documentation {
2735 let Category = DocCatDecl;
2737 The layout_version attribute requests that the compiler utilize the class
2738 layout rules of a particular compiler version.
2739 This attribute only applies to struct, class, and union types.
2740 It is only supported when using the Microsoft C++ ABI.
2744 def LifetimeBoundDocs : Documentation {
2745 let Category = DocCatFunction;
2747 The ``lifetimebound`` attribute indicates that a resource owned by
2748 a function parameter or implicit object parameter
2749 is retained by the return value of the annotated function
2750 (or, for a parameter of a constructor, in the value of the constructed object).
2751 It is only supported in C++.
2753 This attribute provides an experimental implementation of the facility
2754 described in the C++ committee paper `P0936R0 <http://wg21.link/p0936r0>`_,
2755 and is subject to change as the design of the corresponding functionality
2760 def TrivialABIDocs : Documentation {
2761 let Category = DocCatDecl;
2763 The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union.
2764 It instructs the compiler to pass and return the type using the C ABI for the
2765 underlying type when the type would otherwise be considered non-trivial for the
2767 A class annotated with `trivial_abi` can have non-trivial destructors or copy/move constructors without automatically becoming non-trivial for the purposes of calls. For example:
2771 // A is trivial for the purposes of calls because `trivial_abi` makes the
2772 // user-provided special functions trivial.
2773 struct __attribute__((trivial_abi)) A {
2780 // B's destructor and copy/move constructor are considered trivial for the
2781 // purpose of calls because A is trivial.
2786 If a type is trivial for the purposes of calls, has a non-trivial destructor,
2787 and is passed as an argument by value, the convention is that the callee will
2788 destroy the object before returning.
2790 Attribute ``trivial_abi`` has no effect in the following cases:
2792 - The class directly declares a virtual base or virtual methods.
2793 - The class has a base class that is non-trivial for the purposes of calls.
2794 - The class has a non-static data member whose type is non-trivial for the purposes of calls, which includes:
2796 - classes that are non-trivial for the purposes of calls
2797 - __weak-qualified types in Objective-C++
2798 - arrays of any of the above
2802 def MSInheritanceDocs : Documentation {
2803 let Category = DocCatDecl;
2804 let Heading = "__single_inhertiance, __multiple_inheritance, __virtual_inheritance";
2806 This collection of keywords is enabled under ``-fms-extensions`` and controls
2807 the pointer-to-member representation used on ``*-*-win32`` targets.
2809 The ``*-*-win32`` targets utilize a pointer-to-member representation which
2810 varies in size and alignment depending on the definition of the underlying
2813 However, this is problematic when a forward declaration is only available and
2814 no definition has been made yet. In such cases, Clang is forced to utilize the
2815 most general representation that is available to it.
2817 These keywords make it possible to use a pointer-to-member representation other
2818 than the most general one regardless of whether or not the definition will ever
2819 be present in the current translation unit.
2821 This family of keywords belong between the ``class-key`` and ``class-name``:
2825 struct __single_inheritance S;
2829 This keyword can be applied to class templates but only has an effect when used
2830 on full specializations:
2834 template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
2835 template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
2836 template <> struct __single_inheritance A<int, float>;
2838 Note that choosing an inheritance model less general than strictly necessary is
2843 struct __multiple_inheritance S; // error: inheritance model does not match definition
2849 def MSNoVTableDocs : Documentation {
2850 let Category = DocCatDecl;
2852 This attribute can be added to a class declaration or definition to signal to
2853 the compiler that constructors and destructors will not reference the virtual
2854 function table. It is only supported when using the Microsoft C++ ABI.
2858 def OptnoneDocs : Documentation {
2859 let Category = DocCatFunction;
2861 The ``optnone`` attribute suppresses essentially all optimizations
2862 on a function or method, regardless of the optimization level applied to
2863 the compilation unit as a whole. This is particularly useful when you
2864 need to debug a particular function, but it is infeasible to build the
2865 entire application without optimization. Avoiding optimization on the
2866 specified function can improve the quality of the debugging information
2869 This attribute is incompatible with the ``always_inline`` and ``minsize``
2874 def LoopHintDocs : Documentation {
2875 let Category = DocCatStmt;
2876 let Heading = "#pragma clang loop";
2878 The ``#pragma clang loop`` directive allows loop optimization hints to be
2879 specified for the subsequent loop. The directive allows pipelining to be
2880 disabled, or vectorization, vector predication, interleaving, and unrolling to
2881 be enabled or disabled. Vector width, vector predication, interleave count,
2882 unrolling count, and the initiation interval for pipelining can be explicitly
2883 specified. See `language extensions
2884 <http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
2889 def UnrollHintDocs : Documentation {
2890 let Category = DocCatStmt;
2891 let Heading = "#pragma unroll, #pragma nounroll";
2893 Loop unrolling optimization hints can be specified with ``#pragma unroll`` and
2894 ``#pragma nounroll``. The pragma is placed immediately before a for, while,
2895 do-while, or c++11 range-based for loop.
2897 Specifying ``#pragma unroll`` without a parameter directs the loop unroller to
2898 attempt to fully unroll the loop if the trip count is known at compile time and
2899 attempt to partially unroll the loop if the trip count is not known at compile
2909 Specifying the optional parameter, ``#pragma unroll _value_``, directs the
2910 unroller to unroll the loop ``_value_`` times. The parameter may optionally be
2911 enclosed in parentheses:
2925 Specifying ``#pragma nounroll`` indicates that the loop should not be unrolled:
2934 ``#pragma unroll`` and ``#pragma unroll _value_`` have identical semantics to
2935 ``#pragma clang loop unroll(full)`` and
2936 ``#pragma clang loop unroll_count(_value_)`` respectively. ``#pragma nounroll``
2937 is equivalent to ``#pragma clang loop unroll(disable)``. See
2938 `language extensions
2939 <http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
2940 for further details including limitations of the unroll hints.
2944 def PipelineHintDocs : Documentation {
2945 let Category = DocCatStmt;
2946 let Heading = "#pragma clang loop pipeline, #pragma clang loop pipeline_initiation_interval";
2948 Software Pipelining optimization is a technique used to optimize loops by
2949 utilizing instruction-level parallelism. It reorders loop instructions to
2950 overlap iterations. As a result, the next iteration starts before the previous
2951 iteration has finished. The module scheduling technique creates a schedule for
2952 one iteration such that when repeating at regular intervals, no inter-iteration
2953 dependencies are violated. This constant interval(in cycles) between the start
2954 of iterations is called the initiation interval. i.e. The initiation interval
2955 is the number of cycles between two iterations of an unoptimized loop in the
2956 newly created schedule. A new, optimized loop is created such that a single iteration
2957 of the loop executes in the same number of cycles as the initiation interval.
2958 For further details see <https://llvm.org/pubs/2005-06-17-LattnerMSThesis-book.pdf>.
2960 ``#pragma clang loop pipeline and #pragma loop pipeline_initiation_interval``
2961 could be used as hints for the software pipelining optimization. The pragma is
2962 placed immediately before a for, while, do-while, or a C++11 range-based for
2965 Using ``#pragma clang loop pipeline(disable)`` avoids the software pipelining
2966 optimization. The disable state can only be specified:
2970 #pragma clang loop pipeline(disable)
2975 Using ``#pragma loop pipeline_initiation_interval`` instructs
2976 the software pipeliner to try the specified initiation interval.
2977 If a schedule was found then the resulting loop iteration would have
2978 the specified cycle count. If a schedule was not found then loop
2979 remains unchanged. The initiation interval must be a positive number
2984 #pragma loop pipeline_initiation_interval(10)
2992 def OpenCLUnrollHintDocs : Documentation {
2993 let Category = DocCatStmt;
2995 The opencl_unroll_hint attribute qualifier can be used to specify that a loop
2996 (for, while and do loops) can be unrolled. This attribute qualifier can be
2997 used to specify full unrolling or partial unrolling by a specified amount.
2998 This is a compiler hint and the compiler may ignore this directive. See
2999 `OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_
3000 s6.11.5 for details.
3004 def OpenCLIntelReqdSubGroupSizeDocs : Documentation {
3005 let Category = DocCatStmt;
3007 The optional attribute intel_reqd_sub_group_size can be used to indicate that
3008 the kernel must be compiled and executed with the specified subgroup size. When
3009 this attribute is present, get_max_sub_group_size() is guaranteed to return the
3010 specified integer value. This is important for the correctness of many subgroup
3011 algorithms, and in some cases may be used by the compiler to generate more optimal
3012 code. See `cl_intel_required_subgroup_size
3013 <https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>`
3018 def OpenCLAccessDocs : Documentation {
3019 let Category = DocCatStmt;
3020 let Heading = "__read_only, __write_only, __read_write (read_only, write_only, read_write)";
3022 The access qualifiers must be used with image object arguments or pipe arguments
3023 to declare if they are being read or written by a kernel or function.
3025 The read_only/__read_only, write_only/__write_only and read_write/__read_write
3026 names are reserved for use as access qualifiers and shall not be used otherwise.
3031 foo (read_only image2d_t imageA,
3032 write_only image2d_t imageB) {
3036 In the above example imageA is a read-only 2D image object, and imageB is a
3037 write-only 2D image object.
3039 The read_write (or __read_write) qualifier can not be used with pipe.
3041 More details can be found in the OpenCL C language Spec v2.0, Section 6.6.
3045 def DocOpenCLAddressSpaces : DocumentationCategory<"OpenCL Address Spaces"> {
3047 The address space qualifier may be used to specify the region of memory that is
3048 used to allocate the object. OpenCL supports the following address spaces:
3049 __generic(generic), __global(global), __local(local), __private(private),
3050 __constant(constant).
3054 __constant int c = ...;
3056 __generic int* foo(global int* g) {
3063 More details can be found in the OpenCL C language Spec v2.0, Section 6.5.
3067 def OpenCLAddressSpaceGenericDocs : Documentation {
3068 let Category = DocOpenCLAddressSpaces;
3069 let Heading = "__generic, generic, [[clang::opencl_generic]]";
3071 The generic address space attribute is only available with OpenCL v2.0 and later.
3072 It can be used with pointer types. Variables in global and local scope and
3073 function parameters in non-kernel functions can have the generic address space
3074 type attribute. It is intended to be a placeholder for any other address space
3075 except for '__constant' in OpenCL code which can be used with multiple address
3080 def OpenCLAddressSpaceConstantDocs : Documentation {
3081 let Category = DocOpenCLAddressSpaces;
3082 let Heading = "__constant, constant, [[clang::opencl_constant]]";
3084 The constant address space attribute signals that an object is located in
3085 a constant (non-modifiable) memory region. It is available to all work items.
3086 Any type can be annotated with the constant address space attribute. Objects
3087 with the constant address space qualifier can be declared in any scope and must
3088 have an initializer.
3092 def OpenCLAddressSpaceGlobalDocs : Documentation {
3093 let Category = DocOpenCLAddressSpaces;
3094 let Heading = "__global, global, [[clang::opencl_global]]";
3096 The global address space attribute specifies that an object is allocated in
3097 global memory, which is accessible by all work items. The content stored in this
3098 memory area persists between kernel executions. Pointer types to the global
3099 address space are allowed as function parameters or local variables. Starting
3100 with OpenCL v2.0, the global address space can be used with global (program
3101 scope) variables and static local variable as well.
3105 def OpenCLAddressSpaceLocalDocs : Documentation {
3106 let Category = DocOpenCLAddressSpaces;
3107 let Heading = "__local, local, [[clang::opencl_local]]";
3109 The local address space specifies that an object is allocated in the local (work
3110 group) memory area, which is accessible to all work items in the same work
3111 group. The content stored in this memory region is not accessible after
3112 the kernel execution ends. In a kernel function scope, any variable can be in
3113 the local address space. In other scopes, only pointer types to the local address
3114 space are allowed. Local address space variables cannot have an initializer.
3118 def OpenCLAddressSpacePrivateDocs : Documentation {
3119 let Category = DocOpenCLAddressSpaces;
3120 let Heading = "__private, private, [[clang::opencl_private]]";
3122 The private address space specifies that an object is allocated in the private
3123 (work item) memory. Other work items cannot access the same memory area and its
3124 content is destroyed after work item execution ends. Local variables can be
3125 declared in the private address space. Function arguments are always in the
3126 private address space. Kernel function arguments of a pointer or an array type
3127 cannot point to the private address space.
3131 def OpenCLNoSVMDocs : Documentation {
3132 let Category = DocCatVariable;
3134 OpenCL 2.0 supports the optional ``__attribute__((nosvm))`` qualifier for
3135 pointer variable. It informs the compiler that the pointer does not refer
3136 to a shared virtual memory region. See OpenCL v2.0 s6.7.2 for details.
3138 Since it is not widely used and has been removed from OpenCL 2.1, it is ignored
3143 def Ptr32Docs : Documentation {
3144 let Category = DocCatType;
3146 The ``__ptr32`` qualifier represents a native pointer on a 32-bit system. On a
3147 64-bit system, a pointer with ``__ptr32`` is extended to a 64-bit pointer. The
3148 ``__sptr`` and ``__uptr`` qualifiers can be used to specify whether the pointer
3149 is sign extended or zero extended. This qualifier is enabled under
3150 ``-fms-extensions``.
3154 def Ptr64Docs : Documentation {
3155 let Category = DocCatType;
3157 The ``__ptr64`` qualifier represents a native pointer on a 64-bit system. On a
3158 32-bit system, a ``__ptr64`` pointer is truncated to a 32-bit pointer. This
3159 qualifier is enabled under ``-fms-extensions``.
3163 def SPtrDocs : Documentation {
3164 let Category = DocCatType;
3166 The ``__sptr`` qualifier specifies that a 32-bit pointer should be sign
3167 extended when converted to a 64-bit pointer.
3171 def UPtrDocs : Documentation {
3172 let Category = DocCatType;
3174 The ``__uptr`` qualifier specifies that a 32-bit pointer should be zero
3175 extended when converted to a 64-bit pointer.
3180 def NullabilityDocs : DocumentationCategory<"Nullability Attributes"> {
3182 Whether a particular pointer may be "null" is an important concern when working with pointers in the C family of languages. The various nullability attributes indicate whether a particular pointer can be null or not, which makes APIs more expressive and can help static analysis tools identify bugs involving null pointers. Clang supports several kinds of nullability attributes: the ``nonnull`` and ``returns_nonnull`` attributes indicate which function or method parameters and result types can never be null, while nullability type qualifiers indicate which pointer types can be null (``_Nullable``) or cannot be null (``_Nonnull``).
3184 The nullability (type) qualifiers express whether a value of a given pointer type can be null (the ``_Nullable`` qualifier), doesn't have a defined meaning for null (the ``_Nonnull`` qualifier), or for which the purpose of null is unclear (the ``_Null_unspecified`` qualifier). Because nullability qualifiers are expressed within the type system, they are more general than the ``nonnull`` and ``returns_nonnull`` attributes, allowing one to express (for example) a nullable pointer to an array of nonnull pointers. Nullability qualifiers are written to the right of the pointer to which they apply. For example:
3188 // No meaningful result when 'ptr' is null (here, it happens to be undefined behavior).
3189 int fetch(int * _Nonnull ptr) { return *ptr; }
3191 // 'ptr' may be null.
3192 int fetch_or_zero(int * _Nullable ptr) {
3193 return ptr ? *ptr : 0;
3196 // A nullable pointer to non-null pointers to const characters.
3197 const char *join_strings(const char * _Nonnull * _Nullable strings, unsigned n);
3199 In Objective-C, there is an alternate spelling for the nullability qualifiers that can be used in Objective-C methods and properties using context-sensitive, non-underscored keywords. For example:
3201 .. code-block:: objective-c
3203 @interface NSView : NSResponder
3204 - (nullable NSView *)ancestorSharedWithView:(nonnull NSView *)aView;
3205 @property (assign, nullable) NSView *superview;
3206 @property (readonly, nonnull) NSArray *subviews;
3211 def TypeNonNullDocs : Documentation {
3212 let Category = NullabilityDocs;
3214 The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful value for a value of the ``_Nonnull`` pointer type. For example, given a declaration such as:
3218 int fetch(int * _Nonnull ptr);
3220 a caller of ``fetch`` should not provide a null value, and the compiler will produce a warning if it sees a literal null value passed to ``fetch``. Note that, unlike the declaration attribute ``nonnull``, the presence of ``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch`` is free to consider null undefined behavior or (perhaps for backward-compatibility reasons) defensively handle null.
3224 def TypeNullableDocs : Documentation {
3225 let Category = NullabilityDocs;
3227 The ``_Nullable`` nullability qualifier indicates that a value of the ``_Nullable`` pointer type can be null. For example, given:
3231 int fetch_or_zero(int * _Nullable ptr);
3233 a caller of ``fetch_or_zero`` can provide null.
3237 def TypeNullUnspecifiedDocs : Documentation {
3238 let Category = NullabilityDocs;
3240 The ``_Null_unspecified`` nullability qualifier indicates that neither the ``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer type. It is used primarily to indicate that the role of null with specific pointers in a nullability-annotated header is unclear, e.g., due to overly-complex implementations or historical factors with a long-lived API.
3244 def NonNullDocs : Documentation {
3245 let Category = NullabilityDocs;
3247 The ``nonnull`` attribute indicates that some function parameters must not be null, and can be used in several different ways. It's original usage (`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_) is as a function (or Objective-C method) attribute that specifies which parameters of the function are nonnull in a comma-separated list. For example:
3251 extern void * my_memcpy (void *dest, const void *src, size_t len)
3252 __attribute__((nonnull (1, 2)));
3254 Here, the ``nonnull`` attribute indicates that parameters 1 and 2
3255 cannot have a null value. Omitting the parenthesized list of parameter indices means that all parameters of pointer type cannot be null:
3259 extern void * my_memcpy (void *dest, const void *src, size_t len)
3260 __attribute__((nonnull));
3262 Clang also allows the ``nonnull`` attribute to be placed directly on a function (or Objective-C method) parameter, eliminating the need to specify the parameter index ahead of type. For example:
3266 extern void * my_memcpy (void *dest __attribute__((nonnull)),
3267 const void *src __attribute__((nonnull)), size_t len);
3269 Note that the ``nonnull`` attribute indicates that passing null to a non-null parameter is undefined behavior, which the optimizer may take advantage of to, e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a pointer cannot be null in a more general manner (because it is part of the type system) and does not imply undefined behavior, making it more widely applicable.
3273 def ReturnsNonNullDocs : Documentation {
3274 let Category = NullabilityDocs;
3276 The ``returns_nonnull`` attribute indicates that a particular function (or Objective-C method) always returns a non-null pointer. For example, a particular system ``malloc`` might be defined to terminate a process when memory is not available rather than returning a null pointer:
3280 extern void * malloc (size_t size) __attribute__((returns_nonnull));
3282 The ``returns_nonnull`` attribute implies that returning a null pointer is undefined behavior, which the optimizer may take advantage of. The ``_Nonnull`` type qualifier indicates that a pointer cannot be null in a more general manner (because it is part of the type system) and does not imply undefined behavior, making it more widely applicable
3286 def NoAliasDocs : Documentation {
3287 let Category = DocCatFunction;
3289 The ``noalias`` attribute indicates that the only memory accesses inside
3290 function are loads and stores from objects pointed to by its pointer-typed
3291 arguments, with arbitrary offsets.
3295 def OMPDeclareSimdDocs : Documentation {
3296 let Category = DocCatFunction;
3297 let Heading = "#pragma omp declare simd";
3299 The `declare simd` construct can be applied to a function to enable the creation
3300 of one or more versions that can process multiple arguments using SIMD
3301 instructions from a single invocation in a SIMD loop. The `declare simd`
3302 directive is a declarative directive. There may be multiple `declare simd`
3303 directives for a function. The use of a `declare simd` construct on a function
3304 enables the creation of SIMD versions of the associated function that can be
3305 used to process multiple arguments from a single invocation from a SIMD loop
3307 The syntax of the `declare simd` construct is as follows:
3309 .. code-block:: none
3311 #pragma omp declare simd [clause[[,] clause] ...] new-line
3312 [#pragma omp declare simd [clause[[,] clause] ...] new-line]
3314 function definition or declaration
3316 where clause is one of the following:
3318 .. code-block:: none
3321 linear(argument-list[:constant-linear-step])
3322 aligned(argument-list[:alignment])
3323 uniform(argument-list)
3330 def OMPDeclareTargetDocs : Documentation {
3331 let Category = DocCatFunction;
3332 let Heading = "#pragma omp declare target";
3334 The `declare target` directive specifies that variables and functions are mapped
3335 to a device for OpenMP offload mechanism.
3337 The syntax of the declare target directive is as follows:
3341 #pragma omp declare target new-line
3342 declarations-definition-seq
3343 #pragma omp end declare target new-line
3349 #pragma omp declare target (extended-list) new-line
3355 #pragma omp declare target clause[ [,] clause ... ] new-line
3357 where clause is one of the following:
3364 device_type(host | nohost | any)
3368 def OMPDeclareVariantDocs : Documentation {
3369 let Category = DocCatFunction;
3370 let Heading = "#pragma omp declare variant";
3372 The `declare variant` directive declares a specialized variant of a base
3373 function and specifies the context in which that specialized variant is used.
3374 The declare variant directive is a declarative directive.
3375 The syntax of the `declare variant` construct is as follows:
3377 .. code-block:: none
3379 #pragma omp declare variant(variant-func-id) clause new-line
3380 [#pragma omp declare variant(variant-func-id) clause new-line]
3382 function definition or declaration
3384 where clause is one of the following:
3386 .. code-block:: none
3388 match(context-selector-specification)
3390 and where `variant-func-id` is the name of a function variant that is either a
3391 base language identifier or, for C++, a template-id.
3396 def NoStackProtectorDocs : Documentation {
3397 let Category = DocCatFunction;
3399 Clang supports the ``__attribute__((no_stack_protector))`` attribute which disables
3400 the stack protector on the specified function. This attribute is useful for
3401 selectively disabling the stack protector on some functions when building with
3402 ``-fstack-protector`` compiler option.
3404 For example, it disables the stack protector for the function ``foo`` but function
3405 ``bar`` will still be built with the stack protector with the ``-fstack-protector``
3410 int __attribute__((no_stack_protector))
3411 foo (int x); // stack protection will be disabled for foo.
3413 int bar(int y); // bar can be built with the stack protector.
3418 def NotTailCalledDocs : Documentation {
3419 let Category = DocCatFunction;
3421 The ``not_tail_called`` attribute prevents tail-call optimization on statically bound calls. It has no effect on indirect calls. Virtual functions, objective-c methods, and functions marked as ``always_inline`` cannot be marked as ``not_tail_called``.
3423 For example, it prevents tail-call optimization in the following case:
3427 int __attribute__((not_tail_called)) foo1(int);
3430 return foo1(a); // No tail-call optimization on direct calls.
3433 However, it doesn't prevent tail-call optimization in this case:
3437 int __attribute__((not_tail_called)) foo1(int);
3440 int (*fn)(int) = &foo1;
3442 // not_tail_called has no effect on an indirect call even if the call can be
3443 // resolved at compile time.
3447 Marking virtual functions as ``not_tail_called`` is an error:
3453 // not_tail_called on a virtual function is an error.
3454 [[clang::not_tail_called]] virtual int foo1();
3458 // Non-virtual functions can be marked ``not_tail_called``.
3459 [[clang::not_tail_called]] int foo3();
3462 class Derived1 : public Base {
3464 int foo1() override;
3466 // not_tail_called on a virtual function is an error.
3467 [[clang::not_tail_called]] int foo2() override;
3472 def NoThrowDocs : Documentation {
3473 let Category = DocCatFunction;
3475 Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style
3476 ``__declspec(nothrow)`` attribute as an equivalent of `noexcept` on function
3477 declarations. This attribute informs the compiler that the annotated function
3478 does not throw an exception. This prevents exception-unwinding. This attribute
3479 is particularly useful on functions in the C Standard Library that are
3480 guaranteed to not throw an exception.
3484 def InternalLinkageDocs : Documentation {
3485 let Category = DocCatFunction;
3487 The ``internal_linkage`` attribute changes the linkage type of the declaration to internal.
3488 This is similar to C-style ``static``, but can be used on classes and class methods. When applied to a class definition,
3489 this attribute affects all methods and static data members of that class.
3490 This can be used to contain the ABI of a C++ library by excluding unwanted class methods from the export tables.
3494 def ExcludeFromExplicitInstantiationDocs : Documentation {
3495 let Category = DocCatFunction;
3497 The ``exclude_from_explicit_instantiation`` attribute opts-out a member of a
3498 class template from being part of explicit template instantiations of that
3499 class template. This means that an explicit instantiation will not instantiate
3500 members of the class template marked with the attribute, but also that code
3501 where an extern template declaration of the enclosing class template is visible
3502 will not take for granted that an external instantiation of the class template
3503 would provide those members (which would otherwise be a link error, since the
3504 explicit instantiation won't provide those members). For example, let's say we
3505 don't want the ``data()`` method to be part of libc++'s ABI. To make sure it
3506 is not exported from the dylib, we give it hidden visibility:
3511 template <class CharT>
3512 class basic_string {
3514 __attribute__((__visibility__("hidden")))
3515 const value_type* data() const noexcept { ... }
3518 template class basic_string<char>;
3520 Since an explicit template instantiation declaration for ``basic_string<char>``
3521 is provided, the compiler is free to assume that ``basic_string<char>::data()``
3522 will be provided by another translation unit, and it is free to produce an
3523 external call to this function. However, since ``data()`` has hidden visibility
3524 and the explicit template instantiation is provided in a shared library (as
3525 opposed to simply another translation unit), ``basic_string<char>::data()``
3526 won't be found and a link error will ensue. This happens because the compiler
3527 assumes that ``basic_string<char>::data()`` is part of the explicit template
3528 instantiation declaration, when it really isn't. To tell the compiler that
3529 ``data()`` is not part of the explicit template instantiation declaration, the
3530 ``exclude_from_explicit_instantiation`` attribute can be used:
3535 template <class CharT>
3536 class basic_string {
3538 __attribute__((__visibility__("hidden")))
3539 __attribute__((exclude_from_explicit_instantiation))
3540 const value_type* data() const noexcept { ... }
3543 template class basic_string<char>;
3545 Now, the compiler won't assume that ``basic_string<char>::data()`` is provided
3546 externally despite there being an explicit template instantiation declaration:
3547 the compiler will implicitly instantiate ``basic_string<char>::data()`` in the
3548 TUs where it is used.
3550 This attribute can be used on static and non-static member functions of class
3551 templates, static data members of class templates and member classes of class
3556 def DisableTailCallsDocs : Documentation {
3557 let Category = DocCatFunction;
3559 The ``disable_tail_calls`` attribute instructs the backend to not perform tail call optimization inside the marked function.
3567 int foo(int a) __attribute__((disable_tail_calls)) {
3568 return callee(a); // This call is not tail-call optimized.
3571 Marking virtual functions as ``disable_tail_calls`` is legal.
3579 [[clang::disable_tail_calls]] virtual int foo1() {
3580 return callee(); // This call is not tail-call optimized.
3584 class Derived1 : public Base {
3586 int foo1() override {
3587 return callee(); // This call is tail-call optimized.
3594 def AnyX86NoCallerSavedRegistersDocs : Documentation {
3595 let Category = DocCatFunction;
3597 Use this attribute to indicate that the specified function has no
3598 caller-saved registers. That is, all registers are callee-saved except for
3599 registers used for passing parameters to the function or returning parameters
3601 The compiler saves and restores any modified registers that were not used for
3602 passing or returning arguments to the function.
3604 The user can call functions specified with the 'no_caller_saved_registers'
3605 attribute from an interrupt handler without saving and restoring all
3606 call-clobbered registers.
3608 Note that 'no_caller_saved_registers' attribute is not a calling convention.
3609 In fact, it only overrides the decision of which registers should be saved by
3610 the caller, but not how the parameters are passed from the caller to the callee.
3616 __attribute__ ((no_caller_saved_registers, fastcall))
3617 void f (int arg1, int arg2) {
3621 In this case parameters 'arg1' and 'arg2' will be passed in registers.
3622 In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as
3623 register parameters. However, it will not assume any scratch registers and
3624 should save and restore any modified registers except for ECX and EDX.
3628 def X86ForceAlignArgPointerDocs : Documentation {
3629 let Category = DocCatFunction;
3631 Use this attribute to force stack alignment.
3633 Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
3634 (like 'movaps') that work with the stack require operands to be 16-byte aligned.
3635 This attribute realigns the stack in the function prologue to make sure the
3636 stack can be used with SSE instructions.
3638 Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
3639 Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
3640 rare cases where the caller does not align the stack properly (e.g. flow
3641 jumps from i386 arch code).
3645 __attribute__ ((force_align_arg_pointer))
3653 def AnyX86NoCfCheckDocs : Documentation {
3654 let Category = DocCatFunction;
3656 Jump Oriented Programming attacks rely on tampering with addresses used by
3657 indirect call / jmp, e.g. redirect control-flow to non-programmer
3658 intended bytes in the binary.
3659 X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
3660 Enforcement Technology (CET). IBT instruments ENDBR instructions used to
3661 specify valid targets of indirect call / jmp.
3662 The ``nocf_check`` attribute has two roles:
3663 1. Appertains to a function - do not add ENDBR instruction at the beginning of
3665 2. Appertains to a function pointer - do not track the target function of this
3666 pointer (by adding nocf_check prefix to the indirect-call instruction).
3670 def SwiftCallDocs : Documentation {
3671 let Category = DocCatVariable;
3673 The ``swiftcall`` attribute indicates that a function should be called
3674 using the Swift calling convention for a function or function pointer.
3676 The lowering for the Swift calling convention, as described by the Swift
3677 ABI documentation, occurs in multiple phases. The first, "high-level"
3678 phase breaks down the formal parameters and results into innately direct
3679 and indirect components, adds implicit paraameters for the generic
3680 signature, and assigns the context and error ABI treatments to parameters
3681 where applicable. The second phase breaks down the direct parameters
3682 and results from the first phase and assigns them to registers or the
3683 stack. The ``swiftcall`` convention only handles this second phase of
3684 lowering; the C function type must accurately reflect the results
3685 of the first phase, as follows:
3687 - Results classified as indirect by high-level lowering should be
3688 represented as parameters with the ``swift_indirect_result`` attribute.
3690 - Results classified as direct by high-level lowering should be represented
3693 - First, remove any empty direct results.
3695 - If there are no direct results, the C result type should be ``void``.
3697 - If there is one direct result, the C result type should be a type with
3698 the exact layout of that result type.
3700 - If there are a multiple direct results, the C result type should be
3701 a struct type with the exact layout of a tuple of those results.
3703 - Parameters classified as indirect by high-level lowering should be
3704 represented as parameters of pointer type.
3706 - Parameters classified as direct by high-level lowering should be
3707 omitted if they are empty types; otherwise, they should be represented
3708 as a parameter type with a layout exactly matching the layout of the
3709 Swift parameter type.
3711 - The context parameter, if present, should be represented as a trailing
3712 parameter with the ``swift_context`` attribute.
3714 - The error result parameter, if present, should be represented as a
3715 trailing parameter (always following a context parameter) with the
3716 ``swift_error_result`` attribute.
3718 ``swiftcall`` does not support variadic arguments or unprototyped functions.
3720 The parameter ABI treatment attributes are aspects of the function type.
3721 A function type which which applies an ABI treatment attribute to a
3722 parameter is a different type from an otherwise-identical function type
3723 that does not. A single parameter may not have multiple ABI treatment
3726 Support for this feature is target-dependent, although it should be
3727 supported on every target that Swift supports. Query for this support
3728 with ``__has_attribute(swiftcall)``. This implies support for the
3729 ``swift_context``, ``swift_error_result``, and ``swift_indirect_result``
3734 def SwiftContextDocs : Documentation {
3735 let Category = DocCatVariable;
3737 The ``swift_context`` attribute marks a parameter of a ``swiftcall``
3738 function as having the special context-parameter ABI treatment.
3740 This treatment generally passes the context value in a special register
3741 which is normally callee-preserved.
3743 A ``swift_context`` parameter must either be the last parameter or must be
3744 followed by a ``swift_error_result`` parameter (which itself must always be
3745 the last parameter).
3747 A context parameter must have pointer or reference type.
3751 def SwiftErrorResultDocs : Documentation {
3752 let Category = DocCatVariable;
3754 The ``swift_error_result`` attribute marks a parameter of a ``swiftcall``
3755 function as having the special error-result ABI treatment.
3757 This treatment generally passes the underlying error value in and out of
3758 the function through a special register which is normally callee-preserved.
3759 This is modeled in C by pretending that the register is addressable memory:
3761 - The caller appears to pass the address of a variable of pointer type.
3762 The current value of this variable is copied into the register before
3763 the call; if the call returns normally, the value is copied back into the
3766 - The callee appears to receive the address of a variable. This address
3767 is actually a hidden location in its own stack, initialized with the
3768 value of the register upon entry. When the function returns normally,
3769 the value in that hidden location is written back to the register.
3771 A ``swift_error_result`` parameter must be the last parameter, and it must be
3772 preceded by a ``swift_context`` parameter.
3774 A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some
3775 type T. Note that no qualifiers are permitted on the intermediate level.
3777 It is undefined behavior if the caller does not pass a pointer or
3778 reference to a valid object.
3780 The standard convention is that the error value itself (that is, the
3781 value stored in the apparent argument) will be null upon function entry,
3782 but this is not enforced by the ABI.
3786 def SwiftIndirectResultDocs : Documentation {
3787 let Category = DocCatVariable;
3789 The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall``
3790 function as having the special indirect-result ABI treatment.
3792 This treatment gives the parameter the target's normal indirect-result
3793 ABI treatment, which may involve passing it differently from an ordinary
3794 parameter. However, only the first indirect result will receive this
3795 treatment. Furthermore, low-level lowering may decide that a direct result
3796 must be returned indirectly; if so, this will take priority over the
3797 ``swift_indirect_result`` parameters.
3799 A ``swift_indirect_result`` parameter must either be the first parameter or
3800 follow another ``swift_indirect_result`` parameter.
3802 A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for
3803 some object type ``T``. If ``T`` is a complete type at the point of
3804 definition of a function, it is undefined behavior if the argument
3805 value does not point to storage of adequate size and alignment for a
3806 value of type ``T``.
3808 Making indirect results explicit in the signature allows C functions to
3809 directly construct objects into them without relying on language
3810 optimizations like C++'s named return value optimization (NRVO).
3814 def SuppressDocs : Documentation {
3815 let Category = DocCatStmt;
3817 The ``[[gsl::suppress]]`` attribute suppresses specific
3818 clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable
3819 way. The attribute can be attached to declarations, statements, and at
3824 [[gsl::suppress("Rh-public")]]
3827 [[gsl::suppress("type")]] {
3828 p = reinterpret_cast<int*>(7);
3832 [[clang::suppress("type", "bounds")]];
3836 .. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement
3840 def AbiTagsDocs : Documentation {
3841 let Category = DocCatFunction;
3843 The ``abi_tag`` attribute can be applied to a function, variable, class or
3844 inline namespace declaration to modify the mangled name of the entity. It gives
3845 the ability to distinguish between different versions of the same entity but
3846 with different ABI versions supported. For example, a newer version of a class
3847 could have a different set of data members and thus have a different size. Using
3848 the ``abi_tag`` attribute, it is possible to have different mangled names for
3849 a global variable of the class type. Therefore, the old code could keep using
3850 the old manged name and the new code will use the new mangled name with tags.
3854 def PreserveMostDocs : Documentation {
3855 let Category = DocCatCallingConvs;
3857 On X86-64 and AArch64 targets, this attribute changes the calling convention of
3858 a function. The ``preserve_most`` calling convention attempts to make the code
3859 in the caller as unintrusive as possible. This convention behaves identically
3860 to the ``C`` calling convention on how arguments and return values are passed,
3861 but it uses a different set of caller/callee-saved registers. This alleviates
3862 the burden of saving and recovering a large register set before and after the
3863 call in the caller. If the arguments are passed in callee-saved registers,
3864 then they will be preserved by the callee across the call. This doesn't
3865 apply for values returned in callee-saved registers.
3867 - On X86-64 the callee preserves all general purpose registers, except for
3868 R11. R11 can be used as a scratch register. Floating-point registers
3869 (XMMs/YMMs) are not preserved and need to be saved by the caller.
3871 The idea behind this convention is to support calls to runtime functions
3872 that have a hot path and a cold path. The hot path is usually a small piece
3873 of code that doesn't use many registers. The cold path might need to call out to
3874 another function and therefore only needs to preserve the caller-saved
3875 registers, which haven't already been saved by the caller. The
3876 `preserve_most` calling convention is very similar to the ``cold`` calling
3877 convention in terms of caller/callee-saved registers, but they are used for
3878 different types of function calls. ``coldcc`` is for function calls that are
3879 rarely executed, whereas `preserve_most` function calls are intended to be
3880 on the hot path and definitely executed a lot. Furthermore ``preserve_most``
3881 doesn't prevent the inliner from inlining the function call.
3883 This calling convention will be used by a future version of the Objective-C
3884 runtime and should therefore still be considered experimental at this time.
3885 Although this convention was created to optimize certain runtime calls to
3886 the Objective-C runtime, it is not limited to this runtime and might be used
3887 by other runtimes in the future too. The current implementation only
3888 supports X86-64 and AArch64, but the intention is to support more architectures
3893 def PreserveAllDocs : Documentation {
3894 let Category = DocCatCallingConvs;
3896 On X86-64 and AArch64 targets, this attribute changes the calling convention of
3897 a function. The ``preserve_all`` calling convention attempts to make the code
3898 in the caller even less intrusive than the ``preserve_most`` calling convention.
3899 This calling convention also behaves identical to the ``C`` calling convention
3900 on how arguments and return values are passed, but it uses a different set of
3901 caller/callee-saved registers. This removes the burden of saving and
3902 recovering a large register set before and after the call in the caller. If
3903 the arguments are passed in callee-saved registers, then they will be
3904 preserved by the callee across the call. This doesn't apply for values
3905 returned in callee-saved registers.
3907 - On X86-64 the callee preserves all general purpose registers, except for
3908 R11. R11 can be used as a scratch register. Furthermore it also preserves
3909 all floating-point registers (XMMs/YMMs).
3911 The idea behind this convention is to support calls to runtime functions
3912 that don't need to call out to any other functions.
3914 This calling convention, like the ``preserve_most`` calling convention, will be
3915 used by a future version of the Objective-C runtime and should be considered
3916 experimental at this time.
3920 def DeprecatedDocs : Documentation {
3921 let Category = DocCatDecl;
3923 The ``deprecated`` attribute can be applied to a function, a variable, or a
3924 type. This is useful when identifying functions, variables, or types that are
3925 expected to be removed in a future version of a program.
3927 Consider the function declaration for a hypothetical function ``f``:
3931 void f(void) __attribute__((deprecated("message", "replacement")));
3933 When spelled as `__attribute__((deprecated))`, the deprecated attribute can have
3934 two optional string arguments. The first one is the message to display when
3935 emitting the warning; the second one enables the compiler to provide a Fix-It
3936 to replace the deprecated name with a new name. Otherwise, when spelled as
3937 `[[gnu::deprecated]] or [[deprecated]]`, the attribute can have one optional
3938 string argument which is the message to display when emitting the warning.
3942 def IFuncDocs : Documentation {
3943 let Category = DocCatFunction;
3945 ``__attribute__((ifunc("resolver")))`` is used to mark that the address of a declaration should be resolved at runtime by calling a resolver function.
3947 The symbol name of the resolver function is given in quotes. A function with this name (after mangling) must be defined in the current translation unit; it may be ``static``. The resolver function should return a pointer.
3949 The ``ifunc`` attribute may only be used on a function declaration. A function declaration with an ``ifunc`` attribute is considered to be a definition of the declared entity. The entity must not have weak linkage; for example, in C++, it cannot be applied to a declaration if a definition at that location would be considered inline.
3951 Not all targets support this attribute. ELF target support depends on both the linker and runtime linker, and is available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc v2.11.1 and later, and FreeBSD 9.1 and later. Non-ELF targets currently do not support this attribute.
3955 def LTOVisibilityDocs : Documentation {
3956 let Category = DocCatDecl;
3958 See :doc:`LTOVisibility`.
3962 def RenderScriptKernelAttributeDocs : Documentation {
3963 let Category = DocCatFunction;
3965 ``__attribute__((kernel))`` is used to mark a ``kernel`` function in
3968 In RenderScript, ``kernel`` functions are used to express data-parallel
3969 computations. The RenderScript runtime efficiently parallelizes ``kernel``
3970 functions to run on computational resources such as multi-core CPUs and GPUs.
3971 See the RenderScript_ documentation for more information.
3973 .. _RenderScript: https://developer.android.com/guide/topics/renderscript/compute.html
3977 def XRayDocs : Documentation {
3978 let Category = DocCatFunction;
3979 let Heading = "xray_always_instrument, xray_never_instrument, xray_log_args";
3981 ``__attribute__((xray_always_instrument))`` or ``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++), methods (in Objective C), and free functions (in C, C++, and Objective C) to be instrumented with XRay. This will cause the function to always have space at the beginning and exit points to allow for runtime patching.
3983 Conversely, ``__attribute__((xray_never_instrument))`` or ``[[clang::xray_never_instrument]]`` will inhibit the insertion of these instrumentation points.
3985 If a function has neither of these attributes, they become subject to the XRay heuristics used to determine whether a function should be instrumented or otherwise.
3987 ``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is used to preserve N function arguments for the logging function. Currently, only N==1 is supported.
3991 def PatchableFunctionEntryDocs : Documentation {
3992 let Category = DocCatFunction;
3994 ``__attribute__((patchable_function_entry(N,M)))`` is used to generate M NOPs
3995 before the function entry and N-M NOPs after the function entry. This attribute
3996 takes precedence over the command line option ``-fpatchable-function-entry=N,M``.
3997 ``M`` defaults to 0 if omitted.
4001 def TransparentUnionDocs : Documentation {
4002 let Category = DocCatDecl;
4004 This attribute can be applied to a union to change the behaviour of calls to
4005 functions that have an argument with a transparent union type. The compiler
4006 behaviour is changed in the following manner:
4008 - A value whose type is any member of the transparent union can be passed as an
4009 argument without the need to cast that value.
4011 - The argument is passed to the function using the calling convention of the
4012 first member of the transparent union. Consequently, all the members of the
4013 transparent union should have the same calling convention as its first member.
4015 Transparent unions are not supported in C++.
4019 def ObjCSubclassingRestrictedDocs : Documentation {
4020 let Category = DocCatDecl;
4022 This attribute can be added to an Objective-C ``@interface`` declaration to
4023 ensure that this class cannot be subclassed.
4027 def ObjCNonLazyClassDocs : Documentation {
4028 let Category = DocCatDecl;
4030 This attribute can be added to an Objective-C ``@interface`` or
4031 ``@implementation`` declaration to add the class to the list of non-lazily
4032 initialized classes. A non-lazy class will be initialized eagerly when the
4033 Objective-C runtime is loaded. This is required for certain system classes which
4034 have instances allocated in non-standard ways, such as the classes for blocks
4035 and constant strings. Adding this attribute is essentially equivalent to
4036 providing a trivial `+load` method but avoids the (fairly small) load-time
4037 overheads associated with defining and calling such a method.
4041 def ObjCDirectDocs : Documentation {
4042 let Category = DocCatDecl;
4044 The ``objc_direct`` attribute can be used to mark an Objective-C method as
4045 being *direct*. A direct method is treated statically like an ordinary method,
4046 but dynamically it behaves more like a C function. This lowers some of the costs
4047 associated with the method but also sacrifices some of the ordinary capabilities
4048 of Objective-C methods.
4050 A message send of a direct method calls the implementation directly, as if it
4051 were a C function, rather than using ordinary Objective-C method dispatch. This
4052 is substantially faster and potentially allows the implementation to be inlined,
4053 but it also means the method cannot be overridden in subclasses or replaced
4054 dynamically, as ordinary Objective-C methods can.
4056 Furthermore, a direct method is not listed in the class's method lists. This
4057 substantially reduces the code-size overhead of the method but also means it
4058 cannot be called dynamically using ordinary Objective-C method dispatch at all;
4059 in particular, this means that it cannot override a superclass method or satisfy
4060 a protocol requirement.
4062 Because a direct method cannot be overridden, it is an error to perform
4063 a ``super`` message send of one.
4065 Although a message send of a direct method causes the method to be called
4066 directly as if it were a C function, it still obeys Objective-C semantics in other
4069 - If the receiver is ``nil``, the message send does nothing and returns the zero value
4070 for the return type.
4072 - A message send of a direct class method will cause the class to be initialized,
4073 including calling the ``+initialize`` method if present.
4075 - The implicit ``_cmd`` parameter containing the method's selector is still defined.
4076 In order to minimize code-size costs, the implementation will not emit a reference
4077 to the selector if the parameter is unused within the method.
4079 Symbols for direct method implementations are implicitly given hidden
4080 visibility, meaning that they can only be called within the same linkage unit.
4082 It is an error to do any of the following:
4084 - declare a direct method in a protocol,
4085 - declare an override of a direct method with a method in a subclass,
4086 - declare an override of a non-direct method with a direct method in a subclass,
4087 - declare a method with different directness in different class interfaces, or
4088 - implement a non-direct method (as declared in any class interface) with a direct method.
4090 If any of these rules would be violated if every method defined in an
4091 ``@implementation`` within a single linkage unit were declared in an
4092 appropriate class interface, the program is ill-formed with no diagnostic
4093 required. If a violation of this rule is not diagnosed, behavior remains
4094 well-defined; this paragraph is simply reserving the right to diagnose such
4095 conflicts in the future, not to treat them as undefined behavior.
4097 Additionally, Clang will warn about any ``@selector`` expression that
4098 names a selector that is only known to be used for direct methods.
4100 For the purpose of these rules, a "class interface" includes a class's primary
4101 ``@interface`` block, its class extensions, its categories, its declared protocols,
4102 and all the class interfaces of its superclasses.
4104 An Objective-C property can be declared with the ``direct`` property
4105 attribute. If a direct property declaration causes an implicit declaration of
4106 a getter or setter method (that is, if the given method is not explicitly
4107 declared elsewhere), the method is declared to be direct.
4109 Some programmers may wish to make many methods direct at once. In order
4110 to simplify this, the ``objc_direct_members`` attribute is provided; see its
4111 documentation for more information.
4115 def ObjCDirectMembersDocs : Documentation {
4116 let Category = DocCatDecl;
4118 The ``objc_direct_members`` attribute can be placed on an Objective-C
4119 ``@interface`` or ``@implementation`` to mark that methods declared
4120 therein should be considered direct by default. See the documentation
4121 for ``objc_direct`` for more information about direct methods.
4123 When ``objc_direct_members`` is placed on an ``@interface`` block, every
4124 method in the block is considered to be declared as direct. This includes any
4125 implicit method declarations introduced by property declarations. If the method
4126 redeclares a non-direct method, the declaration is ill-formed, exactly as if the
4127 method was annotated with the ``objc_direct`` attribute. ``objc_direct_members``
4128 cannot be placed on the primary interface of a class, only on category or class
4129 extension interfaces.
4131 When ``objc_direct_members`` is placed on an ``@implementation`` block,
4132 methods defined in the block are considered to be declared as direct unless
4133 they have been previously declared as non-direct in any interface of the class.
4134 This includes the implicit method definitions introduced by synthesized
4135 properties, including auto-synthesized properties.
4139 def SelectAnyDocs : Documentation {
4140 let Category = DocCatDecl;
4142 This attribute appertains to a global symbol, causing it to have a weak
4144 `linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_
4145 ), allowing the linker to select any definition.
4147 For more information see
4148 `gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_
4149 or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_.
4152 def WebAssemblyExportNameDocs : Documentation {
4153 let Category = DocCatFunction;
4155 Clang supports the ``__attribute__((export_name(<name>)))``
4156 attribute for the WebAssembly target. This attribute may be attached to a
4157 function declaration, where it modifies how the symbol is to be exported
4158 from the linked WebAssembly.
4160 WebAssembly functions are exported via string name. By default when a symbol
4161 is exported, the export name for C/C++ symbols are the same as their C/C++
4162 symbol names. This attribute can be used to override the default behavior, and
4163 request a specific string name be used instead.
4167 def WebAssemblyImportModuleDocs : Documentation {
4168 let Category = DocCatFunction;
4170 Clang supports the ``__attribute__((import_module(<module_name>)))``
4171 attribute for the WebAssembly target. This attribute may be attached to a
4172 function declaration, where it modifies how the symbol is to be imported
4173 within the WebAssembly linking environment.
4175 WebAssembly imports use a two-level namespace scheme, consisting of a module
4176 name, which typically identifies a module from which to import, and a field
4177 name, which typically identifies a field from that module to import. By
4178 default, module names for C/C++ symbols are assigned automatically by the
4179 linker. This attribute can be used to override the default behavior, and
4180 request a specific module name be used instead.
4184 def WebAssemblyImportNameDocs : Documentation {
4185 let Category = DocCatFunction;
4187 Clang supports the ``__attribute__((import_name(<name>)))``
4188 attribute for the WebAssembly target. This attribute may be attached to a
4189 function declaration, where it modifies how the symbol is to be imported
4190 within the WebAssembly linking environment.
4192 WebAssembly imports use a two-level namespace scheme, consisting of a module
4193 name, which typically identifies a module from which to import, and a field
4194 name, which typically identifies a field from that module to import. By
4195 default, field names for C/C++ symbols are the same as their C/C++ symbol
4196 names. This attribute can be used to override the default behavior, and
4197 request a specific field name be used instead.
4201 def ArtificialDocs : Documentation {
4202 let Category = DocCatFunction;
4204 The ``artificial`` attribute can be applied to an inline function. If such a
4205 function is inlined, the attribute indicates that debuggers should associate
4206 the resulting instructions with the call site, rather than with the
4207 corresponding line within the inlined callee.
4211 def NoDerefDocs : Documentation {
4212 let Category = DocCatType;
4214 The ``noderef`` attribute causes clang to diagnose dereferences of annotated pointer types.
4215 This is ideally used with pointers that point to special memory which cannot be read
4216 from or written to, but allowing for the pointer to be used in pointer arithmetic.
4217 The following are examples of valid expressions where dereferences are diagnosed:
4221 int __attribute__((noderef)) *p;
4222 int x = *p; // warning
4224 int __attribute__((noderef)) **p2;
4225 x = **p2; // warning
4227 int * __attribute__((noderef)) *p3;
4233 struct S __attribute__((noderef)) *s;
4234 x = s->a; // warning
4235 x = (*s).a; // warning
4237 Not all dereferences may diagnose a warning if the value directed by the pointer may not be
4238 accessed. The following are examples of valid expressions where may not be diagnosed:
4243 int __attribute__((noderef)) *p;
4250 struct S __attribute__((noderef)) *s;
4254 ``noderef`` is currently only supported for pointers and arrays and not usable for
4255 references or Objective-C object pointers.
4260 int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type
4264 id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type
4268 def ReinitializesDocs : Documentation {
4269 let Category = DocCatFunction;
4271 The ``reinitializes`` attribute can be applied to a non-static, non-const C++
4272 member function to indicate that this member function reinitializes the entire
4273 object to a known state, independent of the previous state of the object.
4275 This attribute can be interpreted by static analyzers that warn about uses of an
4276 object that has been left in an indeterminate state by a move operation. If a
4277 member function marked with the ``reinitializes`` attribute is called on a
4278 moved-from object, the analyzer can conclude that the object is no longer in an
4279 indeterminate state.
4281 A typical example where this attribute would be used is on functions that clear
4290 [[clang::reinitializes]] void Clear();
4296 def AlwaysDestroyDocs : Documentation {
4297 let Category = DocCatVariable;
4299 The ``always_destroy`` attribute specifies that a variable with static or thread
4300 storage duration should have its exit-time destructor run. This attribute is the
4301 default unless clang was invoked with -fno-c++-static-destructors.
4305 def NoDestroyDocs : Documentation {
4306 let Category = DocCatVariable;
4308 The ``no_destroy`` attribute specifies that a variable with static or thread
4309 storage duration shouldn't have its exit-time destructor run. Annotating every
4310 static and thread duration variable with this attribute is equivalent to
4311 invoking clang with -fno-c++-static-destructors.
4313 If a variable is declared with this attribute, clang doesn't access check or
4314 generate the type's destructor. If you have a type that you only want to be
4315 annotated with ``no_destroy``, you can therefore declare the destructor private:
4319 struct only_no_destroy {
4325 [[clang::no_destroy]] only_no_destroy global; // fine!
4327 Note that destructors are still required for subobjects of aggregates annotated
4328 with this attribute. This is because previously constructed subobjects need to
4329 be destroyed if an exception gets thrown before the initialization of the
4330 complete object is complete. For instance:
4336 [[clang::no_destroy]]
4337 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor.
4343 Here, if the construction of `array[9]` fails with an exception, `array[0..8]`
4344 will be destroyed, so the element's destructor needs to be accessible.
4348 def UninitializedDocs : Documentation {
4349 let Category = DocCatVariable;
4351 The command-line parameter ``-ftrivial-auto-var-init=*`` can be used to
4352 initialize trivial automatic stack variables. By default, trivial automatic
4353 stack variables are uninitialized. This attribute is used to override the
4354 command-line parameter, forcing variables to remain uninitialized. It has no
4355 semantic meaning in that using uninitialized values is undefined behavior,
4356 it rather documents the programmer's intent.
4360 def CallbackDocs : Documentation {
4361 let Category = DocCatFunction;
4363 The ``callback`` attribute specifies that the annotated function may invoke the
4364 specified callback zero or more times. The callback, as well as the passed
4365 arguments, are identified by their parameter name or position (starting with
4366 1!) in the annotated function. The first position in the attribute identifies
4367 the callback callee, the following positions declare describe its arguments.
4368 The callback callee is required to be callable with the number, and order, of
4369 the specified arguments. The index `0`, or the identifier `this`, is used to
4370 represent an implicit "this" pointer in class methods. If there is no implicit
4371 "this" pointer it shall not be referenced. The index '-1', or the name "__",
4372 represents an unknown callback callee argument. This can be a value which is
4373 not present in the declared parameter list, or one that is, but is potentially
4374 inspected, captured, or modified. Parameter names and indices can be mixed in
4375 the callback attribute.
4377 The ``callback`` attribute, which is directly translated to ``callback``
4378 metadata <http://llvm.org/docs/LangRef.html#callback-metadata>, make the
4379 connection between the call to the annotated function and the callback callee.
4380 This can enable interprocedural optimizations which were otherwise impossible.
4381 If a function parameter is mentioned in the ``callback`` attribute, through its
4382 position, it is undefined if that parameter is used for anything other than the
4383 actual callback. Inspected, captured, or modified parameters shall not be
4384 listed in the ``callback`` metadata.
4386 Example encodings for the callback performed by `pthread_create` are shown
4387 below. The explicit attribute annotation indicates that the third parameter
4388 (`start_routine`) is called zero or more times by the `pthread_create` function,
4389 and that the fourth parameter (`arg`) is passed along. Note that the callback
4390 behavior of `pthread_create` is automatically recognized by Clang. In addition,
4391 the declarations of `__kmpc_fork_teams` and `__kmpc_fork_call`, generated for
4392 `#pragma omp target teams` and `#pragma omp parallel`, respectively, are also
4393 automatically recognized as broker functions. Further functions might be added
4398 __attribute__((callback (start_routine, arg)))
4399 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
4400 void *(*start_routine) (void *), void *arg);
4402 __attribute__((callback (3, 4)))
4403 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
4404 void *(*start_routine) (void *), void *arg);
4409 def GnuInlineDocs : Documentation {
4410 let Category = DocCatFunction;
4412 The ``gnu_inline`` changes the meaning of ``extern inline`` to use GNU inline
4415 * If any declaration that is declared ``inline`` is not declared ``extern``,
4416 then the ``inline`` keyword is just a hint. In particular, an out-of-line
4417 definition is still emitted for a function with external linkage, even if all
4418 call sites are inlined, unlike in C99 and C++ inline semantics.
4420 * If all declarations that are declared ``inline`` are also declared
4421 ``extern``, then the function body is present only for inlining and no
4422 out-of-line version is emitted.
4424 Some important consequences: ``static inline`` emits an out-of-line
4425 version if needed, a plain ``inline`` definition emits an out-of-line version
4426 always, and an ``extern inline`` definition (in a header) followed by a
4427 (non-``extern``) ``inline`` declaration in a source file emits an out-of-line
4428 version of the function in that source file but provides the function body for
4429 inlining to all includers of the header.
4431 Either ``__GNUC_GNU_INLINE__`` (GNU inline semantics) or
4432 ``__GNUC_STDC_INLINE__`` (C99 semantics) will be defined (they are mutually
4433 exclusive). If ``__GNUC_STDC_INLINE__`` is defined, then the ``gnu_inline``
4434 function attribute can be used to get GNU inline semantics on a per function
4435 basis. If ``__GNUC_GNU_INLINE__`` is defined, then the translation unit is
4436 already being compiled with GNU inline semantics as the implied default. It is
4437 unspecified which macro is defined in a C++ compilation.
4439 GNU inline semantics are the default behavior with ``-std=gnu89``,
4440 ``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.
4444 def SpeculativeLoadHardeningDocs : Documentation {
4445 let Category = DocCatFunction;
4447 This attribute can be applied to a function declaration in order to indicate
4448 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
4449 should be enabled for the function body. This can also be applied to a method
4450 in Objective C. This attribute will take precedence over the command line flag in
4451 the case where `-mno-speculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
4453 Speculative Load Hardening is a best-effort mitigation against
4454 information leak attacks that make use of control flow
4455 miss-speculation - specifically miss-speculation of whether a branch
4456 is taken or not. Typically vulnerabilities enabling such attacks are
4457 classified as "Spectre variant #1". Notably, this does not attempt to
4458 mitigate against miss-speculation of branch target, classified as
4459 "Spectre variant #2" vulnerabilities.
4461 When inlining, the attribute is sticky. Inlining a function that
4462 carries this attribute will cause the caller to gain the
4463 attribute. This is intended to provide a maximally conservative model
4464 where the code in a function annotated with this attribute will always
4465 (even after inlining) end up hardened.
4469 def NoSpeculativeLoadHardeningDocs : Documentation {
4470 let Category = DocCatFunction;
4472 This attribute can be applied to a function declaration in order to indicate
4473 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
4474 is *not* needed for the function body. This can also be applied to a method
4475 in Objective C. This attribute will take precedence over the command line flag in
4476 the case where `-mspeculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
4478 Warning: This attribute may not prevent Speculative Load Hardening from being
4479 enabled for a function which inlines a function that has the
4480 'speculative_load_hardening' attribute. This is intended to provide a
4481 maximally conservative model where the code that is marked with the
4482 'speculative_load_hardening' attribute will always (even when inlined)
4483 be hardened. A user of this attribute may want to mark functions called by
4484 a function they do not want to be hardened with the 'noinline' attribute.
4490 __attribute__((speculative_load_hardening))
4495 // Note: bar() may still have speculative load hardening enabled if
4496 // foo() is inlined into bar(). Mark foo() with __attribute__((noinline))
4497 // to avoid this situation.
4498 __attribute__((no_speculative_load_hardening))
4505 def ObjCExternallyRetainedDocs : Documentation {
4506 let Category = DocCatVariable;
4508 The ``objc_externally_retained`` attribute can be applied to strong local
4509 variables, functions, methods, or blocks to opt into
4510 `externally-retained semantics
4511 <https://clang.llvm.org/docs/AutomaticReferenceCounting.html#externally-retained-variables>`_.
4513 When applied to the definition of a function, method, or block, every parameter
4514 of the function with implicit strong retainable object pointer type is
4515 considered externally-retained, and becomes ``const``. By explicitly annotating
4516 a parameter with ``__strong``, you can opt back into the default
4517 non-externally-retained behaviour for that parameter. For instance,
4518 ``first_param`` is externally-retained below, but not ``second_param``:
4520 .. code-block:: objc
4522 __attribute__((objc_externally_retained))
4523 void f(NSArray *first_param, __strong NSArray *second_param) {
4527 Likewise, when applied to a strong local variable, that variable becomes
4528 ``const`` and is considered externally-retained.
4530 When compiled without ``-fobjc-arc``, this attribute is ignored.
4533 def MIGConventionDocs : Documentation {
4534 let Category = DocCatFunction;
4536 The Mach Interface Generator release-on-success convention dictates
4537 functions that follow it to only release arguments passed to them when they
4538 return "success" (a ``kern_return_t`` error code that indicates that
4539 no errors have occured). Otherwise the release is performed by the MIG client
4540 that called the function. The annotation ``__attribute__((mig_server_routine))``
4541 is applied in order to specify which functions are expected to follow the
4542 convention. This allows the Static Analyzer to find bugs caused by violations of
4543 that convention. The attribute would normally appear on the forward declaration
4544 of the actual server routine in the MIG server header, but it may also be
4545 added to arbitrary functions that need to follow the same convention - for
4546 example, a user can add them to auxiliary functions called by the server routine
4547 that have their return value of type ``kern_return_t`` unconditionally returned
4548 from the routine. The attribute can be applied to C++ methods, and in this case
4549 it will be automatically applied to overrides if the method is virtual. The
4550 attribute can also be written using C++11 syntax: ``[[mig::server_routine]]``.
4554 def MSAllocatorDocs : Documentation {
4555 let Category = DocCatFunction;
4557 The ``__declspec(allocator)`` attribute is applied to functions that allocate
4558 memory, such as operator new in C++. When CodeView debug information is emitted
4559 (enabled by ``clang -gcodeview`` or ``clang-cl /Z7``), Clang will attempt to
4560 record the code offset of heap allocation call sites in the debug info. It will
4561 also record the type being allocated using some local heuristics. The Visual
4562 Studio debugger uses this information to `profile memory usage`_.
4564 .. _profile memory usage: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage
4566 This attribute does not affect optimizations in any way, unlike GCC's
4567 ``__attribute__((malloc))``.
4571 def CFGuardDocs : Documentation {
4572 let Category = DocCatFunction;
4574 Code can indicate CFG checks are not wanted with the ``__declspec(guard(nocf))``
4575 attribute. This directs the compiler to not insert any CFG checks for the entire
4576 function. This approach is typically used only sparingly in specific situations
4577 where the programmer has manually inserted "CFG-equivalent" protection. The
4578 programmer knows that they are calling through some read-only function table
4579 whose address is obtained through read-only memory references and for which the
4580 index is masked to the function table limit. This approach may also be applied
4581 to small wrapper functions that are not inlined and that do nothing more than
4582 make a call through a function pointer. Since incorrect usage of this directive
4583 can compromise the security of CFG, the programmer must be very careful using
4584 the directive. Typically, this usage is limited to very small functions that
4585 only call one function.
4587 `Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>`
4591 def HIPPinnedShadowDocs : Documentation {
4592 let Category = DocCatType;
4594 The GNU style attribute __attribute__((hip_pinned_shadow)) or MSVC style attribute
4595 __declspec(hip_pinned_shadow) can be added to the definition of a global variable
4596 to indicate it is a HIP pinned shadow variable. A HIP pinned shadow variable can
4597 be accessed on both device side and host side. It has external linkage and is
4598 not initialized on device side. It has internal linkage and is initialized by
4599 the initializer on host side.
4603 def LifetimeOwnerDocs : Documentation {
4604 let Category = DocCatDecl;
4606 .. Note:: This attribute is experimental and its effect on analysis is subject to change in
4607 a future version of clang.
4609 The attribute ``[[gsl::Owner(T)]]`` applies to structs and classes that own an
4610 object of type ``T``:
4614 class [[gsl::Owner(int)]] IntOwner {
4618 int *getInt() { return &value; }
4621 The argument ``T`` is optional and is ignored.
4622 This attribute may be used by analysis tools and has no effect on code
4623 generation. A ``void`` argument means that the class can own any type.
4625 See Pointer_ for an example.
4629 def LifetimePointerDocs : Documentation {
4630 let Category = DocCatDecl;
4632 .. Note:: This attribute is experimental and its effect on analysis is subject to change in
4633 a future version of clang.
4635 The attribute ``[[gsl::Pointer(T)]]`` applies to structs and classes that behave
4636 like pointers to an object of type ``T``:
4640 class [[gsl::Pointer(int)]] IntPointer {
4644 int *getInt() { return &valuePointer; }
4647 The argument ``T`` is optional and is ignored.
4648 This attribute may be used by analysis tools and has no effect on code
4649 generation. A ``void`` argument means that the pointer can point to any type.
4652 When constructing an instance of a class annotated like this (a Pointer) from
4653 an instance of a class annotated with ``[[gsl::Owner]]`` (an Owner),
4654 then the analysis will consider the Pointer to point inside the Owner.
4655 When the Owner's lifetime ends, it will consider the Pointer to be dangling.
4663 P = IntPointer(O); // P "points into" O
4665 return P.get(); // error: Using a dangling Pointer.
4671 def ArmMveAliasDocs : Documentation {
4672 let Category = DocCatFunction;
4674 This attribute is used in the implementation of the ACLE intrinsics
4675 for the Arm MVE instruction set. It allows the intrinsic functions to
4676 be declared using the names defined in ACLE, and still be recognized
4677 as clang builtins equivalent to the underlying name. For example,
4678 ``arm_mve.h`` declares the function ``vaddq_u32`` with
4679 ``__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))``,
4680 and similarly, one of the type-overloaded declarations of ``vaddq``
4681 will have the same attribute. This ensures that both functions are
4682 recognized as that clang builtin, and in the latter case, the choice
4683 of which builtin to identify the function as can be deferred until
4684 after overload resolution.
4686 This attribute can only be used to set up the aliases for the MVE
4687 intrinsic functions; it is intended for use only inside ``arm_mve.h``,
4688 and is not a general mechanism for declaring arbitrary aliases for
4689 clang builtin functions.
4693 def NoBuiltinDocs : Documentation {
4694 let Category = DocCatFunction;
4696 .. Note:: This attribute is not yet fully implemented, it is validated but has
4697 no effect on the generated code.
4699 The ``__attribute__((no_builtin))`` is similar to the ``-fno-builtin`` flag
4700 except it is specific to the body of a function. The attribute may also be
4701 applied to a virtual function but has no effect on the behavior of overriding
4702 functions in a derived class.
4704 It accepts one or more strings corresponding to the specific names of the
4705 builtins to disable (e.g. "memcpy", "memset").
4706 If the attribute is used without parameters it will disable all buitins at
4711 // The compiler is not allowed to add any builtin to foo's body.
4712 void foo(char* data, size_t count) __attribute__((no_builtin)) {
4713 // The compiler is not allowed to convert the loop into
4714 // `__builtin_memset(data, 0xFE, count);`.
4715 for (size_t i = 0; i < count; ++i)
4719 // The compiler is not allowed to add the `memcpy` builtin to bar's body.
4720 void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) {
4721 // The compiler is allowed to convert the loop into
4722 // `__builtin_memset(data, 0xFE, count);` but cannot generate any
4723 // `__builtin_memcpy`
4724 for (size_t i = 0; i < count; ++i)
4730 def HandleDocs : DocumentationCategory<"Handle Attributes"> {
4732 Handles are a way to identify resources like files, sockets, and processes.
4733 They are more opaque than pointers and widely used in system programming. They
4734 have similar risks such as never releasing a resource associated with a handle,
4735 attempting to use a handle that was already released, or trying to release a
4736 handle twice. Using the annotations below it is possible to make the ownership
4737 of the handles clear: whose responsibility is to release them. They can also
4738 aid static analysis tools to find bugs.
4742 def AcquireHandleDocs : Documentation {
4743 let Category = HandleDocs;
4745 If this annotation is on a function or a function type it is assumed to return
4746 a new handle. In case this annotation is on an output parameter,
4747 the function is assumed to fill the corresponding argument with a new
4752 // Output arguments from Zircon.
4753 zx_status_t zx_socket_create(uint32_t options,
4754 zx_handle_t __attribute__((acquire_handle)) * out0,
4755 zx_handle_t* out1 [[clang::acquire_handle]]);
4759 [[clang::acquire_handle]] int open(const char *path, int oflag, ... );
4760 int open(const char *path, int oflag, ... ) __attribute__((acquire_handle));
4764 def UseHandleDocs : Documentation {
4765 let Category = HandleDocs;
4767 A function taking a handle by value might close the handle. If a function
4768 parameter is annotated with `use_handle` it is assumed to not to change
4769 the state of the handle. It is also assumed to require an open handle to work with.
4773 zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle]],
4775 zx_port_packet_t* packet);
4779 def ReleaseHandleDocs : Documentation {
4780 let Category = HandleDocs;
4782 If a function parameter is annotated with `release_handle` it is assumed to
4783 close the handle. It is also assumed to require an open handle to work with.
4787 zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle]]);