1 //==--- AttrDocs.td - Attribute documentation ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===---------------------------------------------------------------------===//
10 def GlobalDocumentation {
12 -------------------------------------------------------------------
13 NOTE: This file is automatically generated by running clang-tblgen
14 -gen-attr-docs. Do not edit this file by hand!!
15 -------------------------------------------------------------------
26 This page lists the attributes currently supported by Clang.
30 def SectionDocs : Documentation {
31 let Category = DocCatVariable;
33 The ``section`` attribute allows you to specify a specific section a
34 global variable or function should be in after translation.
36 let Heading = "section (gnu::section, __declspec(allocate))";
39 def InitSegDocs : Documentation {
40 let Category = DocCatVariable;
42 The attribute applied by ``pragma init_seg()`` controls the section into
43 which global initialization function pointers are emitted. It is only
44 available with ``-fms-extensions``. Typically, this function pointer is
45 emitted into ``.CRT$XCU`` on Windows. The user can change the order of
46 initialization by using a different section name with the same
47 ``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
48 after the standard ``.CRT$XCU`` sections. See the init_seg_
49 documentation on MSDN for more information.
51 .. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx
55 def TLSModelDocs : Documentation {
56 let Category = DocCatVariable;
58 The ``tls_model`` attribute allows you to specify which thread-local storage
59 model to use. It accepts the following strings:
66 TLS models are mutually exclusive.
70 def DLLExportDocs : Documentation {
71 let Category = DocCatVariable;
73 The ``__declspec(dllexport)`` attribute declares a variable, function, or
74 Objective-C interface to be exported from the module. It is available under the
75 ``-fdeclspec`` flag for compatibility with various compilers. The primary use
76 is for COFF object files which explicitly specify what interfaces are available
77 for external use. See the dllexport_ documentation on MSDN for more
80 .. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
84 def DLLImportDocs : Documentation {
85 let Category = DocCatVariable;
87 The ``__declspec(dllimport)`` attribute declares a variable, function, or
88 Objective-C interface to be imported from an external module. It is available
89 under the ``-fdeclspec`` flag for compatibility with various compilers. The
90 primary use is for COFF object files which explicitly specify what interfaces
91 are imported from external modules. See the dllimport_ documentation on MSDN
94 .. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
98 def ThreadDocs : Documentation {
99 let Category = DocCatVariable;
101 The ``__declspec(thread)`` attribute declares a variable with thread local
102 storage. It is available under the ``-fms-extensions`` flag for MSVC
103 compatibility. See the documentation for `__declspec(thread)`_ on MSDN.
105 .. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
107 In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
108 GNU ``__thread`` keyword. The variable must not have a destructor and must have
109 a constant initializer, if any. The attribute only applies to variables
110 declared with static storage duration, such as globals, class static data
111 members, and static locals.
115 def CarriesDependencyDocs : Documentation {
116 let Category = DocCatFunction;
118 The ``carries_dependency`` attribute specifies dependency propagation into and
121 When specified on a function or Objective-C method, the ``carries_dependency``
122 attribute means that the return value carries a dependency out of the function,
123 so that the implementation need not constrain ordering upon return from that
124 function. Implementations of the function and its caller may choose to preserve
125 dependencies instead of emitting memory ordering instructions such as fences.
127 Note, this attribute does not change the meaning of the program, but may result
128 in generation of more efficient code.
132 def C11NoReturnDocs : Documentation {
133 let Category = DocCatFunction;
135 A function declared as ``_Noreturn`` shall not return to its caller. The
136 compiler will generate a diagnostic for a function declared as ``_Noreturn``
137 that appears to be capable of returning to its caller.
141 def CXX11NoReturnDocs : Documentation {
142 let Category = DocCatFunction;
144 A function declared as ``[[noreturn]]`` shall not return to its caller. The
145 compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
146 that appears to be capable of returning to its caller.
150 def AssertCapabilityDocs : Documentation {
151 let Category = DocCatFunction;
152 let Heading = "assert_capability (assert_shared_capability, clang::assert_capability, clang::assert_shared_capability)";
154 Marks a function that dynamically tests whether a capability is held, and halts
155 the program if it is not held.
159 def AcquireCapabilityDocs : Documentation {
160 let Category = DocCatFunction;
161 let Heading = "acquire_capability (acquire_shared_capability, clang::acquire_capability, clang::acquire_shared_capability)";
163 Marks a function as acquiring a capability.
167 def TryAcquireCapabilityDocs : Documentation {
168 let Category = DocCatFunction;
169 let Heading = "try_acquire_capability (try_acquire_shared_capability, clang::try_acquire_capability, clang::try_acquire_shared_capability)";
171 Marks a function that attempts to acquire a capability. This function may fail to
172 actually acquire the capability; they accept a Boolean value determining
173 whether acquiring the capability means success (true), or failing to acquire
174 the capability means success (false).
178 def ReleaseCapabilityDocs : Documentation {
179 let Category = DocCatFunction;
180 let Heading = "release_capability (release_shared_capability, clang::release_capability, clang::release_shared_capability)";
182 Marks a function as releasing a capability.
186 def AssumeAlignedDocs : Documentation {
187 let Category = DocCatFunction;
189 Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function
190 declaration to specify that the return value of the function (which must be a
191 pointer type) has the specified offset, in bytes, from an address with the
192 specified alignment. The offset is taken to be zero if omitted.
196 // The returned pointer value has 32-byte alignment.
197 void *a() __attribute__((assume_aligned (32)));
199 // The returned pointer value is 4 bytes greater than an address having
200 // 32-byte alignment.
201 void *b() __attribute__((assume_aligned (32, 4)));
203 Note that this attribute provides information to the compiler regarding a
204 condition that the code already ensures is true. It does not cause the compiler
205 to enforce the provided alignment assumption.
209 def AllocSizeDocs : Documentation {
210 let Category = DocCatFunction;
212 The ``alloc_size`` attribute can be placed on functions that return pointers in
213 order to hint to the compiler how many bytes of memory will be available at the
214 returned poiner. ``alloc_size`` takes one or two arguments.
216 - ``alloc_size(N)`` implies that argument number N equals the number of
217 available bytes at the returned pointer.
218 - ``alloc_size(N, M)`` implies that the product of argument number N and
219 argument number M equals the number of available bytes at the returned
222 Argument numbers are 1-based.
224 An example of how to use ``alloc_size``
228 void *my_malloc(int a) __attribute__((alloc_size(1)));
229 void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
232 void *const p = my_malloc(100);
233 assert(__builtin_object_size(p, 0) == 100);
234 void *const a = my_calloc(20, 5);
235 assert(__builtin_object_size(a, 0) == 100);
238 .. Note:: This attribute works differently in clang than it does in GCC.
239 Specifically, clang will only trace ``const`` pointers (as above); we give up
240 on pointers that are not marked as ``const``. In the vast majority of cases,
241 this is unimportant, because LLVM has support for the ``alloc_size``
242 attribute. However, this may cause mildly unintuitive behavior when used with
243 other attributes, such as ``enable_if``.
247 def AllocAlignDocs : Documentation {
248 let Category = DocCatFunction;
250 Use ``__attribute__((alloc_align(<alignment>))`` on a function
251 declaration to specify that the return value of the function (which must be a
252 pointer type) is at least as aligned as the value of the indicated parameter. The
253 parameter is given by its index in the list of formal parameters; the first
254 parameter has index 1 unless the function is a C++ non-static member function,
255 in which case the first parameter has index 2 to account for the implicit ``this``
260 // The returned pointer has the alignment specified by the first parameter.
261 void *a(size_t align) __attribute__((alloc_align(1)));
263 // The returned pointer has the alignment specified by the second parameter.
264 void *b(void *v, size_t align) __attribute__((alloc_align(2)));
266 // The returned pointer has the alignment specified by the second visible
267 // parameter, however it must be adjusted for the implicit 'this' parameter.
268 void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
270 Note that this attribute merely informs the compiler that a function always
271 returns a sufficiently aligned pointer. It does not cause the compiler to
272 emit code to enforce that alignment. The behavior is undefined if the returned
273 poitner is not sufficiently aligned.
277 def EnableIfDocs : Documentation {
278 let Category = DocCatFunction;
280 .. Note:: Some features of this attribute are experimental. The meaning of
281 multiple enable_if attributes on a single declaration is subject to change in
282 a future version of clang. Also, the ABI is not standardized and the name
283 mangling may change in future versions. To avoid that, use asm labels.
285 The ``enable_if`` attribute can be placed on function declarations to control
286 which overload is selected based on the values of the function's arguments.
287 When combined with the ``overloadable`` attribute, this feature is also
293 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")));
298 isdigit(-10); // results in a compile-time error.
301 The enable_if attribute takes two arguments, the first is an expression written
302 in terms of the function parameters, the second is a string explaining why this
303 overload candidate could not be selected to be displayed in diagnostics. The
304 expression is part of the function signature for the purposes of determining
305 whether it is a redeclaration (following the rules used when determining
306 whether a C++ template specialization is ODR-equivalent), but is not part of
309 The enable_if expression is evaluated as if it were the body of a
310 bool-returning constexpr function declared with the arguments of the function
311 it is being applied to, then called with the parameters at the call site. If the
312 result is false or could not be determined through constant expression
313 evaluation, then this overload will not be chosen and the provided string may
314 be used in a diagnostic if the compile fails as a result.
316 Because the enable_if expression is an unevaluated context, there are no global
317 state changes, nor the ability to pass information from the enable_if
318 expression to the function body. For example, suppose we want calls to
319 strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
320 strbuf) only if the size of strbuf can be determined:
324 __attribute__((always_inline))
325 static inline size_t strnlen(const char *s, size_t maxlen)
326 __attribute__((overloadable))
327 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
328 "chosen when the buffer size is known but 'maxlen' is not")))
330 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
333 Multiple enable_if attributes may be applied to a single declaration. In this
334 case, the enable_if expressions are evaluated from left to right in the
335 following manner. First, the candidates whose enable_if expressions evaluate to
336 false or cannot be evaluated are discarded. If the remaining candidates do not
337 share ODR-equivalent enable_if expressions, the overload resolution is
338 ambiguous. Otherwise, enable_if overload resolution continues with the next
339 enable_if attribute on the candidates that have not been discarded and have
340 remaining enable_if attributes. In this way, we pick the most specific
341 overload out of a number of viable overloads using enable_if.
345 void f() __attribute__((enable_if(true, ""))); // #1
346 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
348 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
349 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
351 In this example, a call to f() is always resolved to #2, as the first enable_if
352 expression is ODR-equivalent for both declarations, but #1 does not have another
353 enable_if expression to continue evaluating, so the next round of evaluation has
354 only a single candidate. In a call to g(1, 1), the call is ambiguous even though
355 #2 has more enable_if attributes, because the first enable_if expressions are
358 Query for this feature with ``__has_attribute(enable_if)``.
360 Note that functions with one or more ``enable_if`` attributes may not have
361 their address taken, unless all of the conditions specified by said
362 ``enable_if`` are constants that evaluate to ``true``. For example:
366 const int TrueConstant = 1;
367 const int FalseConstant = 0;
368 int f(int a) __attribute__((enable_if(a > 0, "")));
369 int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
370 int h(int a) __attribute__((enable_if(1, "")));
371 int i(int a) __attribute__((enable_if(TrueConstant, "")));
372 int j(int a) __attribute__((enable_if(FalseConstant, "")));
376 ptr = &f; // error: 'a > 0' is not always true
377 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
378 ptr = &h; // OK: 1 is a truthy constant
379 ptr = &i; // OK: 'TrueConstant' is a truthy constant
380 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
383 Because ``enable_if`` evaluation happens during overload resolution,
384 ``enable_if`` may give unintuitive results when used with templates, depending
385 on when overloads are resolved. In the example below, clang will emit a
386 diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``:
390 double foo(int i) __attribute__((enable_if(i > 0, "")));
391 void *foo(int i) __attribute__((enable_if(i <= 0, "")));
393 auto bar() { return foo(I); }
395 template <typename T>
396 auto baz() { return foo(T::number); }
398 struct WithNumber { constexpr static int number = 1; };
400 bar<sizeof(WithNumber)>();
404 This is because, in ``bar``, ``foo`` is resolved prior to template
405 instantiation, so the value for ``I`` isn't known (thus, both ``enable_if``
406 conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during
407 template instantiation, so the value for ``T::number`` is known.
411 def DiagnoseIfDocs : Documentation {
412 let Category = DocCatFunction;
414 The ``diagnose_if`` attribute can be placed on function declarations to emit
415 warnings or errors at compile-time if calls to the attributed function meet
416 certain user-defined criteria. For example:
421 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
423 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
425 int val = abs(1); // warning: Redundant abs call
426 int val2 = must_abs(1); // error: Redundant abs call
428 int val4 = must_abs(val); // Because run-time checks are not emitted for
429 // diagnose_if attributes, this executes without
433 ``diagnose_if`` is closely related to ``enable_if``, with a few key differences:
435 * Overload resolution is not aware of ``diagnose_if`` attributes: they're
436 considered only after we select the best candidate from a given candidate set.
437 * Function declarations that differ only in their ``diagnose_if`` attributes are
438 considered to be redeclarations of the same function (not overloads).
439 * If the condition provided to ``diagnose_if`` cannot be evaluated, no
440 diagnostic will be emitted.
442 Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``.
444 As a result of bullet number two, ``diagnose_if`` attributes will stack on the
445 same function. For example:
449 int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
450 int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
452 int bar = foo(); // warning: diag1
454 int (*fooptr)(void) = foo; // warning: diag1
457 constexpr int supportsAPILevel(int N) { return N < 5; }
459 __attribute__((diagnose_if(!supportsAPILevel(10),
460 "Upgrade to API level 10 to use baz", "error")));
462 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
464 int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
465 int v = baz(0); // error: Upgrade to API level 10 to use baz
467 Query for this feature with ``__has_attribute(diagnose_if)``.
471 def PassObjectSizeDocs : Documentation {
472 let Category = DocCatVariable; // Technically it's a parameter doc, but eh.
474 .. Note:: The mangling of functions with parameters that are annotated with
475 ``pass_object_size`` is subject to change. You can get around this by
476 using ``__asm__("foo")`` to explicitly name your functions, thus preserving
477 your ABI; also, non-overloadable C functions with ``pass_object_size`` are
480 The ``pass_object_size(Type)`` attribute can be placed on function parameters to
481 instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite
482 of said function, and implicitly pass the result of this call in as an invisible
483 argument of type ``size_t`` directly after the parameter annotated with
484 ``pass_object_size``. Clang will also replace any calls to
485 ``__builtin_object_size(param, Type)`` in the function by said implicit
492 int bzero1(char *const p __attribute__((pass_object_size(0))))
493 __attribute__((noinline)) {
495 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
503 int n = bzero1(&chars[0]);
504 assert(n == sizeof(chars));
508 If successfully evaluating ``__builtin_object_size(param, Type)`` at the
509 callsite is not possible, then the "failed" value is passed in. So, using the
510 definition of ``bzero1`` from above, the following code would exit cleanly:
514 int main2(int argc, char *argv[]) {
515 int n = bzero1(argv);
520 ``pass_object_size`` plays a part in overload resolution. If two overload
521 candidates are otherwise equally good, then the overload with one or more
522 parameters with ``pass_object_size`` is preferred. This implies that the choice
523 between two identical overloads both with ``pass_object_size`` on one or more
524 parameters will always be ambiguous; for this reason, having two such overloads
525 is illegal. For example:
529 #define PS(N) __attribute__((pass_object_size(N)))
531 void Foo(char *a, char *b); // Overload A
532 // OK -- overload A has no parameters with pass_object_size.
533 void Foo(char *a PS(0), char *b PS(0)); // Overload B
534 // Error -- Same signature (sans pass_object_size) as overload B, and both
535 // overloads have one or more parameters with the pass_object_size attribute.
536 void Foo(void *a PS(0), void *b);
539 void Bar(void *a PS(0)); // Overload C
541 void Bar(char *c PS(1)); // Overload D
544 char known[10], *unknown;
545 Foo(unknown, unknown); // Calls overload B
546 Foo(known, unknown); // Calls overload B
547 Foo(unknown, known); // Calls overload B
548 Foo(known, known); // Calls overload B
550 Bar(known); // Calls overload D
551 Bar(unknown); // Calls overload D
554 Currently, ``pass_object_size`` is a bit restricted in terms of its usage:
556 * Only one use of ``pass_object_size`` is allowed per parameter.
558 * It is an error to take the address of a function with ``pass_object_size`` on
559 any of its parameters. If you wish to do this, you can create an overload
560 without ``pass_object_size`` on any parameters.
562 * It is an error to apply the ``pass_object_size`` attribute to parameters that
563 are not pointers. Additionally, any parameter that ``pass_object_size`` is
564 applied to must be marked ``const`` at its function's definition.
568 def OverloadableDocs : Documentation {
569 let Category = DocCatFunction;
571 Clang provides support for C++ function overloading in C. Function overloading
572 in C is introduced using the ``overloadable`` attribute. For example, one
573 might provide several overloaded versions of a ``tgsin`` function that invokes
574 the appropriate standard function computing the sine of a value with ``float``,
575 ``double``, or ``long double`` precision:
580 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
581 double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
582 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
584 Given these declarations, one can call ``tgsin`` with a ``float`` value to
585 receive a ``float`` result, with a ``double`` to receive a ``double`` result,
586 etc. Function overloading in C follows the rules of C++ function overloading
587 to pick the best overload given the call arguments, with a few C-specific
590 * Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
591 floating-point promotion (per C99) rather than as a floating-point conversion
594 * A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
595 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
598 * A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
599 and ``U`` are compatible types. This conversion is given "conversion" rank.
601 * If no viable candidates are otherwise available, we allow a conversion from a
602 pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are
603 incompatible. This conversion is ranked below all other types of conversions.
604 Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient
605 for ``T`` and ``U`` to be incompatible.
607 The declaration of ``overloadable`` functions is restricted to function
608 declarations and definitions. Most importantly, if any function with a given
609 name is given the ``overloadable`` attribute, then all function declarations
610 and definitions with that name (and in that scope) must have the
611 ``overloadable`` attribute. This rule even applies to redeclarations of
612 functions whose original declaration had the ``overloadable`` attribute, e.g.,
616 int f(int) __attribute__((overloadable));
617 float f(float); // error: declaration of "f" must have the "overloadable" attribute
619 int g(int) __attribute__((overloadable));
620 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
622 Functions marked ``overloadable`` must have prototypes. Therefore, the
623 following code is ill-formed:
627 int h() __attribute__((overloadable)); // error: h does not have a prototype
629 However, ``overloadable`` functions are allowed to use a ellipsis even if there
630 are no named parameters (as is permitted in C++). This feature is particularly
631 useful when combined with the ``unavailable`` attribute:
635 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
637 Functions declared with the ``overloadable`` attribute have their names mangled
638 according to the same rules as C++ function names. For example, the three
639 ``tgsin`` functions in our motivating example get the mangled names
640 ``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
641 caveats to this use of name mangling:
643 * Future versions of Clang may change the name mangling of functions overloaded
644 in C, so you should not depend on an specific mangling. To be completely
645 safe, we strongly urge the use of ``static inline`` with ``overloadable``
648 * The ``overloadable`` attribute has almost no meaning when used in C++,
649 because names will already be mangled and functions are already overloadable.
650 However, when an ``overloadable`` function occurs within an ``extern "C"``
651 linkage specification, it's name *will* be mangled in the same way as it
654 Query for this feature with ``__has_extension(attribute_overloadable)``.
658 def ObjCMethodFamilyDocs : Documentation {
659 let Category = DocCatFunction;
661 Many methods in Objective-C have conventional meanings determined by their
662 selectors. It is sometimes useful to be able to mark a method as having a
663 particular conventional meaning despite not having the right selector, or as
664 not having the conventional meaning that its selector would suggest. For these
665 use cases, we provide an attribute to specifically describe the "method family"
666 that a method belongs to.
668 **Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
669 ``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
670 attribute can only be placed at the end of a method declaration:
674 - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
676 Users who do not wish to change the conventional meaning of a method, and who
677 merely want to document its non-standard retain and release semantics, should
678 use the retaining behavior attributes (``ns_returns_retained``,
679 ``ns_returns_not_retained``, etc).
681 Query for this feature with ``__has_attribute(objc_method_family)``.
685 def NoDebugDocs : Documentation {
686 let Category = DocCatVariable;
688 The ``nodebug`` attribute allows you to suppress debugging information for a
689 function or method, or for a variable that is not a parameter or a non-static
694 def NoDuplicateDocs : Documentation {
695 let Category = DocCatFunction;
697 The ``noduplicate`` attribute can be placed on function declarations to control
698 whether function calls to this function can be duplicated or not as a result of
699 optimizations. This is required for the implementation of functions with
700 certain special requirements, like the OpenCL "barrier" function, that might
701 need to be run concurrently by all the threads that are executing in lockstep
702 on the hardware. For example this attribute applied on the function
703 "nodupfunc" in the code below avoids that:
707 void nodupfunc() __attribute__((noduplicate));
708 // Setting it as a C++11 attribute is also valid
709 // void nodupfunc() [[clang::noduplicate]];
720 gets possibly modified by some optimizations into code similar to this:
732 where the call to "nodupfunc" is duplicated and sunk into the two branches
737 def ConvergentDocs : Documentation {
738 let Category = DocCatFunction;
740 The ``convergent`` attribute can be placed on a function declaration. It is
741 translated into the LLVM ``convergent`` attribute, which indicates that the call
742 instructions of a function with this attribute cannot be made control-dependent
743 on any additional values.
745 In languages designed for SPMD/SIMT programming model, e.g. OpenCL or CUDA,
746 the call instructions of a function with this attribute must be executed by
747 all work items or threads in a work group or sub group.
749 This attribute is different from ``noduplicate`` because it allows duplicating
750 function calls if it can be proved that the duplicated function calls are
751 not made control-dependent on any additional values, e.g., unrolling a loop
752 executed by all work items.
757 void convfunc(void) __attribute__((convergent));
758 // Setting it as a C++11 attribute is also valid in a C++ program.
759 // void convfunc(void) [[clang::convergent]];
764 def NoSplitStackDocs : Documentation {
765 let Category = DocCatFunction;
767 The ``no_split_stack`` attribute disables the emission of the split stack
768 preamble for a particular function. It has no effect if ``-fsplit-stack``
773 def ObjCRequiresSuperDocs : Documentation {
774 let Category = DocCatFunction;
776 Some Objective-C classes allow a subclass to override a particular method in a
777 parent class but expect that the overriding method also calls the overridden
778 method in the parent class. For these cases, we provide an attribute to
779 designate that a method requires a "call to ``super``" in the overriding
780 method in the subclass.
782 **Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
783 be placed at the end of a method declaration:
787 - (void)foo __attribute__((objc_requires_super));
789 This attribute can only be applied the method declarations within a class, and
790 not a protocol. Currently this attribute does not enforce any placement of
791 where the call occurs in the overriding method (such as in the case of
792 ``-dealloc`` where the call must appear at the end). It checks only that it
795 Note that on both OS X and iOS that the Foundation framework provides a
796 convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
801 - (void)foo NS_REQUIRES_SUPER;
803 This macro is conditionally defined depending on the compiler's support for
804 this attribute. If the compiler does not support the attribute the macro
807 Operationally, when a method has this annotation the compiler will warn if the
808 implementation of an override in a subclass does not call super. For example:
812 warning: method possibly missing a [super AnnotMeth] call
813 - (void) AnnotMeth{};
818 def ObjCRuntimeNameDocs : Documentation {
819 let Category = DocCatFunction;
821 By default, the Objective-C interface or protocol identifier is used
822 in the metadata name for that object. The `objc_runtime_name`
823 attribute allows annotated interfaces or protocols to use the
824 specified string argument in the object's metadata name instead of the
827 **Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute
828 can only be placed before an @protocol or @interface declaration:
832 __attribute__((objc_runtime_name("MyLocalName")))
839 def ObjCRuntimeVisibleDocs : Documentation {
840 let Category = DocCatFunction;
842 This attribute specifies that the Objective-C class to which it applies is visible to the Objective-C runtime but not to the linker. Classes annotated with this attribute cannot be subclassed and cannot have categories defined for them.
846 def ObjCBoxableDocs : Documentation {
847 let Category = DocCatFunction;
849 Structs and unions marked with the ``objc_boxable`` attribute can be used
850 with the Objective-C boxed expression syntax, ``@(...)``.
852 **Usage**: ``__attribute__((objc_boxable))``. This attribute
853 can only be placed on a declaration of a trivially-copyable struct or union:
857 struct __attribute__((objc_boxable)) some_struct {
860 union __attribute__((objc_boxable)) some_union {
864 typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
869 NSValue *boxed = @(ss);
874 def AvailabilityDocs : Documentation {
875 let Category = DocCatFunction;
877 The ``availability`` attribute can be placed on declarations to describe the
878 lifecycle of that declaration relative to operating system versions. Consider
879 the function declaration for a hypothetical function ``f``:
883 void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
885 The availability attribute states that ``f`` was introduced in Mac OS X 10.4,
886 deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7. This information
887 is used by Clang to determine when it is safe to use ``f``: for example, if
888 Clang is instructed to compile code for Mac OS X 10.5, a call to ``f()``
889 succeeds. If Clang is instructed to compile code for Mac OS X 10.6, the call
890 succeeds but Clang emits a warning specifying that the function is deprecated.
891 Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call
892 fails because ``f()`` is no longer available.
894 The availability attribute is a comma-separated list starting with the
895 platform name and then including clauses specifying important milestones in the
896 declaration's lifetime (in any order) along with additional information. Those
899 introduced=\ *version*
900 The first version in which this declaration was introduced.
902 deprecated=\ *version*
903 The first version in which this declaration was deprecated, meaning that
904 users should migrate away from this API.
906 obsoleted=\ *version*
907 The first version in which this declaration was obsoleted, meaning that it
908 was removed completely and can no longer be used.
911 This declaration is never available on this platform.
913 message=\ *string-literal*
914 Additional message text that Clang will provide when emitting a warning or
915 error about use of a deprecated or obsoleted declaration. Useful to direct
916 users to replacement APIs.
918 replacement=\ *string-literal*
919 Additional message text that Clang will use to provide Fix-It when emitting
920 a warning about use of a deprecated declaration. The Fix-It will replace
921 the deprecated declaration with the new declaration specified.
923 Multiple availability attributes can be placed on a declaration, which may
924 correspond to different platforms. Only the availability attribute with the
925 platform corresponding to the target platform will be used; any others will be
926 ignored. If no availability attribute specifies availability for the current
927 target platform, the availability attributes are ignored. Supported platforms
931 Apple's iOS operating system. The minimum deployment target is specified by
932 the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
933 command-line arguments.
936 Apple's Mac OS X operating system. The minimum deployment target is
937 specified by the ``-mmacosx-version-min=*version*`` command-line argument.
938 ``macosx`` is supported for backward-compatibility reasons, but it is
942 Apple's tvOS operating system. The minimum deployment target is specified by
943 the ``-mtvos-version-min=*version*`` command-line argument.
946 Apple's watchOS operating system. The minimum deployment target is specified by
947 the ``-mwatchos-version-min=*version*`` command-line argument.
949 A declaration can typically be used even when deploying back to a platform
950 version prior to when the declaration was introduced. When this happens, the
951 declaration is `weakly linked
952 <https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
953 as if the ``weak_import`` attribute were added to the declaration. A
954 weakly-linked declaration may or may not be present a run-time, and a program
955 can determine whether the declaration is present by checking whether the
956 address of that declaration is non-NULL.
958 The flag ``strict`` disallows using API when deploying back to a
959 platform version prior to when the declaration was introduced. An
960 attempt to use such API before its introduction causes a hard error.
961 Weakly-linking is almost always a better API choice, since it allows
962 users to query availability at runtime.
964 If there are multiple declarations of the same entity, the availability
965 attributes must either match on a per-platform basis or later
966 declarations must not have availability attributes for that
967 platform. For example:
971 void g(void) __attribute__((availability(macos,introduced=10.4)));
972 void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
973 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
974 void g(void); // okay, inherits both macos and ios availability from above.
975 void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
977 When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
982 - (id)method __attribute__((availability(macos,introduced=10.4)));
983 - (id)method2 __attribute__((availability(macos,introduced=10.4)));
987 - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
988 - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
993 def ExternalSourceSymbolDocs : Documentation {
994 let Category = DocCatFunction;
996 The ``external_source_symbol`` attribute specifies that a declaration originates
997 from an external source and describes the nature of that source.
999 The fact that Clang is capable of recognizing declarations that were defined
1000 externally can be used to provide better tooling support for mixed-language
1001 projects or projects that rely on auto-generated code. For instance, an IDE that
1002 uses Clang and that supports mixed-language projects can use this attribute to
1003 provide a correct 'jump-to-definition' feature. For a concrete example,
1004 consider a protocol that's defined in a Swift file:
1006 .. code-block:: swift
1008 @objc public protocol SwiftProtocol {
1012 This protocol can be used from Objective-C code by including a header file that
1013 was generated by the Swift compiler. The declarations in that header can use
1014 the ``external_source_symbol`` attribute to make Clang aware of the fact
1015 that ``SwiftProtocol`` actually originates from a Swift module:
1017 .. code-block:: objc
1019 __attribute__((external_source_symbol(language="Swift",defined_in="module")))
1020 @protocol SwiftProtocol
1025 Consequently, when 'jump-to-definition' is performed at a location that
1026 references ``SwiftProtocol``, the IDE can jump to the original definition in
1027 the Swift source file rather than jumping to the Objective-C declaration in the
1028 auto-generated header file.
1030 The ``external_source_symbol`` attribute is a comma-separated list that includes
1031 clauses that describe the origin and the nature of the particular declaration.
1032 Those clauses can be:
1034 language=\ *string-literal*
1035 The name of the source language in which this declaration was defined.
1037 defined_in=\ *string-literal*
1038 The name of the source container in which the declaration was defined. The
1039 exact definition of source container is language-specific, e.g. Swift's
1040 source containers are modules, so ``defined_in`` should specify the Swift
1043 generated_declaration
1044 This declaration was automatically generated by some tool.
1046 The clauses can be specified in any order. The clauses that are listed above are
1047 all optional, but the attribute has to have at least one clause.
1051 def RequireConstantInitDocs : Documentation {
1052 let Category = DocCatVariable;
1054 This attribute specifies that the variable to which it is attached is intended
1055 to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_
1056 according to the rules of [basic.start.static]. The variable is required to
1057 have static or thread storage duration. If the initialization of the variable
1058 is not a constant initializer an error will be produced. This attribute may
1059 only be used in C++.
1061 Note that in C++03 strict constant expression checking is not done. Instead
1062 the attribute reports if Clang can emit the variable as a constant, even if it's
1063 not technically a 'constant initializer'. This behavior is non-portable.
1065 Static storage duration variables with constant initializers avoid hard-to-find
1066 bugs caused by the indeterminate order of dynamic initialization. They can also
1067 be safely used during dynamic initialization across translation units.
1069 This attribute acts as a compile time assertion that the requirements
1070 for constant initialization have been met. Since these requirements change
1071 between dialects and have subtle pitfalls it's important to fail fast instead
1072 of silently falling back on dynamic initialization.
1077 #define SAFE_STATIC [[clang::require_constant_initialization]]
1080 ~T(); // non-trivial
1082 SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
1083 SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
1084 // copy initialization is not a constant expression on a non-literal type.
1088 def WarnMaybeUnusedDocs : Documentation {
1089 let Category = DocCatVariable;
1090 let Heading = "maybe_unused, unused, gnu::unused";
1092 When passing the ``-Wunused`` flag to Clang, entities that are unused by the
1093 program may be diagnosed. The ``[[maybe_unused]]`` (or
1094 ``__attribute__((unused))``) attribute can be used to silence such diagnostics
1095 when the entity cannot be removed. For instance, a local variable may exist
1096 solely for use in an ``assert()`` statement, which makes the local variable
1097 unused when ``NDEBUG`` is defined.
1099 The attribute may be applied to the declaration of a class, a typedef, a
1100 variable, a function or method, a function parameter, an enumeration, an
1101 enumerator, a non-static data member, or a label.
1106 [[maybe_unused]] void f([[maybe_unused]] bool thing1,
1107 [[maybe_unused]] bool thing2) {
1108 [[maybe_unused]] bool b = thing1 && thing2;
1114 def WarnUnusedResultsDocs : Documentation {
1115 let Category = DocCatFunction;
1116 let Heading = "nodiscard, warn_unused_result, clang::warn_unused_result, gnu::warn_unused_result";
1118 Clang supports the ability to diagnose when the results of a function call
1119 expression are discarded under suspicious circumstances. A diagnostic is
1120 generated when a function or its return type is marked with ``[[nodiscard]]``
1121 (or ``__attribute__((warn_unused_result))``) and the function call appears as a
1122 potentially-evaluated discarded-value expression that is not explicitly cast to
1126 struct [[nodiscard]] error_info { /*...*/ };
1127 error_info enable_missile_safety_mode();
1129 void launch_missiles();
1130 void test_missiles() {
1131 enable_missile_safety_mode(); // diagnoses
1135 void f() { foo(); } // Does not diagnose, error_info is a reference.
1139 def FallthroughDocs : Documentation {
1140 let Category = DocCatStmt;
1141 let Heading = "fallthrough, clang::fallthrough";
1143 The ``fallthrough`` (or ``clang::fallthrough``) attribute is used
1144 to annotate intentional fall-through
1145 between switch labels. It can only be applied to a null statement placed at a
1146 point of execution between any statement and the next switch label. It is
1147 common to mark these places with a specific comment, but this attribute is
1148 meant to replace comments with a more strict annotation, which can be checked
1149 by the compiler. This attribute doesn't change semantics of the code and can
1150 be used wherever an intended fall-through occurs. It is designed to mimic
1151 control-flow statements like ``break;``, so it can be placed in most places
1152 where ``break;`` can, but only if there are no statements on the execution path
1153 between it and the next switch label.
1155 By default, Clang does not warn on unannotated fallthrough from one ``switch``
1156 case to another. Diagnostics on fallthrough without a corresponding annotation
1157 can be enabled with the ``-Wimplicit-fallthrough`` argument.
1163 // compile with -Wimplicit-fallthrough
1166 case 33: // no warning: no statements between case labels
1168 case 44: // warning: unannotated fall-through
1170 [[clang::fallthrough]];
1171 case 55: // no warning
1178 [[clang::fallthrough]];
1180 case 66: // no warning
1182 [[clang::fallthrough]]; // warning: fallthrough annotation does not
1183 // directly precede case label
1185 case 77: // warning: unannotated fall-through
1191 def ARMInterruptDocs : Documentation {
1192 let Category = DocCatFunction;
1194 Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
1195 ARM targets. This attribute may be attached to a function definition and
1196 instructs the backend to generate appropriate function entry/exit code so that
1197 it can be used directly as an interrupt service routine.
1199 The parameter passed to the interrupt attribute is optional, but if
1200 provided it must be a string literal with one of the following values: "IRQ",
1201 "FIQ", "SWI", "ABORT", "UNDEF".
1203 The semantics are as follows:
1205 - If the function is AAPCS, Clang instructs the backend to realign the stack to
1206 8 bytes on entry. This is a general requirement of the AAPCS at public
1207 interfaces, but may not hold when an exception is taken. Doing this allows
1208 other AAPCS functions to be called.
1209 - If the CPU is M-class this is all that needs to be done since the architecture
1210 itself is designed in such a way that functions obeying the normal AAPCS ABI
1211 constraints are valid exception handlers.
1212 - If the CPU is not M-class, the prologue and epilogue are modified to save all
1213 non-banked registers that are used, so that upon return the user-mode state
1214 will not be corrupted. Note that to avoid unnecessary overhead, only
1215 general-purpose (integer) registers are saved in this way. If VFP operations
1216 are needed, that state must be saved manually.
1218 Specifically, interrupt kinds other than "FIQ" will save all core registers
1219 except "lr" and "sp". "FIQ" interrupts will save r0-r7.
1220 - If the CPU is not M-class, the return instruction is changed to one of the
1221 canonical sequences permitted by the architecture for exception return. Where
1222 possible the function itself will make the necessary "lr" adjustments so that
1223 the "preferred return address" is selected.
1225 Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
1226 handler, where the offset from "lr" to the preferred return address depends on
1227 the execution state of the code which generated the exception. In this case
1228 a sequence equivalent to "movs pc, lr" will be used.
1232 def MipsInterruptDocs : Documentation {
1233 let Category = DocCatFunction;
1235 Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on
1236 MIPS targets. This attribute may be attached to a function definition and instructs
1237 the backend to generate appropriate function entry/exit code so that it can be used
1238 directly as an interrupt service routine.
1240 By default, the compiler will produce a function prologue and epilogue suitable for
1241 an interrupt service routine that handles an External Interrupt Controller (eic)
1242 generated interrupt. This behaviour can be explicitly requested with the "eic"
1245 Otherwise, for use with vectored interrupt mode, the argument passed should be
1246 of the form "vector=LEVEL" where LEVEL is one of the following values:
1247 "sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
1248 then set the interrupt mask to the corresponding level which will mask all
1249 interrupts up to and including the argument.
1251 The semantics are as follows:
1253 - The prologue is modified so that the Exception Program Counter (EPC) and
1254 Status coprocessor registers are saved to the stack. The interrupt mask is
1255 set so that the function can only be interrupted by a higher priority
1256 interrupt. The epilogue will restore the previous values of EPC and Status.
1258 - The prologue and epilogue are modified to save and restore all non-kernel
1259 registers as necessary.
1261 - The FPU is disabled in the prologue, as the floating pointer registers are not
1262 spilled to the stack.
1264 - The function return sequence is changed to use an exception return instruction.
1266 - The parameter sets the interrupt mask for the function corresponding to the
1267 interrupt level specified. If no mask is specified the interrupt mask
1272 def AVRInterruptDocs : Documentation {
1273 let Category = DocCatFunction;
1275 Clang supports the GNU style ``__attribute__((interrupt))`` attribute on
1276 AVR targets. This attribute may be attached to a function definition and instructs
1277 the backend to generate appropriate function entry/exit code so that it can be used
1278 directly as an interrupt service routine.
1280 On the AVR, the hardware globally disables interrupts when an interrupt is executed.
1281 The first instruction of an interrupt handler declared with this attribute is a SEI
1282 instruction to re-enable interrupts. See also the signal attribute that
1283 does not insert a SEI instruction.
1287 def AVRSignalDocs : Documentation {
1288 let Category = DocCatFunction;
1290 Clang supports the GNU style ``__attribute__((signal))`` attribute on
1291 AVR targets. This attribute may be attached to a function definition and instructs
1292 the backend to generate appropriate function entry/exit code so that it can be used
1293 directly as an interrupt service routine.
1295 Interrupt handler functions defined with the signal attribute do not re-enable interrupts.
1299 def TargetDocs : Documentation {
1300 let Category = DocCatFunction;
1302 Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute.
1303 This attribute may be attached to a function definition and instructs
1304 the backend to use different code generation options than were passed on the
1307 The current set of options correspond to the existing "subtarget features" for
1308 the target with or without a "-mno-" in front corresponding to the absence
1309 of the feature, as well as ``arch="CPU"`` which will change the default "CPU"
1312 Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
1313 "avx", "xop" and largely correspond to the machine specific options handled by
1318 def DocCatAMDGPUAttributes : DocumentationCategory<"AMD GPU Attributes">;
1320 def AMDGPUFlatWorkGroupSizeDocs : Documentation {
1321 let Category = DocCatAMDGPUAttributes;
1323 The flat work-group size is the number of work-items in the work-group size
1324 specified when the kernel is dispatched. It is the product of the sizes of the
1325 x, y, and z dimension of the work-group.
1328 ``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the
1329 AMDGPU target. This attribute may be attached to a kernel function definition
1330 and is an optimization hint.
1332 ``<min>`` parameter specifies the minimum flat work-group size, and ``<max>``
1333 parameter specifies the maximum flat work-group size (must be greater than
1334 ``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0``
1335 as ``<min>, <max>`` implies the default behavior (``128, 256``).
1337 If specified, the AMDGPU target backend might be able to produce better machine
1338 code for barriers and perform scratch promotion by estimating available group
1341 An error will be given if:
1342 - Specified values violate subtarget specifications;
1343 - Specified values are not compatible with values provided through other
1348 def AMDGPUWavesPerEUDocs : Documentation {
1349 let Category = DocCatAMDGPUAttributes;
1351 A compute unit (CU) is responsible for executing the wavefronts of a work-group.
1352 It is composed of one or more execution units (EU), which are responsible for
1353 executing the wavefronts. An EU can have enough resources to maintain the state
1354 of more than one executing wavefront. This allows an EU to hide latency by
1355 switching between wavefronts in a similar way to symmetric multithreading on a
1356 CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
1357 resources used by a single wavefront have to be limited. For example, the number
1358 of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
1359 but can result in having to spill some register state to memory.
1361 Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))``
1362 attribute for the AMDGPU target. This attribute may be attached to a kernel
1363 function definition and is an optimization hint.
1365 ``<min>`` parameter specifies the requested minimum number of waves per EU, and
1366 *optional* ``<max>`` parameter specifies the requested maximum number of waves
1367 per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted,
1368 then there is no restriction on the maximum number of waves per EU other than
1369 the one dictated by the hardware for which the kernel is compiled. Passing
1370 ``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits).
1372 If specified, this attribute allows an advanced developer to tune the number of
1373 wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
1374 target backend can use this information to limit resources, such as number of
1375 SGPRs, number of VGPRs, size of available group and private memory segments, in
1376 such a way that guarantees that at least ``<min>`` wavefronts and at most
1377 ``<max>`` wavefronts are able to fit within the resources of an EU. Requesting
1378 more wavefronts can hide memory latency but limits available registers which
1379 can result in spilling. Requesting fewer wavefronts can help reduce cache
1380 thrashing, but can reduce memory latency hiding.
1382 This attribute controls the machine code generated by the AMDGPU target backend
1383 to ensure it is capable of meeting the requested values. However, when the
1384 kernel is executed, there may be other reasons that prevent meeting the request,
1385 for example, there may be wavefronts from other kernels executing on the EU.
1387 An error will be given if:
1388 - Specified values violate subtarget specifications;
1389 - Specified values are not compatible with values provided through other
1391 - The AMDGPU target backend is unable to create machine code that can meet the
1396 def AMDGPUNumSGPRNumVGPRDocs : Documentation {
1397 let Category = DocCatAMDGPUAttributes;
1399 Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
1400 ``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
1401 target. These attributes may be attached to a kernel function definition and are
1402 an optimization hint.
1404 If these attributes are specified, then the AMDGPU target backend will attempt
1405 to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
1406 number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
1407 allocation requirements or constraints of the subtarget. Passing ``0`` as
1408 ``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
1410 These attributes can be used to test the AMDGPU target backend. It is
1411 recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
1412 resources such as SGPRs and VGPRs since it is aware of the limits for different
1415 An error will be given if:
1416 - Specified values violate subtarget specifications;
1417 - Specified values are not compatible with values provided through other
1419 - The AMDGPU target backend is unable to create machine code that can meet the
1424 def DocCatCallingConvs : DocumentationCategory<"Calling Conventions"> {
1426 Clang supports several different calling conventions, depending on the target
1427 platform and architecture. The calling convention used for a function determines
1428 how parameters are passed, how results are returned to the caller, and other
1429 low-level details of calling a function.
1433 def PcsDocs : Documentation {
1434 let Category = DocCatCallingConvs;
1436 On ARM targets, this attribute can be used to select calling conventions
1437 similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and
1442 def RegparmDocs : Documentation {
1443 let Category = DocCatCallingConvs;
1445 On 32-bit x86 targets, the regparm attribute causes the compiler to pass
1446 the first three integer parameters in EAX, EDX, and ECX instead of on the
1447 stack. This attribute has no effect on variadic functions, and all parameters
1448 are passed via the stack as normal.
1452 def SysVABIDocs : Documentation {
1453 let Category = DocCatCallingConvs;
1455 On Windows x86_64 targets, this attribute changes the calling convention of a
1456 function to match the default convention used on Sys V targets such as Linux,
1457 Mac, and BSD. This attribute has no effect on other targets.
1461 def MSABIDocs : Documentation {
1462 let Category = DocCatCallingConvs;
1464 On non-Windows x86_64 targets, this attribute changes the calling convention of
1465 a function to match the default convention used on Windows x86_64. This
1466 attribute has no effect on Windows targets or non-x86_64 targets.
1470 def StdCallDocs : Documentation {
1471 let Category = DocCatCallingConvs;
1473 On 32-bit x86 targets, this attribute changes the calling convention of a
1474 function to clear parameters off of the stack on return. This convention does
1475 not support variadic calls or unprototyped functions in C, and has no effect on
1476 x86_64 targets. This calling convention is used widely by the Windows API and
1477 COM applications. See the documentation for `__stdcall`_ on MSDN.
1479 .. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx
1483 def FastCallDocs : Documentation {
1484 let Category = DocCatCallingConvs;
1486 On 32-bit x86 targets, this attribute changes the calling convention of a
1487 function to use ECX and EDX as register parameters and clear parameters off of
1488 the stack on return. This convention does not support variadic calls or
1489 unprototyped functions in C, and has no effect on x86_64 targets. This calling
1490 convention is supported primarily for compatibility with existing code. Users
1491 seeking register parameters should use the ``regparm`` attribute, which does
1492 not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN.
1494 .. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx
1498 def RegCallDocs : Documentation {
1499 let Category = DocCatCallingConvs;
1501 On x86 targets, this attribute changes the calling convention to
1502 `__regcall`_ convention. This convention aims to pass as many arguments
1503 as possible in registers. It also tries to utilize registers for the
1504 return value whenever it is possible.
1506 .. _`__regcall`: https://software.intel.com/en-us/node/693069
1510 def ThisCallDocs : Documentation {
1511 let Category = DocCatCallingConvs;
1513 On 32-bit x86 targets, this attribute changes the calling convention of a
1514 function to use ECX for the first parameter (typically the implicit ``this``
1515 parameter of C++ methods) and clear parameters off of the stack on return. This
1516 convention does not support variadic calls or unprototyped functions in C, and
1517 has no effect on x86_64 targets. See the documentation for `__thiscall`_ on
1520 .. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx
1524 def VectorCallDocs : Documentation {
1525 let Category = DocCatCallingConvs;
1527 On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
1528 convention of a function to pass vector parameters in SSE registers.
1530 On 32-bit x86 targets, this calling convention is similar to ``__fastcall``.
1531 The first two integer parameters are passed in ECX and EDX. Subsequent integer
1532 parameters are passed in memory, and callee clears the stack. On x86_64
1533 targets, the callee does *not* clear the stack, and integer parameters are
1534 passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
1537 On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
1538 passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
1539 passed in sequential SSE registers if enough are available. If AVX is enabled,
1540 256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
1541 cannot be passed in registers for any reason is passed by reference, which
1542 allows the caller to align the parameter memory.
1544 See the documentation for `__vectorcall`_ on MSDN for more details.
1546 .. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx
1550 def DocCatConsumed : DocumentationCategory<"Consumed Annotation Checking"> {
1552 Clang supports additional attributes for checking basic resource management
1553 properties, specifically for unique objects that have a single owning reference.
1554 The following attributes are currently supported, although **the implementation
1555 for these annotations is currently in development and are subject to change.**
1559 def SetTypestateDocs : Documentation {
1560 let Category = DocCatConsumed;
1562 Annotate methods that transition an object into a new state with
1563 ``__attribute__((set_typestate(new_state)))``. The new state must be
1564 unconsumed, consumed, or unknown.
1568 def CallableWhenDocs : Documentation {
1569 let Category = DocCatConsumed;
1571 Use ``__attribute__((callable_when(...)))`` to indicate what states a method
1572 may be called in. Valid states are unconsumed, consumed, or unknown. Each
1573 argument to this attribute must be a quoted string. E.g.:
1575 ``__attribute__((callable_when("unconsumed", "unknown")))``
1579 def TestTypestateDocs : Documentation {
1580 let Category = DocCatConsumed;
1582 Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
1583 returns true if the object is in the specified state..
1587 def ParamTypestateDocs : Documentation {
1588 let Category = DocCatConsumed;
1590 This attribute specifies expectations about function parameters. Calls to an
1591 function with annotated parameters will issue a warning if the corresponding
1592 argument isn't in the expected state. The attribute is also used to set the
1593 initial state of the parameter when analyzing the function's body.
1597 def ReturnTypestateDocs : Documentation {
1598 let Category = DocCatConsumed;
1600 The ``return_typestate`` attribute can be applied to functions or parameters.
1601 When applied to a function the attribute specifies the state of the returned
1602 value. The function's body is checked to ensure that it always returns a value
1603 in the specified state. On the caller side, values returned by the annotated
1604 function are initialized to the given state.
1606 When applied to a function parameter it modifies the state of an argument after
1607 a call to the function returns. The function's body is checked to ensure that
1608 the parameter is in the expected state before returning.
1612 def ConsumableDocs : Documentation {
1613 let Category = DocCatConsumed;
1615 Each ``class`` that uses any of the typestate annotations must first be marked
1616 using the ``consumable`` attribute. Failure to do so will result in a warning.
1618 This attribute accepts a single parameter that must be one of the following:
1619 ``unknown``, ``consumed``, or ``unconsumed``.
1623 def NoSanitizeDocs : Documentation {
1624 let Category = DocCatFunction;
1626 Use the ``no_sanitize`` attribute on a function declaration to specify
1627 that a particular instrumentation or set of instrumentations should not be
1628 applied to that function. The attribute takes a list of string literals,
1629 which have the same meaning as values accepted by the ``-fno-sanitize=``
1630 flag. For example, ``__attribute__((no_sanitize("address", "thread")))``
1631 specifies that AddressSanitizer and ThreadSanitizer should not be applied
1634 See :ref:`Controlling Code Generation <controlling-code-generation>` for a
1635 full list of supported sanitizer flags.
1639 def NoSanitizeAddressDocs : Documentation {
1640 let Category = DocCatFunction;
1641 // This function has multiple distinct spellings, and so it requires a custom
1642 // heading to be specified. The most common spelling is sufficient.
1643 let Heading = "no_sanitize_address (no_address_safety_analysis, gnu::no_address_safety_analysis, gnu::no_sanitize_address)";
1645 .. _langext-address_sanitizer:
1647 Use ``__attribute__((no_sanitize_address))`` on a function declaration to
1648 specify that address safety instrumentation (e.g. AddressSanitizer) should
1649 not be applied to that function.
1653 def NoSanitizeThreadDocs : Documentation {
1654 let Category = DocCatFunction;
1655 let Heading = "no_sanitize_thread";
1657 .. _langext-thread_sanitizer:
1659 Use ``__attribute__((no_sanitize_thread))`` on a function declaration to
1660 specify that checks for data races on plain (non-atomic) memory accesses should
1661 not be inserted by ThreadSanitizer. The function is still instrumented by the
1662 tool to avoid false positives and provide meaningful stack traces.
1666 def NoSanitizeMemoryDocs : Documentation {
1667 let Category = DocCatFunction;
1668 let Heading = "no_sanitize_memory";
1670 .. _langext-memory_sanitizer:
1672 Use ``__attribute__((no_sanitize_memory))`` on a function declaration to
1673 specify that checks for uninitialized memory should not be inserted
1674 (e.g. by MemorySanitizer). The function may still be instrumented by the tool
1675 to avoid false positives in other places.
1679 def DocCatTypeSafety : DocumentationCategory<"Type Safety Checking"> {
1681 Clang supports additional attributes to enable checking type safety properties
1682 that can't be enforced by the C type system. To see warnings produced by these
1683 checks, ensure that -Wtype-safety is enabled. Use cases include:
1685 * MPI library implementations, where these attributes enable checking that
1686 the buffer type matches the passed ``MPI_Datatype``;
1687 * for HDF5 library there is a similar use case to MPI;
1688 * checking types of variadic functions' arguments for functions like
1689 ``fcntl()`` and ``ioctl()``.
1691 You can detect support for these attributes with ``__has_attribute()``. For
1696 #if defined(__has_attribute)
1697 # if __has_attribute(argument_with_type_tag) && \
1698 __has_attribute(pointer_with_type_tag) && \
1699 __has_attribute(type_tag_for_datatype)
1700 # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
1701 /* ... other macros ... */
1705 #if !defined(ATTR_MPI_PWT)
1706 # define ATTR_MPI_PWT(buffer_idx, type_idx)
1709 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
1714 def ArgumentWithTypeTagDocs : Documentation {
1715 let Category = DocCatTypeSafety;
1716 let Heading = "argument_with_type_tag";
1718 Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
1719 type_tag_idx)))`` on a function declaration to specify that the function
1720 accepts a type tag that determines the type of some other argument.
1722 This attribute is primarily useful for checking arguments of variadic functions
1723 (``pointer_with_type_tag`` can be used in most non-variadic cases).
1725 In the attribute prototype above:
1726 * ``arg_kind`` is an identifier that should be used when annotating all
1727 applicable type tags.
1728 * ``arg_idx`` provides the position of a function argument. The expected type of
1729 this function argument will be determined by the function argument specified
1730 by ``type_tag_idx``. In the code example below, "3" means that the type of the
1731 function's third argument will be determined by ``type_tag_idx``.
1732 * ``type_tag_idx`` provides the position of a function argument. This function
1733 argument will be a type tag. The type tag will determine the expected type of
1734 the argument specified by ``arg_idx``. In the code example below, "2" means
1735 that the type tag associated with the function's second argument should agree
1736 with the type of the argument specified by ``arg_idx``.
1742 int fcntl(int fd, int cmd, ...)
1743 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
1744 // The function's second argument will be a type tag; this type tag will
1745 // determine the expected type of the function's third argument.
1749 def PointerWithTypeTagDocs : Documentation {
1750 let Category = DocCatTypeSafety;
1751 let Heading = "pointer_with_type_tag";
1753 Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
1754 on a function declaration to specify that the function accepts a type tag that
1755 determines the pointee type of some other pointer argument.
1757 In the attribute prototype above:
1758 * ``ptr_kind`` is an identifier that should be used when annotating all
1759 applicable type tags.
1760 * ``ptr_idx`` provides the position of a function argument; this function
1761 argument will have a pointer type. The expected pointee type of this pointer
1762 type will be determined by the function argument specified by
1763 ``type_tag_idx``. In the code example below, "1" means that the pointee type
1764 of the function's first argument will be determined by ``type_tag_idx``.
1765 * ``type_tag_idx`` provides the position of a function argument; this function
1766 argument will be a type tag. The type tag will determine the expected pointee
1767 type of the pointer argument specified by ``ptr_idx``. In the code example
1768 below, "3" means that the type tag associated with the function's third
1769 argument should agree with the pointee type of the pointer argument specified
1776 typedef int MPI_Datatype;
1777 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
1778 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
1779 // The function's 3rd argument will be a type tag; this type tag will
1780 // determine the expected pointee type of the function's 1st argument.
1784 def TypeTagForDatatypeDocs : Documentation {
1785 let Category = DocCatTypeSafety;
1787 When declaring a variable, use
1788 ``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that
1789 is tied to the ``type`` argument given to the attribute.
1791 In the attribute prototype above:
1792 * ``kind`` is an identifier that should be used when annotating all applicable
1794 * ``type`` indicates the name of the type.
1796 Clang supports annotating type tags of two forms.
1798 * **Type tag that is a reference to a declared identifier.**
1799 Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that
1804 typedef int MPI_Datatype;
1805 extern struct mpi_datatype mpi_datatype_int
1806 __attribute__(( type_tag_for_datatype(mpi,int) ));
1807 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
1808 // &mpi_datatype_int is a type tag. It is tied to type "int".
1810 * **Type tag that is an integral literal.**
1811 Declare a ``static const`` variable with an initializer value and attach
1812 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration:
1816 typedef int MPI_Datatype;
1817 static const MPI_Datatype mpi_datatype_int
1818 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
1819 #define MPI_INT ((MPI_Datatype) 42)
1820 // The number 42 is a type tag. It is tied to type "int".
1823 The ``type_tag_for_datatype`` attribute also accepts an optional third argument
1824 that determines how the type of the function argument specified by either
1825 ``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type
1826 tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the
1827 function argument specified by ``arg_idx`` is compared against the type
1828 associated with the type tag. Also recall that for the ``pointer_with_type_tag``
1829 attribute, the pointee type of the function argument specified by ``ptr_idx`` is
1830 compared against the type associated with the type tag.) There are two supported
1831 values for this optional third argument:
1833 * ``layout_compatible`` will cause types to be compared according to
1834 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
1835 layout-compatibility rules for two standard-layout struct types and for two
1836 standard-layout union types). This is useful when creating a type tag
1837 associated with a struct or union type. For example:
1842 typedef int MPI_Datatype;
1843 struct internal_mpi_double_int { double d; int i; };
1844 extern struct mpi_datatype mpi_datatype_double_int
1845 __attribute__(( type_tag_for_datatype(mpi,
1846 struct internal_mpi_double_int, layout_compatible) ));
1848 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
1850 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
1851 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
1854 struct my_pair { double a; int b; };
1855 struct my_pair *buffer;
1856 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
1857 // layout of my_pair is
1858 // compatible with that of
1859 // internal_mpi_double_int
1861 struct my_int_pair { int a; int b; }
1862 struct my_int_pair *buffer2;
1863 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
1864 // layout of my_int_pair
1865 // does not match that of
1866 // internal_mpi_double_int
1868 * ``must_be_null`` specifies that the function argument specified by either
1869 ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for
1870 the ``pointer_with_type_tag`` attribute) should be a null pointer constant.
1871 The second argument to the ``type_tag_for_datatype`` attribute is ignored. For
1877 typedef int MPI_Datatype;
1878 extern struct mpi_datatype mpi_datatype_null
1879 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
1881 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
1882 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
1883 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
1886 struct my_pair { double a; int b; };
1887 struct my_pair *buffer;
1888 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
1889 // was specified but buffer
1890 // is not a null pointer
1894 def FlattenDocs : Documentation {
1895 let Category = DocCatFunction;
1897 The ``flatten`` attribute causes calls within the attributed function to
1898 be inlined unless it is impossible to do so, for example if the body of the
1899 callee is unavailable or if the callee has the ``noinline`` attribute.
1903 def FormatDocs : Documentation {
1904 let Category = DocCatFunction;
1907 Clang supports the ``format`` attribute, which indicates that the function
1908 accepts a ``printf`` or ``scanf``-like format string and corresponding
1909 arguments or a ``va_list`` that contains these arguments.
1911 Please see `GCC documentation about format attribute
1912 <http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
1913 about attribute syntax.
1915 Clang implements two kinds of checks with this attribute.
1917 #. Clang checks that the function with the ``format`` attribute is called with
1918 a format string that uses format specifiers that are allowed, and that
1919 arguments match the format string. This is the ``-Wformat`` warning, it is
1922 #. Clang checks that the format string argument is a literal string. This is
1923 the ``-Wformat-nonliteral`` warning, it is off by default.
1925 Clang implements this mostly the same way as GCC, but there is a difference
1926 for functions that accept a ``va_list`` argument (for example, ``vprintf``).
1927 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
1928 functions. Clang does not warn if the format string comes from a function
1929 parameter, where the function is annotated with a compatible attribute,
1930 otherwise it warns. For example:
1934 __attribute__((__format__ (__scanf__, 1, 3)))
1935 void foo(const char* s, char *buf, ...) {
1939 vprintf(s, ap); // warning: format string is not a string literal
1942 In this case we warn because ``s`` contains a format string for a
1943 ``scanf``-like function, but it is passed to a ``printf``-like function.
1945 If the attribute is removed, clang still warns, because the format string is
1946 not a string literal.
1952 __attribute__((__format__ (__printf__, 1, 3)))
1953 void foo(const char* s, char *buf, ...) {
1957 vprintf(s, ap); // warning
1960 In this case Clang does not warn because the format string ``s`` and
1961 the corresponding arguments are annotated. If the arguments are
1962 incorrect, the caller of ``foo`` will receive a warning.
1966 def AlignValueDocs : Documentation {
1967 let Category = DocCatType;
1969 The align_value attribute can be added to the typedef of a pointer type or the
1970 declaration of a variable of pointer or reference type. It specifies that the
1971 pointer will point to, or the reference will bind to, only objects with at
1972 least the provided alignment. This alignment value must be some positive power
1977 typedef double * aligned_double_ptr __attribute__((align_value(64)));
1978 void foo(double & x __attribute__((align_value(128)),
1979 aligned_double_ptr y) { ... }
1981 If the pointer value does not have the specified alignment at runtime, the
1982 behavior of the program is undefined.
1986 def FlagEnumDocs : Documentation {
1987 let Category = DocCatType;
1989 This attribute can be added to an enumerator to signal to the compiler that it
1990 is intended to be used as a flag type. This will cause the compiler to assume
1991 that the range of the type includes all of the values that you can get by
1992 manipulating bits of the enumerator when issuing warnings.
1996 def EnumExtensibilityDocs : Documentation {
1997 let Category = DocCatType;
1999 Attribute ``enum_extensibility`` is used to distinguish between enum definitions
2000 that are extensible and those that are not. The attribute can take either
2001 ``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the
2002 enum type takes a value that corresponds to one of the enumerators listed in the
2003 enum definition or, when the enum is annotated with ``flag_enum``, a value that
2004 can be constructed using values corresponding to the enumerators. ``open``
2005 indicates a variable of the enum type can take any values allowed by the
2006 standard and instructs clang to be more lenient when issuing warnings.
2010 enum __attribute__((enum_extensibility(closed))) ClosedEnum {
2014 enum __attribute__((enum_extensibility(open))) OpenEnum {
2018 enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
2019 C0 = 1 << 0, C1 = 1 << 1
2022 enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
2023 D0 = 1 << 0, D1 = 1 << 1
2029 enum ClosedFlagEnum cfe;
2030 enum OpenFlagEnum ofe;
2032 ce = A1; // no warnings
2033 ce = 100; // warning issued
2034 oe = B1; // no warnings
2035 oe = 100; // no warnings
2036 cfe = C0 | C1; // no warnings
2037 cfe = C0 | C1 | 4; // warning issued
2038 ofe = D0 | D1; // no warnings
2039 ofe = D0 | D1 | 4; // no warnings
2045 def EmptyBasesDocs : Documentation {
2046 let Category = DocCatType;
2048 The empty_bases attribute permits the compiler to utilize the
2049 empty-base-optimization more frequently.
2050 This attribute only applies to struct, class, and union types.
2051 It is only supported when using the Microsoft C++ ABI.
2055 def LayoutVersionDocs : Documentation {
2056 let Category = DocCatType;
2058 The layout_version attribute requests that the compiler utilize the class
2059 layout rules of a particular compiler version.
2060 This attribute only applies to struct, class, and union types.
2061 It is only supported when using the Microsoft C++ ABI.
2065 def MSInheritanceDocs : Documentation {
2066 let Category = DocCatType;
2067 let Heading = "__single_inhertiance, __multiple_inheritance, __virtual_inheritance";
2069 This collection of keywords is enabled under ``-fms-extensions`` and controls
2070 the pointer-to-member representation used on ``*-*-win32`` targets.
2072 The ``*-*-win32`` targets utilize a pointer-to-member representation which
2073 varies in size and alignment depending on the definition of the underlying
2076 However, this is problematic when a forward declaration is only available and
2077 no definition has been made yet. In such cases, Clang is forced to utilize the
2078 most general representation that is available to it.
2080 These keywords make it possible to use a pointer-to-member representation other
2081 than the most general one regardless of whether or not the definition will ever
2082 be present in the current translation unit.
2084 This family of keywords belong between the ``class-key`` and ``class-name``:
2088 struct __single_inheritance S;
2092 This keyword can be applied to class templates but only has an effect when used
2093 on full specializations:
2097 template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
2098 template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
2099 template <> struct __single_inheritance A<int, float>;
2101 Note that choosing an inheritance model less general than strictly necessary is
2106 struct __multiple_inheritance S; // error: inheritance model does not match definition
2112 def MSNoVTableDocs : Documentation {
2113 let Category = DocCatType;
2115 This attribute can be added to a class declaration or definition to signal to
2116 the compiler that constructors and destructors will not reference the virtual
2117 function table. It is only supported when using the Microsoft C++ ABI.
2121 def OptnoneDocs : Documentation {
2122 let Category = DocCatFunction;
2124 The ``optnone`` attribute suppresses essentially all optimizations
2125 on a function or method, regardless of the optimization level applied to
2126 the compilation unit as a whole. This is particularly useful when you
2127 need to debug a particular function, but it is infeasible to build the
2128 entire application without optimization. Avoiding optimization on the
2129 specified function can improve the quality of the debugging information
2132 This attribute is incompatible with the ``always_inline`` and ``minsize``
2137 def LoopHintDocs : Documentation {
2138 let Category = DocCatStmt;
2139 let Heading = "#pragma clang loop";
2141 The ``#pragma clang loop`` directive allows loop optimization hints to be
2142 specified for the subsequent loop. The directive allows vectorization,
2143 interleaving, and unrolling to be enabled or disabled. Vector width as well
2144 as interleave and unrolling count can be manually specified. See
2145 `language extensions
2146 <http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
2151 def UnrollHintDocs : Documentation {
2152 let Category = DocCatStmt;
2153 let Heading = "#pragma unroll, #pragma nounroll";
2155 Loop unrolling optimization hints can be specified with ``#pragma unroll`` and
2156 ``#pragma nounroll``. The pragma is placed immediately before a for, while,
2157 do-while, or c++11 range-based for loop.
2159 Specifying ``#pragma unroll`` without a parameter directs the loop unroller to
2160 attempt to fully unroll the loop if the trip count is known at compile time and
2161 attempt to partially unroll the loop if the trip count is not known at compile
2171 Specifying the optional parameter, ``#pragma unroll _value_``, directs the
2172 unroller to unroll the loop ``_value_`` times. The parameter may optionally be
2173 enclosed in parentheses:
2187 Specifying ``#pragma nounroll`` indicates that the loop should not be unrolled:
2196 ``#pragma unroll`` and ``#pragma unroll _value_`` have identical semantics to
2197 ``#pragma clang loop unroll(full)`` and
2198 ``#pragma clang loop unroll_count(_value_)`` respectively. ``#pragma nounroll``
2199 is equivalent to ``#pragma clang loop unroll(disable)``. See
2200 `language extensions
2201 <http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
2202 for further details including limitations of the unroll hints.
2206 def OpenCLUnrollHintDocs : Documentation {
2207 let Category = DocCatStmt;
2208 let Heading = "__attribute__((opencl_unroll_hint))";
2210 The opencl_unroll_hint attribute qualifier can be used to specify that a loop
2211 (for, while and do loops) can be unrolled. This attribute qualifier can be
2212 used to specify full unrolling or partial unrolling by a specified amount.
2213 This is a compiler hint and the compiler may ignore this directive. See
2214 `OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_
2215 s6.11.5 for details.
2219 def OpenCLAccessDocs : Documentation {
2220 let Category = DocCatStmt;
2221 let Heading = "__read_only, __write_only, __read_write (read_only, write_only, read_write)";
2223 The access qualifiers must be used with image object arguments or pipe arguments
2224 to declare if they are being read or written by a kernel or function.
2226 The read_only/__read_only, write_only/__write_only and read_write/__read_write
2227 names are reserved for use as access qualifiers and shall not be used otherwise.
2232 foo (read_only image2d_t imageA,
2233 write_only image2d_t imageB) {
2237 In the above example imageA is a read-only 2D image object, and imageB is a
2238 write-only 2D image object.
2240 The read_write (or __read_write) qualifier can not be used with pipe.
2242 More details can be found in the OpenCL C language Spec v2.0, Section 6.6.
2246 def DocOpenCLAddressSpaces : DocumentationCategory<"OpenCL Address Spaces"> {
2248 The address space qualifier may be used to specify the region of memory that is
2249 used to allocate the object. OpenCL supports the following address spaces:
2250 __generic(generic), __global(global), __local(local), __private(private),
2251 __constant(constant).
2255 __constant int c = ...;
2257 __generic int* foo(global int* g) {
2264 More details can be found in the OpenCL C language Spec v2.0, Section 6.5.
2268 def OpenCLAddressSpaceGenericDocs : Documentation {
2269 let Category = DocOpenCLAddressSpaces;
2271 The generic address space attribute is only available with OpenCL v2.0 and later.
2272 It can be used with pointer types. Variables in global and local scope and
2273 function parameters in non-kernel functions can have the generic address space
2274 type attribute. It is intended to be a placeholder for any other address space
2275 except for '__constant' in OpenCL code which can be used with multiple address
2280 def OpenCLAddressSpaceConstantDocs : Documentation {
2281 let Category = DocOpenCLAddressSpaces;
2283 The constant address space attribute signals that an object is located in
2284 a constant (non-modifiable) memory region. It is available to all work items.
2285 Any type can be annotated with the constant address space attribute. Objects
2286 with the constant address space qualifier can be declared in any scope and must
2287 have an initializer.
2291 def OpenCLAddressSpaceGlobalDocs : Documentation {
2292 let Category = DocOpenCLAddressSpaces;
2294 The global address space attribute specifies that an object is allocated in
2295 global memory, which is accessible by all work items. The content stored in this
2296 memory area persists between kernel executions. Pointer types to the global
2297 address space are allowed as function parameters or local variables. Starting
2298 with OpenCL v2.0, the global address space can be used with global (program
2299 scope) variables and static local variable as well.
2303 def OpenCLAddressSpaceLocalDocs : Documentation {
2304 let Category = DocOpenCLAddressSpaces;
2306 The local address space specifies that an object is allocated in the local (work
2307 group) memory area, which is accessible to all work items in the same work
2308 group. The content stored in this memory region is not accessible after
2309 the kernel execution ends. In a kernel function scope, any variable can be in
2310 the local address space. In other scopes, only pointer types to the local address
2311 space are allowed. Local address space variables cannot have an initializer.
2315 def OpenCLAddressSpacePrivateDocs : Documentation {
2316 let Category = DocOpenCLAddressSpaces;
2318 The private address space specifies that an object is allocated in the private
2319 (work item) memory. Other work items cannot access the same memory area and its
2320 content is destroyed after work item execution ends. Local variables can be
2321 declared in the private address space. Function arguments are always in the
2322 private address space. Kernel function arguments of a pointer or an array type
2323 cannot point to the private address space.
2327 def OpenCLNoSVMDocs : Documentation {
2328 let Category = DocCatVariable;
2330 OpenCL 2.0 supports the optional ``__attribute__((nosvm))`` qualifier for
2331 pointer variable. It informs the compiler that the pointer does not refer
2332 to a shared virtual memory region. See OpenCL v2.0 s6.7.2 for details.
2334 Since it is not widely used and has been removed from OpenCL 2.1, it is ignored
2338 def NullabilityDocs : DocumentationCategory<"Nullability Attributes"> {
2340 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``).
2342 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:
2346 // No meaningful result when 'ptr' is null (here, it happens to be undefined behavior).
2347 int fetch(int * _Nonnull ptr) { return *ptr; }
2349 // 'ptr' may be null.
2350 int fetch_or_zero(int * _Nullable ptr) {
2351 return ptr ? *ptr : 0;
2354 // A nullable pointer to non-null pointers to const characters.
2355 const char *join_strings(const char * _Nonnull * _Nullable strings, unsigned n);
2357 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:
2359 .. code-block:: objective-c
2361 @interface NSView : NSResponder
2362 - (nullable NSView *)ancestorSharedWithView:(nonnull NSView *)aView;
2363 @property (assign, nullable) NSView *superview;
2364 @property (readonly, nonnull) NSArray *subviews;
2369 def TypeNonNullDocs : Documentation {
2370 let Category = NullabilityDocs;
2372 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:
2376 int fetch(int * _Nonnull ptr);
2378 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.
2382 def TypeNullableDocs : Documentation {
2383 let Category = NullabilityDocs;
2385 The ``_Nullable`` nullability qualifier indicates that a value of the ``_Nullable`` pointer type can be null. For example, given:
2389 int fetch_or_zero(int * _Nullable ptr);
2391 a caller of ``fetch_or_zero`` can provide null.
2395 def TypeNullUnspecifiedDocs : Documentation {
2396 let Category = NullabilityDocs;
2398 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.
2402 def NonNullDocs : Documentation {
2403 let Category = NullabilityDocs;
2405 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:
2409 extern void * my_memcpy (void *dest, const void *src, size_t len)
2410 __attribute__((nonnull (1, 2)));
2412 Here, the ``nonnull`` attribute indicates that parameters 1 and 2
2413 cannot have a null value. Omitting the parenthesized list of parameter indices means that all parameters of pointer type cannot be null:
2417 extern void * my_memcpy (void *dest, const void *src, size_t len)
2418 __attribute__((nonnull));
2420 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:
2424 extern void * my_memcpy (void *dest __attribute__((nonnull)),
2425 const void *src __attribute__((nonnull)), size_t len);
2427 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.
2431 def ReturnsNonNullDocs : Documentation {
2432 let Category = NullabilityDocs;
2434 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:
2438 extern void * malloc (size_t size) __attribute__((returns_nonnull));
2440 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
2444 def NoAliasDocs : Documentation {
2445 let Category = DocCatFunction;
2447 The ``noalias`` attribute indicates that the only memory accesses inside
2448 function are loads and stores from objects pointed to by its pointer-typed
2449 arguments, with arbitrary offsets.
2453 def OMPDeclareSimdDocs : Documentation {
2454 let Category = DocCatFunction;
2455 let Heading = "#pragma omp declare simd";
2457 The `declare simd` construct can be applied to a function to enable the creation
2458 of one or more versions that can process multiple arguments using SIMD
2459 instructions from a single invocation in a SIMD loop. The `declare simd`
2460 directive is a declarative directive. There may be multiple `declare simd`
2461 directives for a function. The use of a `declare simd` construct on a function
2462 enables the creation of SIMD versions of the associated function that can be
2463 used to process multiple arguments from a single invocation from a SIMD loop
2465 The syntax of the `declare simd` construct is as follows:
2469 #pragma omp declare simd [clause[[,] clause] ...] new-line
2470 [#pragma omp declare simd [clause[[,] clause] ...] new-line]
2472 function definition or declaration
2474 where clause is one of the following:
2479 linear(argument-list[:constant-linear-step])
2480 aligned(argument-list[:alignment])
2481 uniform(argument-list)
2488 def OMPDeclareTargetDocs : Documentation {
2489 let Category = DocCatFunction;
2490 let Heading = "#pragma omp declare target";
2492 The `declare target` directive specifies that variables and functions are mapped
2493 to a device for OpenMP offload mechanism.
2495 The syntax of the declare target directive is as follows:
2499 #pragma omp declare target new-line
2500 declarations-definition-seq
2501 #pragma omp end declare target new-line
2505 def NotTailCalledDocs : Documentation {
2506 let Category = DocCatFunction;
2508 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``.
2510 For example, it prevents tail-call optimization in the following case:
2514 int __attribute__((not_tail_called)) foo1(int);
2517 return foo1(a); // No tail-call optimization on direct calls.
2520 However, it doesn't prevent tail-call optimization in this case:
2524 int __attribute__((not_tail_called)) foo1(int);
2527 int (*fn)(int) = &foo1;
2529 // not_tail_called has no effect on an indirect call even if the call can be
2530 // resolved at compile time.
2534 Marking virtual functions as ``not_tail_called`` is an error:
2540 // not_tail_called on a virtual function is an error.
2541 [[clang::not_tail_called]] virtual int foo1();
2545 // Non-virtual functions can be marked ``not_tail_called``.
2546 [[clang::not_tail_called]] int foo3();
2549 class Derived1 : public Base {
2551 int foo1() override;
2553 // not_tail_called on a virtual function is an error.
2554 [[clang::not_tail_called]] int foo2() override;
2559 def InternalLinkageDocs : Documentation {
2560 let Category = DocCatFunction;
2562 The ``internal_linkage`` attribute changes the linkage type of the declaration to internal.
2563 This is similar to C-style ``static``, but can be used on classes and class methods. When applied to a class definition,
2564 this attribute affects all methods and static data members of that class.
2565 This can be used to contain the ABI of a C++ library by excluding unwanted class methods from the export tables.
2569 def DisableTailCallsDocs : Documentation {
2570 let Category = DocCatFunction;
2572 The ``disable_tail_calls`` attribute instructs the backend to not perform tail call optimization inside the marked function.
2580 int foo(int a) __attribute__((disable_tail_calls)) {
2581 return callee(a); // This call is not tail-call optimized.
2584 Marking virtual functions as ``disable_tail_calls`` is legal.
2592 [[clang::disable_tail_calls]] virtual int foo1() {
2593 return callee(); // This call is not tail-call optimized.
2597 class Derived1 : public Base {
2599 int foo1() override {
2600 return callee(); // This call is tail-call optimized.
2607 def AnyX86InterruptDocs : Documentation {
2608 let Category = DocCatFunction;
2610 Clang supports the GNU style ``__attribute__((interrupt))`` attribute on
2611 x86/x86-64 targets.The compiler generates function entry and exit sequences
2612 suitable for use in an interrupt handler when this attribute is present.
2613 The 'IRET' instruction, instead of the 'RET' instruction, is used to return
2614 from interrupt or exception handlers. All registers, except for the EFLAGS
2615 register which is restored by the 'IRET' instruction, are preserved by the
2618 Any interruptible-without-stack-switch code must be compiled with
2619 -mno-red-zone since interrupt handlers can and will, because of the
2620 hardware design, touch the red zone.
2622 1. interrupt handler must be declared with a mandatory pointer argument:
2626 struct interrupt_frame
2635 __attribute__ ((interrupt))
2636 void f (struct interrupt_frame *frame) {
2640 2. exception handler:
2642 The exception handler is very similar to the interrupt handler with
2643 a different mandatory function signature:
2647 __attribute__ ((interrupt))
2648 void f (struct interrupt_frame *frame, uword_t error_code) {
2652 and compiler pops 'ERROR_CODE' off stack before the 'IRET' instruction.
2654 The exception handler should only be used for exceptions which push an
2655 error code and all other exceptions must use the interrupt handler.
2656 The system will crash if the wrong handler is used.
2660 def SwiftCallDocs : Documentation {
2661 let Category = DocCatVariable;
2663 The ``swiftcall`` attribute indicates that a function should be called
2664 using the Swift calling convention for a function or function pointer.
2666 The lowering for the Swift calling convention, as described by the Swift
2667 ABI documentation, occurs in multiple phases. The first, "high-level"
2668 phase breaks down the formal parameters and results into innately direct
2669 and indirect components, adds implicit paraameters for the generic
2670 signature, and assigns the context and error ABI treatments to parameters
2671 where applicable. The second phase breaks down the direct parameters
2672 and results from the first phase and assigns them to registers or the
2673 stack. The ``swiftcall`` convention only handles this second phase of
2674 lowering; the C function type must accurately reflect the results
2675 of the first phase, as follows:
2677 - Results classified as indirect by high-level lowering should be
2678 represented as parameters with the ``swift_indirect_result`` attribute.
2680 - Results classified as direct by high-level lowering should be represented
2683 - First, remove any empty direct results.
2685 - If there are no direct results, the C result type should be ``void``.
2687 - If there is one direct result, the C result type should be a type with
2688 the exact layout of that result type.
2690 - If there are a multiple direct results, the C result type should be
2691 a struct type with the exact layout of a tuple of those results.
2693 - Parameters classified as indirect by high-level lowering should be
2694 represented as parameters of pointer type.
2696 - Parameters classified as direct by high-level lowering should be
2697 omitted if they are empty types; otherwise, they should be represented
2698 as a parameter type with a layout exactly matching the layout of the
2699 Swift parameter type.
2701 - The context parameter, if present, should be represented as a trailing
2702 parameter with the ``swift_context`` attribute.
2704 - The error result parameter, if present, should be represented as a
2705 trailing parameter (always following a context parameter) with the
2706 ``swift_error_result`` attribute.
2708 ``swiftcall`` does not support variadic arguments or unprototyped functions.
2710 The parameter ABI treatment attributes are aspects of the function type.
2711 A function type which which applies an ABI treatment attribute to a
2712 parameter is a different type from an otherwise-identical function type
2713 that does not. A single parameter may not have multiple ABI treatment
2716 Support for this feature is target-dependent, although it should be
2717 supported on every target that Swift supports. Query for this support
2718 with ``__has_attribute(swiftcall)``. This implies support for the
2719 ``swift_context``, ``swift_error_result``, and ``swift_indirect_result``
2724 def SwiftContextDocs : Documentation {
2725 let Category = DocCatVariable;
2727 The ``swift_context`` attribute marks a parameter of a ``swiftcall``
2728 function as having the special context-parameter ABI treatment.
2730 This treatment generally passes the context value in a special register
2731 which is normally callee-preserved.
2733 A ``swift_context`` parameter must either be the last parameter or must be
2734 followed by a ``swift_error_result`` parameter (which itself must always be
2735 the last parameter).
2737 A context parameter must have pointer or reference type.
2741 def SwiftErrorResultDocs : Documentation {
2742 let Category = DocCatVariable;
2744 The ``swift_error_result`` attribute marks a parameter of a ``swiftcall``
2745 function as having the special error-result ABI treatment.
2747 This treatment generally passes the underlying error value in and out of
2748 the function through a special register which is normally callee-preserved.
2749 This is modeled in C by pretending that the register is addressable memory:
2751 - The caller appears to pass the address of a variable of pointer type.
2752 The current value of this variable is copied into the register before
2753 the call; if the call returns normally, the value is copied back into the
2756 - The callee appears to receive the address of a variable. This address
2757 is actually a hidden location in its own stack, initialized with the
2758 value of the register upon entry. When the function returns normally,
2759 the value in that hidden location is written back to the register.
2761 A ``swift_error_result`` parameter must be the last parameter, and it must be
2762 preceded by a ``swift_context`` parameter.
2764 A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some
2765 type T. Note that no qualifiers are permitted on the intermediate level.
2767 It is undefined behavior if the caller does not pass a pointer or
2768 reference to a valid object.
2770 The standard convention is that the error value itself (that is, the
2771 value stored in the apparent argument) will be null upon function entry,
2772 but this is not enforced by the ABI.
2776 def SwiftIndirectResultDocs : Documentation {
2777 let Category = DocCatVariable;
2779 The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall``
2780 function as having the special indirect-result ABI treatment.
2782 This treatment gives the parameter the target's normal indirect-result
2783 ABI treatment, which may involve passing it differently from an ordinary
2784 parameter. However, only the first indirect result will receive this
2785 treatment. Furthermore, low-level lowering may decide that a direct result
2786 must be returned indirectly; if so, this will take priority over the
2787 ``swift_indirect_result`` parameters.
2789 A ``swift_indirect_result`` parameter must either be the first parameter or
2790 follow another ``swift_indirect_result`` parameter.
2792 A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for
2793 some object type ``T``. If ``T`` is a complete type at the point of
2794 definition of a function, it is undefined behavior if the argument
2795 value does not point to storage of adequate size and alignment for a
2796 value of type ``T``.
2798 Making indirect results explicit in the signature allows C functions to
2799 directly construct objects into them without relying on language
2800 optimizations like C++'s named return value optimization (NRVO).
2804 def SuppressDocs : Documentation {
2805 let Category = DocCatStmt;
2807 The ``[[gsl::suppress]]`` attribute suppresses specific
2808 clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable
2809 way. The attribute can be attached to declarations, statements, and at
2814 [[gsl::suppress("Rh-public")]]
2817 [[gsl::suppress("type")]] {
2818 p = reinterpret_cast<int*>(7);
2822 [[clang::suppress("type", "bounds")]];
2826 .. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement
2830 def AbiTagsDocs : Documentation {
2831 let Category = DocCatFunction;
2833 The ``abi_tag`` attribute can be applied to a function, variable, class or
2834 inline namespace declaration to modify the mangled name of the entity. It gives
2835 the ability to distinguish between different versions of the same entity but
2836 with different ABI versions supported. For example, a newer version of a class
2837 could have a different set of data members and thus have a different size. Using
2838 the ``abi_tag`` attribute, it is possible to have different mangled names for
2839 a global variable of the class type. Therefor, the old code could keep using
2840 the old manged name and the new code will use the new mangled name with tags.
2844 def PreserveMostDocs : Documentation {
2845 let Category = DocCatCallingConvs;
2847 On X86-64 and AArch64 targets, this attribute changes the calling convention of
2848 a function. The ``preserve_most`` calling convention attempts to make the code
2849 in the caller as unintrusive as possible. This convention behaves identically
2850 to the ``C`` calling convention on how arguments and return values are passed,
2851 but it uses a different set of caller/callee-saved registers. This alleviates
2852 the burden of saving and recovering a large register set before and after the
2853 call in the caller. If the arguments are passed in callee-saved registers,
2854 then they will be preserved by the callee across the call. This doesn't
2855 apply for values returned in callee-saved registers.
2857 - On X86-64 the callee preserves all general purpose registers, except for
2858 R11. R11 can be used as a scratch register. Floating-point registers
2859 (XMMs/YMMs) are not preserved and need to be saved by the caller.
2861 The idea behind this convention is to support calls to runtime functions
2862 that have a hot path and a cold path. The hot path is usually a small piece
2863 of code that doesn't use many registers. The cold path might need to call out to
2864 another function and therefore only needs to preserve the caller-saved
2865 registers, which haven't already been saved by the caller. The
2866 `preserve_most` calling convention is very similar to the ``cold`` calling
2867 convention in terms of caller/callee-saved registers, but they are used for
2868 different types of function calls. ``coldcc`` is for function calls that are
2869 rarely executed, whereas `preserve_most` function calls are intended to be
2870 on the hot path and definitely executed a lot. Furthermore ``preserve_most``
2871 doesn't prevent the inliner from inlining the function call.
2873 This calling convention will be used by a future version of the Objective-C
2874 runtime and should therefore still be considered experimental at this time.
2875 Although this convention was created to optimize certain runtime calls to
2876 the Objective-C runtime, it is not limited to this runtime and might be used
2877 by other runtimes in the future too. The current implementation only
2878 supports X86-64 and AArch64, but the intention is to support more architectures
2883 def PreserveAllDocs : Documentation {
2884 let Category = DocCatCallingConvs;
2886 On X86-64 and AArch64 targets, this attribute changes the calling convention of
2887 a function. The ``preserve_all`` calling convention attempts to make the code
2888 in the caller even less intrusive than the ``preserve_most`` calling convention.
2889 This calling convention also behaves identical to the ``C`` calling convention
2890 on how arguments and return values are passed, but it uses a different set of
2891 caller/callee-saved registers. This removes the burden of saving and
2892 recovering a large register set before and after the call in the caller. If
2893 the arguments are passed in callee-saved registers, then they will be
2894 preserved by the callee across the call. This doesn't apply for values
2895 returned in callee-saved registers.
2897 - On X86-64 the callee preserves all general purpose registers, except for
2898 R11. R11 can be used as a scratch register. Furthermore it also preserves
2899 all floating-point registers (XMMs/YMMs).
2901 The idea behind this convention is to support calls to runtime functions
2902 that don't need to call out to any other functions.
2904 This calling convention, like the ``preserve_most`` calling convention, will be
2905 used by a future version of the Objective-C runtime and should be considered
2906 experimental at this time.
2910 def DeprecatedDocs : Documentation {
2911 let Category = DocCatFunction;
2913 The ``deprecated`` attribute can be applied to a function, a variable, or a
2914 type. This is useful when identifying functions, variables, or types that are
2915 expected to be removed in a future version of a program.
2917 Consider the function declaration for a hypothetical function ``f``:
2921 void f(void) __attribute__((deprecated("message", "replacement")));
2923 When spelled as `__attribute__((deprecated))`, the deprecated attribute can have
2924 two optional string arguments. The first one is the message to display when
2925 emitting the warning; the second one enables the compiler to provide a Fix-It
2926 to replace the deprecated name with a new name. Otherwise, when spelled as
2927 `[[gnu::deprecated]] or [[deprecated]]`, the attribute can have one optional
2928 string argument which is the message to display when emitting the warning.
2932 def IFuncDocs : Documentation {
2933 let Category = DocCatFunction;
2935 ``__attribute__((ifunc("resolver")))`` is used to mark that the address of a declaration should be resolved at runtime by calling a resolver function.
2937 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 take no arguments and return a pointer.
2939 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.
2941 Not all targets support this attribute. ELF targets support this attribute when using binutils v2.20.1 or higher and glibc v2.11.1 or higher. Non-ELF targets currently do not support this attribute.
2945 def LTOVisibilityDocs : Documentation {
2946 let Category = DocCatType;
2948 See :doc:`LTOVisibility`.
2952 def RenderScriptKernelAttributeDocs : Documentation {
2953 let Category = DocCatFunction;
2955 ``__attribute__((kernel))`` is used to mark a ``kernel`` function in
2958 In RenderScript, ``kernel`` functions are used to express data-parallel
2959 computations. The RenderScript runtime efficiently parallelizes ``kernel``
2960 functions to run on computational resources such as multi-core CPUs and GPUs.
2961 See the RenderScript_ documentation for more information.
2963 .. _RenderScript: https://developer.android.com/guide/topics/renderscript/compute.html
2967 def XRayDocs : Documentation {
2968 let Category = DocCatFunction;
2969 let Heading = "xray_always_instrument (clang::xray_always_instrument), xray_never_instrument (clang::xray_never_instrument), xray_log_args (clang::xray_log_args)";
2971 ``__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.
2973 Conversely, ``__attribute__((xray_never_instrument))`` or ``[[clang::xray_never_instrument]]`` will inhibit the insertion of these instrumentation points.
2975 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.
2977 ``__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.
2981 def TransparentUnionDocs : Documentation {
2982 let Category = DocCatType;
2984 This attribute can be applied to a union to change the behaviour of calls to
2985 functions that have an argument with a transparent union type. The compiler
2986 behaviour is changed in the following manner:
2988 - A value whose type is any member of the transparent union can be passed as an
2989 argument without the need to cast that value.
2991 - The argument is passed to the function using the calling convention of the
2992 first member of the transparent union. Consequently, all the members of the
2993 transparent union should have the same calling convention as its first member.
2995 Transparent unions are not supported in C++.
2999 def ObjCSubclassingRestrictedDocs : Documentation {
3000 let Category = DocCatType;
3002 This attribute can be added to an Objective-C ``@interface`` declaration to
3003 ensure that this class cannot be subclassed.