Clang Project

clang_source_code/include/clang/Basic/AttrDocs.td
1//==--- AttrDocs.td - Attribute documentation ----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===---------------------------------------------------------------------===//
8
9// To test that the documentation builds cleanly, you must run clang-tblgen to
10// convert the .td file into a .rst file, and then run sphinx to convert the
11// .rst file into an HTML file. After completing testing, you should revert the
12// generated .rst file so that the modified version does not get checked in to
13// version control.
14//
15// To run clang-tblgen to generate the .rst file:
16// clang-tblgen -gen-attr-docs -I <root>/llvm/tools/clang/include
17//   <root>/llvm/tools/clang/include/clang/Basic/Attr.td -o
18//   <root>/llvm/tools/clang/docs/AttributeReference.rst
19//
20// To run sphinx to generate the .html files (note that sphinx-build must be
21// available on the PATH):
22// Windows (from within the clang\docs directory):
23//   make.bat html
24// Non-Windows (from within the clang\docs directory):
25//   make -f Makefile.sphinx html
26
27def GlobalDocumentation {
28  code Intro =[{..
29  -------------------------------------------------------------------
30  NOTE: This file is automatically generated by running clang-tblgen
31  -gen-attr-docs. Do not edit this file by hand!!
32  -------------------------------------------------------------------
33
34===================
35Attributes in Clang
36===================
37.. contents::
38   :local:
39
40.. |br| raw:: html
41
42  <br/>
43
44Introduction
45============
46
47This page lists the attributes currently supported by Clang.
48}];
49}
50
51def SectionDocs : Documentation {
52  let Category = DocCatVariable;
53  let Content = [{
54The ``section`` attribute allows you to specify a specific section a
55global variable or function should be in after translation.
56  }];
57  let Heading = "section, __declspec(allocate)";
58}
59
60def InitSegDocs : Documentation {
61  let Category = DocCatVariable;
62  let Content = [{
63The attribute applied by ``pragma init_seg()`` controls the section into
64which global initialization function pointers are emitted.  It is only
65available with ``-fms-extensions``.  Typically, this function pointer is
66emitted into ``.CRT$XCU`` on Windows.  The user can change the order of
67initialization by using a different section name with the same
68``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
69after the standard ``.CRT$XCU`` sections.  See the init_seg_
70documentation on MSDN for more information.
71
72.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx
73  }];
74}
75
76def TLSModelDocs : Documentation {
77  let Category = DocCatVariable;
78  let Content = [{
79The ``tls_model`` attribute allows you to specify which thread-local storage
80model to use. It accepts the following strings:
81
82* global-dynamic
83* local-dynamic
84* initial-exec
85* local-exec
86
87TLS models are mutually exclusive.
88  }];
89}
90
91def DLLExportDocs : Documentation {
92  let Category = DocCatVariable;
93  let Content = [{
94The ``__declspec(dllexport)`` attribute declares a variable, function, or
95Objective-C interface to be exported from the module.  It is available under the
96``-fdeclspec`` flag for compatibility with various compilers.  The primary use
97is for COFF object files which explicitly specify what interfaces are available
98for external use.  See the dllexport_ documentation on MSDN for more
99information.
100
101.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
102  }];
103}
104
105def DLLImportDocs : Documentation {
106  let Category = DocCatVariable;
107  let Content = [{
108The ``__declspec(dllimport)`` attribute declares a variable, function, or
109Objective-C interface to be imported from an external module.  It is available
110under the ``-fdeclspec`` flag for compatibility with various compilers.  The
111primary use is for COFF object files which explicitly specify what interfaces
112are imported from external modules.  See the dllimport_ documentation on MSDN
113for more information.
114
115.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
116  }];
117}
118
119def ThreadDocs : Documentation {
120  let Category = DocCatVariable;
121  let Content = [{
122The ``__declspec(thread)`` attribute declares a variable with thread local
123storage.  It is available under the ``-fms-extensions`` flag for MSVC
124compatibility.  See the documentation for `__declspec(thread)`_ on MSDN.
125
126.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
127
128In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
129GNU ``__thread`` keyword.  The variable must not have a destructor and must have
130a constant initializer, if any.  The attribute only applies to variables
131declared with static storage duration, such as globals, class static data
132members, and static locals.
133  }];
134}
135
136def NoEscapeDocs : Documentation {
137  let Category = DocCatVariable;
138  let Content = [{
139``noescape`` placed on a function parameter of a pointer type is used to inform
140the compiler that the pointer cannot escape: that is, no reference to the object
141the pointer points to that is derived from the parameter value will survive
142after the function returns. Users are responsible for making sure parameters
143annotated with ``noescape`` do not actuallly escape.
144
145For example:
146
147.. code-block:: c
148
149  int *gp;
150
151  void nonescapingFunc(__attribute__((noescape)) int *p) {
152    *p += 100; // OK.
153  }
154
155  void escapingFunc(__attribute__((noescape)) int *p) {
156    gp = p; // Not OK.
157  }
158
159Additionally, when the parameter is a `block pointer
160<https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction
161applies to copies of the block. For example:
162
163.. code-block:: c
164
165  typedef void (^BlockTy)();
166  BlockTy g0, g1;
167
168  void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
169    block(); // OK.
170  }
171
172  void escapingFunc(__attribute__((noescape)) BlockTy block) {
173    g0 = block; // Not OK.
174    g1 = Block_copy(block); // Not OK either.
175  }
176
177  }];
178}
179
180def CarriesDependencyDocs : Documentation {
181  let Category = DocCatFunction;
182  let Content = [{
183The ``carries_dependency`` attribute specifies dependency propagation into and
184out of functions.
185
186When specified on a function or Objective-C method, the ``carries_dependency``
187attribute means that the return value carries a dependency out of the function,
188so that the implementation need not constrain ordering upon return from that
189function. Implementations of the function and its caller may choose to preserve
190dependencies instead of emitting memory ordering instructions such as fences.
191
192Note, this attribute does not change the meaning of the program, but may result
193in generation of more efficient code.
194  }];
195}
196
197def CPUSpecificCPUDispatchDocs : Documentation {
198  let Category = DocCatFunction;
199  let Content = [{
200The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
201resolve multiversioned functions. This form of multiversioning provides a
202mechanism for declaring versions across translation units and manually
203specifying the resolved function list. A specified CPU defines a set of minimum
204features that are required for the function to be called. The result of this is
205that future processors execute the most restrictive version of the function the
206new processor can execute.
207
208Function versions are defined with ``cpu_specific``, which takes one or more CPU
209names as a parameter. For example:
210
211.. code-block:: c
212
213  // Declares and defines the ivybridge version of single_cpu.
214  __attribute__((cpu_specific(ivybridge)))
215  void single_cpu(void){}
216
217  // Declares and defines the atom version of single_cpu.
218  __attribute__((cpu_specific(atom)))
219  void single_cpu(void){}
220
221  // Declares and defines both the ivybridge and atom version of multi_cpu.
222  __attribute__((cpu_specific(ivybridge, atom)))
223  void multi_cpu(void){}
224
225A dispatching (or resolving) function can be declared anywhere in a project's
226source code with ``cpu_dispatch``. This attribute takes one or more CPU names
227as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
228are not expected to be defined, only declared. If such a marked function has a
229definition, any side effects of the function are ignored; trivial function
230bodies are permissible for ICC compatibility.
231
232.. code-block:: c
233
234  // Creates a resolver for single_cpu above.
235  __attribute__((cpu_dispatch(ivybridge, atom)))
236  void single_cpu(void){}
237
238  // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
239  // translation unit.
240  __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
241  void multi_cpu(void){}
242
243Note that it is possible to have a resolving function that dispatches based on
244more or fewer options than are present in the program. Specifying fewer will
245result in the omitted options not being considered during resolution. Specifying
246a version for resolution that isn't defined in the program will result in a
247linking failure.
248
249It is also possible to specify a CPU name of ``generic`` which will be resolved
250if the executing processor doesn't satisfy the features required in the CPU
251name. The behavior of a program executing on a processor that doesn't satisfy
252any option of a multiversioned function is undefined.
253  }];
254}
255
256def C11NoReturnDocs : Documentation {
257  let Category = DocCatFunction;
258  let Content = [{
259A function declared as ``_Noreturn`` shall not return to its caller. The
260compiler will generate a diagnostic for a function declared as ``_Noreturn``
261that appears to be capable of returning to its caller.
262  }];
263}
264
265def CXX11NoReturnDocs : Documentation {
266  let Category = DocCatFunction;
267  let Content = [{
268A function declared as ``[[noreturn]]`` shall not return to its caller. The
269compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
270that appears to be capable of returning to its caller.
271  }];
272}
273
274def AssertCapabilityDocs : Documentation {
275  let Category = DocCatFunction;
276  let Heading = "assert_capability, assert_shared_capability";
277  let Content = [{
278Marks a function that dynamically tests whether a capability is held, and halts
279the program if it is not held.
280  }];
281}
282
283def AcquireCapabilityDocs : Documentation {
284  let Category = DocCatFunction;
285  let Heading = "acquire_capability, acquire_shared_capability";
286  let Content = [{
287Marks a function as acquiring a capability.
288  }];
289}
290
291def TryAcquireCapabilityDocs : Documentation {
292  let Category = DocCatFunction;
293  let Heading = "try_acquire_capability, try_acquire_shared_capability";
294  let Content = [{
295Marks a function that attempts to acquire a capability. This function may fail to
296actually acquire the capability; they accept a Boolean value determining
297whether acquiring the capability means success (true), or failing to acquire
298the capability means success (false).
299  }];
300}
301
302def ReleaseCapabilityDocs : Documentation {
303  let Category = DocCatFunction;
304  let Heading = "release_capability, release_shared_capability";
305  let Content = [{
306Marks a function as releasing a capability.
307  }];
308}
309
310def AssumeAlignedDocs : Documentation {
311  let Category = DocCatFunction;
312  let Content = [{
313Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function
314declaration to specify that the return value of the function (which must be a
315pointer type) has the specified offset, in bytes, from an address with the
316specified alignment. The offset is taken to be zero if omitted.
317
318.. code-block:: c++
319
320  // The returned pointer value has 32-byte alignment.
321  void *a() __attribute__((assume_aligned (32)));
322
323  // The returned pointer value is 4 bytes greater than an address having
324  // 32-byte alignment.
325  void *b() __attribute__((assume_aligned (32, 4)));
326
327Note that this attribute provides information to the compiler regarding a
328condition that the code already ensures is true. It does not cause the compiler
329to enforce the provided alignment assumption.
330  }];
331}
332
333def AllocSizeDocs : Documentation {
334  let Category = DocCatFunction;
335  let Content = [{
336The ``alloc_size`` attribute can be placed on functions that return pointers in
337order to hint to the compiler how many bytes of memory will be available at the
338returned pointer. ``alloc_size`` takes one or two arguments.
339
340- ``alloc_size(N)`` implies that argument number N equals the number of
341  available bytes at the returned pointer.
342- ``alloc_size(N, M)`` implies that the product of argument number N and
343  argument number M equals the number of available bytes at the returned
344  pointer.
345
346Argument numbers are 1-based.
347
348An example of how to use ``alloc_size``
349
350.. code-block:: c
351
352  void *my_malloc(int a) __attribute__((alloc_size(1)));
353  void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
354
355  int main() {
356    void *const p = my_malloc(100);
357    assert(__builtin_object_size(p, 0) == 100);
358    void *const a = my_calloc(20, 5);
359    assert(__builtin_object_size(a, 0) == 100);
360  }
361
362.. Note:: This attribute works differently in clang than it does in GCC.
363  Specifically, clang will only trace ``const`` pointers (as above); we give up
364  on pointers that are not marked as ``const``. In the vast majority of cases,
365  this is unimportant, because LLVM has support for the ``alloc_size``
366  attribute. However, this may cause mildly unintuitive behavior when used with
367  other attributes, such as ``enable_if``.
368  }];
369}
370
371def CodeSegDocs : Documentation {
372  let Category = DocCatFunction;
373  let Content = [{
374The ``__declspec(code_seg)`` attribute enables the placement of code into separate
375named segments that can be paged or locked in memory individually. This attribute
376is used to control the placement of instantiated templates and compiler-generated
377code. See the documentation for `__declspec(code_seg)`_ on MSDN.
378
379.. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx
380  }];
381}
382
383def AllocAlignDocs : Documentation {
384  let Category = DocCatFunction;
385  let Content = [{
386Use ``__attribute__((alloc_align(<alignment>))`` on a function
387declaration to specify that the return value of the function (which must be a
388pointer type) is at least as aligned as the value of the indicated parameter. The
389parameter is given by its index in the list of formal parameters; the first
390parameter has index 1 unless the function is a C++ non-static member function,
391in which case the first parameter has index 2 to account for the implicit ``this``
392parameter.
393
394.. code-block:: c++
395
396  // The returned pointer has the alignment specified by the first parameter.
397  void *a(size_t align) __attribute__((alloc_align(1)));
398
399  // The returned pointer has the alignment specified by the second parameter.
400  void *b(void *v, size_t align) __attribute__((alloc_align(2)));
401
402  // The returned pointer has the alignment specified by the second visible
403  // parameter, however it must be adjusted for the implicit 'this' parameter.
404  void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
405
406Note that this attribute merely informs the compiler that a function always
407returns a sufficiently aligned pointer. It does not cause the compiler to
408emit code to enforce that alignment.  The behavior is undefined if the returned
409poitner is not sufficiently aligned.
410  }];
411}
412
413def EnableIfDocs : Documentation {
414  let Category = DocCatFunction;
415  let Content = [{
416.. Note:: Some features of this attribute are experimental. The meaning of
417  multiple enable_if attributes on a single declaration is subject to change in
418  a future version of clang. Also, the ABI is not standardized and the name
419  mangling may change in future versions. To avoid that, use asm labels.
420
421The ``enable_if`` attribute can be placed on function declarations to control
422which overload is selected based on the values of the function's arguments.
423When combined with the ``overloadable`` attribute, this feature is also
424available in C.
425
426.. code-block:: c++
427
428  int isdigit(int c);
429  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")));
430
431  void foo(char c) {
432    isdigit(c);
433    isdigit(10);
434    isdigit(-10);  // results in a compile-time error.
435  }
436
437The enable_if attribute takes two arguments, the first is an expression written
438in terms of the function parameters, the second is a string explaining why this
439overload candidate could not be selected to be displayed in diagnostics. The
440expression is part of the function signature for the purposes of determining
441whether it is a redeclaration (following the rules used when determining
442whether a C++ template specialization is ODR-equivalent), but is not part of
443the type.
444
445The enable_if expression is evaluated as if it were the body of a
446bool-returning constexpr function declared with the arguments of the function
447it is being applied to, then called with the parameters at the call site. If the
448result is false or could not be determined through constant expression
449evaluation, then this overload will not be chosen and the provided string may
450be used in a diagnostic if the compile fails as a result.
451
452Because the enable_if expression is an unevaluated context, there are no global
453state changes, nor the ability to pass information from the enable_if
454expression to the function body. For example, suppose we want calls to
455strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
456strbuf) only if the size of strbuf can be determined:
457
458.. code-block:: c++
459
460  __attribute__((always_inline))
461  static inline size_t strnlen(const char *s, size_t maxlen)
462    __attribute__((overloadable))
463    __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
464                             "chosen when the buffer size is known but 'maxlen' is not")))
465  {
466    return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
467  }
468
469Multiple enable_if attributes may be applied to a single declaration. In this
470case, the enable_if expressions are evaluated from left to right in the
471following manner. First, the candidates whose enable_if expressions evaluate to
472false or cannot be evaluated are discarded. If the remaining candidates do not
473share ODR-equivalent enable_if expressions, the overload resolution is
474ambiguous. Otherwise, enable_if overload resolution continues with the next
475enable_if attribute on the candidates that have not been discarded and have
476remaining enable_if attributes. In this way, we pick the most specific
477overload out of a number of viable overloads using enable_if.
478
479.. code-block:: c++
480
481  void f() __attribute__((enable_if(true, "")));  // #1
482  void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, "")));  // #2
483
484  void g(int i, int j) __attribute__((enable_if(i, "")));  // #1
485  void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true)));  // #2
486
487In this example, a call to f() is always resolved to #2, as the first enable_if
488expression is ODR-equivalent for both declarations, but #1 does not have another
489enable_if expression to continue evaluating, so the next round of evaluation has
490only a single candidate. In a call to g(1, 1), the call is ambiguous even though
491#2 has more enable_if attributes, because the first enable_if expressions are
492not ODR-equivalent.
493
494Query for this feature with ``__has_attribute(enable_if)``.
495
496Note that functions with one or more ``enable_if`` attributes may not have
497their address taken, unless all of the conditions specified by said
498``enable_if`` are constants that evaluate to ``true``. For example:
499
500.. code-block:: c
501
502  const int TrueConstant = 1;
503  const int FalseConstant = 0;
504  int f(int a) __attribute__((enable_if(a > 0, "")));
505  int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
506  int h(int a) __attribute__((enable_if(1, "")));
507  int i(int a) __attribute__((enable_if(TrueConstant, "")));
508  int j(int a) __attribute__((enable_if(FalseConstant, "")));
509
510  void fn() {
511    int (*ptr)(int);
512    ptr = &f; // error: 'a > 0' is not always true
513    ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
514    ptr = &h; // OK: 1 is a truthy constant
515    ptr = &i; // OK: 'TrueConstant' is a truthy constant
516    ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
517  }
518
519Because ``enable_if`` evaluation happens during overload resolution,
520``enable_if`` may give unintuitive results when used with templates, depending
521on when overloads are resolved. In the example below, clang will emit a
522diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``:
523
524.. code-block:: c++
525
526  double foo(int i) __attribute__((enable_if(i > 0, "")));
527  void *foo(int i) __attribute__((enable_if(i <= 0, "")));
528  template <int I>
529  auto bar() { return foo(I); }
530
531  template <typename T>
532  auto baz() { return foo(T::number); }
533
534  struct WithNumber { constexpr static int number = 1; };
535  void callThem() {
536    bar<sizeof(WithNumber)>();
537    baz<WithNumber>();
538  }
539
540This is because, in ``bar``, ``foo`` is resolved prior to template
541instantiation, so the value for ``I`` isn't known (thus, both ``enable_if``
542conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during
543template instantiation, so the value for ``T::number`` is known.
544  }];
545}
546
547def DiagnoseIfDocs : Documentation {
548  let Category = DocCatFunction;
549  let Content = [{
550The ``diagnose_if`` attribute can be placed on function declarations to emit
551warnings or errors at compile-time if calls to the attributed function meet
552certain user-defined criteria. For example:
553
554.. code-block:: c
555
556  int abs(int a)
557    __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
558  int must_abs(int a)
559    __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
560
561  int val = abs(1); // warning: Redundant abs call
562  int val2 = must_abs(1); // error: Redundant abs call
563  int val3 = abs(val);
564  int val4 = must_abs(val); // Because run-time checks are not emitted for
565                            // diagnose_if attributes, this executes without
566                            // issue.
567
568
569``diagnose_if`` is closely related to ``enable_if``, with a few key differences:
570
571* Overload resolution is not aware of ``diagnose_if`` attributes: they're
572  considered only after we select the best candidate from a given candidate set.
573* Function declarations that differ only in their ``diagnose_if`` attributes are
574  considered to be redeclarations of the same function (not overloads).
575* If the condition provided to ``diagnose_if`` cannot be evaluated, no
576  diagnostic will be emitted.
577
578Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``.
579
580As a result of bullet number two, ``diagnose_if`` attributes will stack on the
581same function. For example:
582
583.. code-block:: c
584
585  int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
586  int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
587
588  int bar = foo(); // warning: diag1
589                   // warning: diag2
590  int (*fooptr)(void) = foo; // warning: diag1
591                             // warning: diag2
592
593  constexpr int supportsAPILevel(int N) { return N < 5; }
594  int baz(int a)
595    __attribute__((diagnose_if(!supportsAPILevel(10),
596                               "Upgrade to API level 10 to use baz", "error")));
597  int baz(int a)
598    __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
599
600  int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
601  int v = baz(0); // error: Upgrade to API level 10 to use baz
602
603Query for this feature with ``__has_attribute(diagnose_if)``.
604  }];
605}
606
607def PassObjectSizeDocs : Documentation {
608  let Category = DocCatVariable; // Technically it's a parameter doc, but eh.
609  let Heading = "pass_object_size, pass_dynamic_object_size";
610  let Content = [{
611.. Note:: The mangling of functions with parameters that are annotated with
612  ``pass_object_size`` is subject to change. You can get around this by
613  using ``__asm__("foo")`` to explicitly name your functions, thus preserving
614  your ABI; also, non-overloadable C functions with ``pass_object_size`` are
615  not mangled.
616
617The ``pass_object_size(Type)`` attribute can be placed on function parameters to
618instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite
619of said function, and implicitly pass the result of this call in as an invisible
620argument of type ``size_t`` directly after the parameter annotated with
621``pass_object_size``. Clang will also replace any calls to
622``__builtin_object_size(param, Type)`` in the function by said implicit
623parameter.
624
625Example usage:
626
627.. code-block:: c
628
629  int bzero1(char *const p __attribute__((pass_object_size(0))))
630      __attribute__((noinline)) {
631    int i = 0;
632    for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
633      p[i] = 0;
634    }
635    return i;
636  }
637
638  int main() {
639    char chars[100];
640    int n = bzero1(&chars[0]);
641    assert(n == sizeof(chars));
642    return 0;
643  }
644
645If successfully evaluating ``__builtin_object_size(param, Type)`` at the
646callsite is not possible, then the "failed" value is passed in. So, using the
647definition of ``bzero1`` from above, the following code would exit cleanly:
648
649.. code-block:: c
650
651  int main2(int argc, char *argv[]) {
652    int n = bzero1(argv);
653    assert(n == -1);
654    return 0;
655  }
656
657``pass_object_size`` plays a part in overload resolution. If two overload
658candidates are otherwise equally good, then the overload with one or more
659parameters with ``pass_object_size`` is preferred. This implies that the choice
660between two identical overloads both with ``pass_object_size`` on one or more
661parameters will always be ambiguous; for this reason, having two such overloads
662is illegal. For example:
663
664.. code-block:: c++
665
666  #define PS(N) __attribute__((pass_object_size(N)))
667  // OK
668  void Foo(char *a, char *b); // Overload A
669  // OK -- overload A has no parameters with pass_object_size.
670  void Foo(char *a PS(0), char *b PS(0)); // Overload B
671  // Error -- Same signature (sans pass_object_size) as overload B, and both
672  // overloads have one or more parameters with the pass_object_size attribute.
673  void Foo(void *a PS(0), void *b);
674
675  // OK
676  void Bar(void *a PS(0)); // Overload C
677  // OK
678  void Bar(char *c PS(1)); // Overload D
679
680  void main() {
681    char known[10], *unknown;
682    Foo(unknown, unknown); // Calls overload B
683    Foo(known, unknown); // Calls overload B
684    Foo(unknown, known); // Calls overload B
685    Foo(known, known); // Calls overload B
686
687    Bar(known); // Calls overload D
688    Bar(unknown); // Calls overload D
689  }
690
691Currently, ``pass_object_size`` is a bit restricted in terms of its usage:
692
693* Only one use of ``pass_object_size`` is allowed per parameter.
694
695* It is an error to take the address of a function with ``pass_object_size`` on
696  any of its parameters. If you wish to do this, you can create an overload
697  without ``pass_object_size`` on any parameters.
698
699* It is an error to apply the ``pass_object_size`` attribute to parameters that
700  are not pointers. Additionally, any parameter that ``pass_object_size`` is
701  applied to must be marked ``const`` at its function's definition.
702
703Clang also supports the ``pass_dynamic_object_size`` attribute, which behaves
704identically to ``pass_object_size``, but evaluates a call to
705``__builtin_dynamic_object_size`` at the callee instead of
706``__builtin_object_size``. ``__builtin_dynamic_object_size`` provides some extra
707runtime checks when the object size can't be determined at compile-time. You can
708read more about ``__builtin_dynamic_object_size`` `here
709<https://clang.llvm.org/docs/LanguageExtensions.html#evaluating-object-size-dynamically>`_.
710
711  }];
712}
713
714def OverloadableDocs : Documentation {
715  let Category = DocCatFunction;
716  let Content = [{
717Clang provides support for C++ function overloading in C.  Function overloading
718in C is introduced using the ``overloadable`` attribute.  For example, one
719might provide several overloaded versions of a ``tgsin`` function that invokes
720the appropriate standard function computing the sine of a value with ``float``,
721``double``, or ``long double`` precision:
722
723.. code-block:: c
724
725  #include <math.h>
726  float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
727  double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
728  long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
729
730Given these declarations, one can call ``tgsin`` with a ``float`` value to
731receive a ``float`` result, with a ``double`` to receive a ``double`` result,
732etc.  Function overloading in C follows the rules of C++ function overloading
733to pick the best overload given the call arguments, with a few C-specific
734semantics:
735
736* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
737  floating-point promotion (per C99) rather than as a floating-point conversion
738  (as in C++).
739
740* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
741  considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
742  compatible types.
743
744* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
745  and ``U`` are compatible types.  This conversion is given "conversion" rank.
746
747* If no viable candidates are otherwise available, we allow a conversion from a
748  pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are
749  incompatible. This conversion is ranked below all other types of conversions.
750  Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient
751  for ``T`` and ``U`` to be incompatible.
752
753The declaration of ``overloadable`` functions is restricted to function
754declarations and definitions.  If a function is marked with the ``overloadable``
755attribute, then all declarations and definitions of functions with that name,
756except for at most one (see the note below about unmarked overloads), must have
757the ``overloadable`` attribute.  In addition, redeclarations of a function with
758the ``overloadable`` attribute must have the ``overloadable`` attribute, and
759redeclarations of a function without the ``overloadable`` attribute must *not*
760have the ``overloadable`` attribute. e.g.,
761
762.. code-block:: c
763
764  int f(int) __attribute__((overloadable));
765  float f(float); // error: declaration of "f" must have the "overloadable" attribute
766  int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
767
768  int g(int) __attribute__((overloadable));
769  int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
770
771  int h(int);
772  int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
773                                            // have the "overloadable" attribute
774
775Functions marked ``overloadable`` must have prototypes.  Therefore, the
776following code is ill-formed:
777
778.. code-block:: c
779
780  int h() __attribute__((overloadable)); // error: h does not have a prototype
781
782However, ``overloadable`` functions are allowed to use a ellipsis even if there
783are no named parameters (as is permitted in C++).  This feature is particularly
784useful when combined with the ``unavailable`` attribute:
785
786.. code-block:: c++
787
788  void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
789
790Functions declared with the ``overloadable`` attribute have their names mangled
791according to the same rules as C++ function names.  For example, the three
792``tgsin`` functions in our motivating example get the mangled names
793``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively.  There are two
794caveats to this use of name mangling:
795
796* Future versions of Clang may change the name mangling of functions overloaded
797  in C, so you should not depend on an specific mangling.  To be completely
798  safe, we strongly urge the use of ``static inline`` with ``overloadable``
799  functions.
800
801* The ``overloadable`` attribute has almost no meaning when used in C++,
802  because names will already be mangled and functions are already overloadable.
803  However, when an ``overloadable`` function occurs within an ``extern "C"``
804  linkage specification, it's name *will* be mangled in the same way as it
805  would in C.
806
807For the purpose of backwards compatibility, at most one function with the same
808name as other ``overloadable`` functions may omit the ``overloadable``
809attribute. In this case, the function without the ``overloadable`` attribute
810will not have its name mangled.
811
812For example:
813
814.. code-block:: c
815
816  // Notes with mangled names assume Itanium mangling.
817  int f(int);
818  int f(double) __attribute__((overloadable));
819  void foo() {
820    f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
821          // was marked with overloadable).
822    f(1.0); // Emits a call to _Z1fd.
823  }
824
825Support for unmarked overloads is not present in some versions of clang. You may
826query for it using ``__has_extension(overloadable_unmarked)``.
827
828Query for this attribute with ``__has_attribute(overloadable)``.
829  }];
830}
831
832def ObjCMethodFamilyDocs : Documentation {
833  let Category = DocCatFunction;
834  let Content = [{
835Many methods in Objective-C have conventional meanings determined by their
836selectors. It is sometimes useful to be able to mark a method as having a
837particular conventional meaning despite not having the right selector, or as
838not having the conventional meaning that its selector would suggest. For these
839use cases, we provide an attribute to specifically describe the "method family"
840that a method belongs to.
841
842**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
843``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``.  This
844attribute can only be placed at the end of a method declaration:
845
846.. code-block:: objc
847
848  - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
849
850Users who do not wish to change the conventional meaning of a method, and who
851merely want to document its non-standard retain and release semantics, should
852use the retaining behavior attributes (``ns_returns_retained``,
853``ns_returns_not_retained``, etc).
854
855Query for this feature with ``__has_attribute(objc_method_family)``.
856  }];
857}
858
859def RetainBehaviorDocs : Documentation {
860  let Category = DocCatFunction;
861  let Content = [{
862The behavior of a function with respect to reference counting for Foundation
863(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
864convention (e.g. functions starting with "get" are assumed to return at
865``+0``).
866
867It can be overriden using a family of the following attributes.  In
868Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
869a function communicates that the object is returned at ``+1``, and the caller
870is responsible for freeing it.
871Similiarly, the annotation ``__attribute__((ns_returns_not_retained))``
872specifies that the object is returned at ``+0`` and the ownership remains with
873the callee.
874The annotation ``__attribute__((ns_consumes_self))`` specifies that
875the Objective-C method call consumes the reference to ``self``, e.g. by
876attaching it to a supplied parameter.
877Additionally, parameters can have an annotation
878``__attribute__((ns_consumed))``, which specifies that passing an owned object
879as that parameter effectively transfers the ownership, and the caller is no
880longer responsible for it.
881These attributes affect code generation when interacting with ARC code, and
882they are used by the Clang Static Analyzer.
883
884In C programs using CoreFoundation, a similar set of attributes:
885``__attribute__((cf_returns_not_retained))``,
886``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
887have the same respective semantics when applied to CoreFoundation objects.
888These attributes affect code generation when interacting with ARC code, and
889they are used by the Clang Static Analyzer.
890
891Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
892the same attribute family is present:
893``__attribute__((os_returns_not_retained))``,
894``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
895with the same respective semantics.
896Similar to ``__attribute__((ns_consumes_self))``,
897``__attribute__((os_consumes_this))`` specifies that the method call consumes
898the reference to "this" (e.g., when attaching it to a different object supplied
899as a parameter).
900Out parameters (parameters the function is meant to write into,
901either via pointers-to-pointers or references-to-pointers)
902may be annotated with ``__attribute__((os_returns_retained))``
903or ``__attribute__((os_returns_not_retained))`` which specifies that the object
904written into the out parameter should (or respectively should not) be released
905after use.
906Since often out parameters may or may not be written depending on the exit
907code of the function,
908annotations ``__attribute__((os_returns_retained_on_zero))``
909and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
910an out parameter at ``+1`` is written if and only if the function returns a zero
911(respectively non-zero) error code.
912Observe that return-code-dependent out parameter annotations are only
913available for retained out parameters, as non-retained object do not have to be
914released by the callee.
915These attributes are only used by the Clang Static Analyzer.
916
917The family of attributes ``X_returns_X_retained`` can be added to functions,
918C++ methods, and Objective-C methods and properties.
919Attributes ``X_consumed`` can be added to parameters of methods, functions,
920and Objective-C methods.
921  }];
922}
923
924
925
926def NoDebugDocs : Documentation {
927  let Category = DocCatVariable;
928  let Content = [{
929The ``nodebug`` attribute allows you to suppress debugging information for a
930function or method, or for a variable that is not a parameter or a non-static
931data member.
932  }];
933}
934
935def NoDuplicateDocs : Documentation {
936  let Category = DocCatFunction;
937  let Content = [{
938The ``noduplicate`` attribute can be placed on function declarations to control
939whether function calls to this function can be duplicated or not as a result of
940optimizations. This is required for the implementation of functions with
941certain special requirements, like the OpenCL "barrier" function, that might
942need to be run concurrently by all the threads that are executing in lockstep
943on the hardware. For example this attribute applied on the function
944"nodupfunc" in the code below avoids that:
945
946.. code-block:: c
947
948  void nodupfunc() __attribute__((noduplicate));
949  // Setting it as a C++11 attribute is also valid
950  // void nodupfunc() [[clang::noduplicate]];
951  void foo();
952  void bar();
953
954  nodupfunc();
955  if (a > n) {
956    foo();
957  } else {
958    bar();
959  }
960
961gets possibly modified by some optimizations into code similar to this:
962
963.. code-block:: c
964
965  if (a > n) {
966    nodupfunc();
967    foo();
968  } else {
969    nodupfunc();
970    bar();
971  }
972
973where the call to "nodupfunc" is duplicated and sunk into the two branches
974of the condition.
975  }];
976}
977
978def ConvergentDocs : Documentation {
979  let Category = DocCatFunction;
980  let Content = [{
981The ``convergent`` attribute can be placed on a function declaration. It is
982translated into the LLVM ``convergent`` attribute, which indicates that the call
983instructions of a function with this attribute cannot be made control-dependent
984on any additional values.
985
986In languages designed for SPMD/SIMT programming model, e.g. OpenCL or CUDA,
987the call instructions of a function with this attribute must be executed by
988all work items or threads in a work group or sub group.
989
990This attribute is different from ``noduplicate`` because it allows duplicating
991function calls if it can be proved that the duplicated function calls are
992not made control-dependent on any additional values, e.g., unrolling a loop
993executed by all work items.
994
995Sample usage:
996.. code-block:: c
997
998  void convfunc(void) __attribute__((convergent));
999  // Setting it as a C++11 attribute is also valid in a C++ program.
1000  // void convfunc(void) [[clang::convergent]];
1001
1002  }];
1003}
1004
1005def NoSplitStackDocs : Documentation {
1006  let Category = DocCatFunction;
1007  let Content = [{
1008The ``no_split_stack`` attribute disables the emission of the split stack
1009preamble for a particular function. It has no effect if ``-fsplit-stack``
1010is not specified.
1011  }];
1012}
1013
1014def ObjCRequiresSuperDocs : Documentation {
1015  let Category = DocCatFunction;
1016  let Content = [{
1017Some Objective-C classes allow a subclass to override a particular method in a
1018parent class but expect that the overriding method also calls the overridden
1019method in the parent class. For these cases, we provide an attribute to
1020designate that a method requires a "call to ``super``" in the overriding
1021method in the subclass.
1022
1023**Usage**: ``__attribute__((objc_requires_super))``.  This attribute can only
1024be placed at the end of a method declaration:
1025
1026.. code-block:: objc
1027
1028  - (void)foo __attribute__((objc_requires_super));
1029
1030This attribute can only be applied the method declarations within a class, and
1031not a protocol.  Currently this attribute does not enforce any placement of
1032where the call occurs in the overriding method (such as in the case of
1033``-dealloc`` where the call must appear at the end).  It checks only that it
1034exists.
1035
1036Note that on both OS X and iOS that the Foundation framework provides a
1037convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
1038attribute:
1039
1040.. code-block:: objc
1041
1042  - (void)foo NS_REQUIRES_SUPER;
1043
1044This macro is conditionally defined depending on the compiler's support for
1045this attribute.  If the compiler does not support the attribute the macro
1046expands to nothing.
1047
1048Operationally, when a method has this annotation the compiler will warn if the
1049implementation of an override in a subclass does not call super.  For example:
1050
1051.. code-block:: objc
1052
1053   warning: method possibly missing a [super AnnotMeth] call
1054   - (void) AnnotMeth{};
1055                      ^
1056  }];
1057}
1058
1059def ObjCRuntimeNameDocs : Documentation {
1060    let Category = DocCatFunction;
1061    let Content = [{
1062By default, the Objective-C interface or protocol identifier is used
1063in the metadata name for that object. The `objc_runtime_name`
1064attribute allows annotated interfaces or protocols to use the
1065specified string argument in the object's metadata name instead of the
1066default name.
1067
1068**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``.  This attribute
1069can only be placed before an @protocol or @interface declaration:
1070
1071.. code-block:: objc
1072
1073  __attribute__((objc_runtime_name("MyLocalName")))
1074  @interface Message
1075  @end
1076
1077    }];
1078}
1079
1080def ObjCRuntimeVisibleDocs : Documentation {
1081    let Category = DocCatFunction;
1082    let Content = [{
1083This 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.
1084    }];
1085}
1086
1087def ObjCBoxableDocs : Documentation {
1088    let Category = DocCatFunction;
1089    let Content = [{
1090Structs and unions marked with the ``objc_boxable`` attribute can be used
1091with the Objective-C boxed expression syntax, ``@(...)``.
1092
1093**Usage**: ``__attribute__((objc_boxable))``. This attribute
1094can only be placed on a declaration of a trivially-copyable struct or union:
1095
1096.. code-block:: objc
1097
1098  struct __attribute__((objc_boxable)) some_struct {
1099    int i;
1100  };
1101  union __attribute__((objc_boxable)) some_union {
1102    int i;
1103    float f;
1104  };
1105  typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
1106
1107  // ...
1108
1109  some_struct ss;
1110  NSValue *boxed = @(ss);
1111
1112    }];
1113}
1114
1115def AvailabilityDocs : Documentation {
1116  let Category = DocCatFunction;
1117  let Content = [{
1118The ``availability`` attribute can be placed on declarations to describe the
1119lifecycle of that declaration relative to operating system versions.  Consider
1120the function declaration for a hypothetical function ``f``:
1121
1122.. code-block:: c++
1123
1124  void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
1125
1126The availability attribute states that ``f`` was introduced in macOS 10.4,
1127deprecated in macOS 10.6, and obsoleted in macOS 10.7.  This information
1128is used by Clang to determine when it is safe to use ``f``: for example, if
1129Clang is instructed to compile code for macOS 10.5, a call to ``f()``
1130succeeds.  If Clang is instructed to compile code for macOS 10.6, the call
1131succeeds but Clang emits a warning specifying that the function is deprecated.
1132Finally, if Clang is instructed to compile code for macOS 10.7, the call
1133fails because ``f()`` is no longer available.
1134
1135The availability attribute is a comma-separated list starting with the
1136platform name and then including clauses specifying important milestones in the
1137declaration's lifetime (in any order) along with additional information.  Those
1138clauses can be:
1139
1140introduced=\ *version*
1141  The first version in which this declaration was introduced.
1142
1143deprecated=\ *version*
1144  The first version in which this declaration was deprecated, meaning that
1145  users should migrate away from this API.
1146
1147obsoleted=\ *version*
1148  The first version in which this declaration was obsoleted, meaning that it
1149  was removed completely and can no longer be used.
1150
1151unavailable
1152  This declaration is never available on this platform.
1153
1154message=\ *string-literal*
1155  Additional message text that Clang will provide when emitting a warning or
1156  error about use of a deprecated or obsoleted declaration.  Useful to direct
1157  users to replacement APIs.
1158
1159replacement=\ *string-literal*
1160  Additional message text that Clang will use to provide Fix-It when emitting
1161  a warning about use of a deprecated declaration. The Fix-It will replace
1162  the deprecated declaration with the new declaration specified.
1163
1164Multiple availability attributes can be placed on a declaration, which may
1165correspond to different platforms. For most platforms, the availability
1166attribute with the platform corresponding to the target platform will be used;
1167any others will be ignored. However, the availability for ``watchOS`` and
1168``tvOS`` can be implicitly inferred from an ``iOS`` availability attribute.
1169Any explicit availability attributes for those platforms are still prefered over
1170the implicitly inferred availability attributes. If no availability attribute
1171specifies availability for the current target platform, the availability
1172attributes are ignored. Supported platforms are:
1173
1174``ios``
1175  Apple's iOS operating system.  The minimum deployment target is specified by
1176  the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
1177  command-line arguments.
1178
1179``macos``
1180  Apple's macOS operating system.  The minimum deployment target is
1181  specified by the ``-mmacosx-version-min=*version*`` command-line argument.
1182  ``macosx`` is supported for backward-compatibility reasons, but it is
1183  deprecated.
1184
1185``tvos``
1186  Apple's tvOS operating system.  The minimum deployment target is specified by
1187  the ``-mtvos-version-min=*version*`` command-line argument.
1188
1189``watchos``
1190  Apple's watchOS operating system.  The minimum deployment target is specified by
1191  the ``-mwatchos-version-min=*version*`` command-line argument.
1192
1193A declaration can typically be used even when deploying back to a platform
1194version prior to when the declaration was introduced.  When this happens, the
1195declaration is `weakly linked
1196<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
1197as if the ``weak_import`` attribute were added to the declaration.  A
1198weakly-linked declaration may or may not be present a run-time, and a program
1199can determine whether the declaration is present by checking whether the
1200address of that declaration is non-NULL.
1201
1202The flag ``strict`` disallows using API when deploying back to a
1203platform version prior to when the declaration was introduced.  An
1204attempt to use such API before its introduction causes a hard error.
1205Weakly-linking is almost always a better API choice, since it allows
1206users to query availability at runtime.
1207
1208If there are multiple declarations of the same entity, the availability
1209attributes must either match on a per-platform basis or later
1210declarations must not have availability attributes for that
1211platform. For example:
1212
1213.. code-block:: c
1214
1215  void g(void) __attribute__((availability(macos,introduced=10.4)));
1216  void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
1217  void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
1218  void g(void); // okay, inherits both macos and ios availability from above.
1219  void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
1220
1221When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
1222
1223.. code-block:: objc
1224
1225  @interface A
1226  - (id)method __attribute__((availability(macos,introduced=10.4)));
1227  - (id)method2 __attribute__((availability(macos,introduced=10.4)));
1228  @end
1229
1230  @interface B : A
1231  - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
1232  - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
1233  @end
1234
1235Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from
1236``<os/availability.h>`` can simplify the spelling:
1237
1238.. code-block:: objc
1239
1240  @interface A
1241  - (id)method API_AVAILABLE(macos(10.11)));
1242  - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1243  @end
1244
1245Availability attributes can also be applied using a ``#pragma clang attribute``.
1246Any explicit availability attribute whose platform corresponds to the target
1247platform is applied to a declaration regardless of the availability attributes
1248specified in the pragma. For example, in the code below,
1249``hasExplicitAvailabilityAttribute`` will use the ``macOS`` availability
1250attribute that is specified with the declaration, whereas
1251``getsThePragmaAvailabilityAttribute`` will use the ``macOS`` availability
1252attribute that is applied by the pragma.
1253
1254.. code-block:: c
1255
1256  #pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)
1257  void getsThePragmaAvailabilityAttribute(void);
1258  void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4)));
1259  #pragma clang attribute pop
1260
1261For platforms like ``watchOS`` and ``tvOS``, whose availability attributes can
1262be implicitly inferred from an ``iOS`` availability attribute, the logic is
1263slightly more complex. The explicit and the pragma-applied availability
1264attributes whose platform corresponds to the target platform are applied as
1265described in the previous paragraph. However, the implicitly inferred attributes
1266are applied to a declaration only when there is no explicit or pragma-applied
1267availability attribute whose platform corresponds to the target platform. For
1268example, the function below will receive the ``tvOS`` availability from the
1269pragma rather than using the inferred ``iOS`` availability from the declaration:
1270
1271.. code-block:: c
1272
1273  #pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)
1274  void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0)));
1275  #pragma clang attribute pop
1276
1277The compiler is also able to apply implicly inferred attributes from a pragma
1278as well. For example, when targeting ``tvOS``, the function below will receive
1279a ``tvOS`` availability attribute that is implicitly inferred from the ``iOS``
1280availability attribute applied by the pragma:
1281
1282.. code-block:: c
1283
1284  #pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)
1285  void infersTVOSAvailabilityFromPragma(void);
1286  #pragma clang attribute pop
1287
1288The implicit attributes that are inferred from explicitly specified attributes
1289whose platform corresponds to the target platform are applied to the declaration
1290even if there is an availability attribute that can be inferred from a pragma.
1291For example, the function below will receive the ``tvOS, introduced=11.0``
1292availability that is inferred from the attribute on the declaration rather than
1293inferring availability from the pragma:
1294
1295.. code-block:: c
1296
1297  #pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)
1298  void infersTVOSAvailabilityFromAttributeNextToDeclaration(void)
1299    __attribute__((availability(iOS,introduced=11.0)));
1300  #pragma clang attribute pop
1301
1302Also see the documentation for `@available
1303<http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_
1304  }];
1305}
1306
1307def ExternalSourceSymbolDocs : Documentation {
1308  let Category = DocCatFunction;
1309  let Content = [{
1310The ``external_source_symbol`` attribute specifies that a declaration originates
1311from an external source and describes the nature of that source.
1312
1313The fact that Clang is capable of recognizing declarations that were defined
1314externally can be used to provide better tooling support for mixed-language
1315projects or projects that rely on auto-generated code. For instance, an IDE that
1316uses Clang and that supports mixed-language projects can use this attribute to
1317provide a correct 'jump-to-definition' feature. For a concrete example,
1318consider a protocol that's defined in a Swift file:
1319
1320.. code-block:: swift
1321
1322  @objc public protocol SwiftProtocol {
1323    func method()
1324  }
1325
1326This protocol can be used from Objective-C code by including a header file that
1327was generated by the Swift compiler. The declarations in that header can use
1328the ``external_source_symbol`` attribute to make Clang aware of the fact
1329that ``SwiftProtocol`` actually originates from a Swift module:
1330
1331.. code-block:: objc
1332
1333  __attribute__((external_source_symbol(language="Swift",defined_in="module")))
1334  @protocol SwiftProtocol
1335  @required
1336  - (void) method;
1337  @end
1338
1339Consequently, when 'jump-to-definition' is performed at a location that
1340references ``SwiftProtocol``, the IDE can jump to the original definition in
1341the Swift source file rather than jumping to the Objective-C declaration in the
1342auto-generated header file.
1343
1344The ``external_source_symbol`` attribute is a comma-separated list that includes
1345clauses that describe the origin and the nature of the particular declaration.
1346Those clauses can be:
1347
1348language=\ *string-literal*
1349  The name of the source language in which this declaration was defined.
1350
1351defined_in=\ *string-literal*
1352  The name of the source container in which the declaration was defined. The
1353  exact definition of source container is language-specific, e.g. Swift's
1354  source containers are modules, so ``defined_in`` should specify the Swift
1355  module name.
1356
1357generated_declaration
1358  This declaration was automatically generated by some tool.
1359
1360The clauses can be specified in any order. The clauses that are listed above are
1361all optional, but the attribute has to have at least one clause.
1362  }];
1363}
1364
1365def RequireConstantInitDocs : Documentation {
1366  let Category = DocCatVariable;
1367  let Content = [{
1368This attribute specifies that the variable to which it is attached is intended
1369to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_
1370according to the rules of [basic.start.static]. The variable is required to
1371have static or thread storage duration. If the initialization of the variable
1372is not a constant initializer an error will be produced. This attribute may
1373only be used in C++.
1374
1375Note that in C++03 strict constant expression checking is not done. Instead
1376the attribute reports if Clang can emit the variable as a constant, even if it's
1377not technically a 'constant initializer'. This behavior is non-portable.
1378
1379Static storage duration variables with constant initializers avoid hard-to-find
1380bugs caused by the indeterminate order of dynamic initialization. They can also
1381be safely used during dynamic initialization across translation units.
1382
1383This attribute acts as a compile time assertion that the requirements
1384for constant initialization have been met. Since these requirements change
1385between dialects and have subtle pitfalls it's important to fail fast instead
1386of silently falling back on dynamic initialization.
1387
1388.. code-block:: c++
1389
1390  // -std=c++14
1391  #define SAFE_STATIC [[clang::require_constant_initialization]]
1392  struct T {
1393    constexpr T(int) {}
1394    ~T(); // non-trivial
1395  };
1396  SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
1397  SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
1398  // copy initialization is not a constant expression on a non-literal type.
1399  }];
1400}
1401
1402def WarnMaybeUnusedDocs : Documentation {
1403  let Category = DocCatVariable;
1404  let Heading = "maybe_unused, unused";
1405  let Content = [{
1406When passing the ``-Wunused`` flag to Clang, entities that are unused by the
1407program may be diagnosed. The ``[[maybe_unused]]`` (or
1408``__attribute__((unused))``) attribute can be used to silence such diagnostics
1409when the entity cannot be removed. For instance, a local variable may exist
1410solely for use in an ``assert()`` statement, which makes the local variable
1411unused when ``NDEBUG`` is defined.
1412
1413The attribute may be applied to the declaration of a class, a typedef, a
1414variable, a function or method, a function parameter, an enumeration, an
1415enumerator, a non-static data member, or a label.
1416
1417.. code-block: c++
1418  #include <cassert>
1419
1420  [[maybe_unused]] void f([[maybe_unused]] bool thing1,
1421                          [[maybe_unused]] bool thing2) {
1422    [[maybe_unused]] bool b = thing1 && thing2;
1423    assert(b);
1424  }
1425  }];
1426}
1427
1428def WarnUnusedResultsDocs : Documentation {
1429  let Category = DocCatFunction;
1430  let Heading = "nodiscard, warn_unused_result";
1431  let Content  = [{
1432Clang supports the ability to diagnose when the results of a function call
1433expression are discarded under suspicious circumstances. A diagnostic is
1434generated when a function or its return type is marked with ``[[nodiscard]]``
1435(or ``__attribute__((warn_unused_result))``) and the function call appears as a
1436potentially-evaluated discarded-value expression that is not explicitly cast to
1437`void`.
1438
1439.. code-block: c++
1440  struct [[nodiscard]] error_info { /*...*/ };
1441  error_info enable_missile_safety_mode();
1442
1443  void launch_missiles();
1444  void test_missiles() {
1445    enable_missile_safety_mode(); // diagnoses
1446    launch_missiles();
1447  }
1448  error_info &foo();
1449  void f() { foo(); } // Does not diagnose, error_info is a reference.
1450  }];
1451}
1452
1453def FallthroughDocs : Documentation {
1454  let Category = DocCatStmt;
1455  let Heading = "fallthrough";
1456  let Content = [{
1457The ``fallthrough`` (or ``clang::fallthrough``) attribute is used
1458to annotate intentional fall-through
1459between switch labels.  It can only be applied to a null statement placed at a
1460point of execution between any statement and the next switch label.  It is
1461common to mark these places with a specific comment, but this attribute is
1462meant to replace comments with a more strict annotation, which can be checked
1463by the compiler.  This attribute doesn't change semantics of the code and can
1464be used wherever an intended fall-through occurs.  It is designed to mimic
1465control-flow statements like ``break;``, so it can be placed in most places
1466where ``break;`` can, but only if there are no statements on the execution path
1467between it and the next switch label.
1468
1469By default, Clang does not warn on unannotated fallthrough from one ``switch``
1470case to another. Diagnostics on fallthrough without a corresponding annotation
1471can be enabled with the ``-Wimplicit-fallthrough`` argument.
1472
1473Here is an example:
1474
1475.. code-block:: c++
1476
1477  // compile with -Wimplicit-fallthrough
1478  switch (n) {
1479  case 22:
1480  case 33:  // no warning: no statements between case labels
1481    f();
1482  case 44:  // warning: unannotated fall-through
1483    g();
1484    [[clang::fallthrough]];
1485  case 55:  // no warning
1486    if (x) {
1487      h();
1488      break;
1489    }
1490    else {
1491      i();
1492      [[clang::fallthrough]];
1493    }
1494  case 66:  // no warning
1495    p();
1496    [[clang::fallthrough]]; // warning: fallthrough annotation does not
1497                            //          directly precede case label
1498    q();
1499  case 77:  // warning: unannotated fall-through
1500    r();
1501  }
1502  }];
1503}
1504
1505def ARMInterruptDocs : Documentation {
1506  let Category = DocCatFunction;
1507  let Heading = "interrupt (ARM)";
1508  let Content = [{
1509Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
1510ARM targets. This attribute may be attached to a function definition and
1511instructs the backend to generate appropriate function entry/exit code so that
1512it can be used directly as an interrupt service routine.
1513
1514The parameter passed to the interrupt attribute is optional, but if
1515provided it must be a string literal with one of the following values: "IRQ",
1516"FIQ", "SWI", "ABORT", "UNDEF".
1517
1518The semantics are as follows:
1519
1520- If the function is AAPCS, Clang instructs the backend to realign the stack to
1521  8 bytes on entry. This is a general requirement of the AAPCS at public
1522  interfaces, but may not hold when an exception is taken. Doing this allows
1523  other AAPCS functions to be called.
1524- If the CPU is M-class this is all that needs to be done since the architecture
1525  itself is designed in such a way that functions obeying the normal AAPCS ABI
1526  constraints are valid exception handlers.
1527- If the CPU is not M-class, the prologue and epilogue are modified to save all
1528  non-banked registers that are used, so that upon return the user-mode state
1529  will not be corrupted. Note that to avoid unnecessary overhead, only
1530  general-purpose (integer) registers are saved in this way. If VFP operations
1531  are needed, that state must be saved manually.
1532
1533  Specifically, interrupt kinds other than "FIQ" will save all core registers
1534  except "lr" and "sp". "FIQ" interrupts will save r0-r7.
1535- If the CPU is not M-class, the return instruction is changed to one of the
1536  canonical sequences permitted by the architecture for exception return. Where
1537  possible the function itself will make the necessary "lr" adjustments so that
1538  the "preferred return address" is selected.
1539
1540  Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
1541  handler, where the offset from "lr" to the preferred return address depends on
1542  the execution state of the code which generated the exception. In this case
1543  a sequence equivalent to "movs pc, lr" will be used.
1544  }];
1545}
1546
1547def MipsInterruptDocs : Documentation {
1548  let Category = DocCatFunction;
1549  let Heading = "interrupt (MIPS)";
1550  let Content = [{
1551Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on
1552MIPS targets. This attribute may be attached to a function definition and instructs
1553the backend to generate appropriate function entry/exit code so that it can be used
1554directly as an interrupt service routine.
1555
1556By default, the compiler will produce a function prologue and epilogue suitable for
1557an interrupt service routine that handles an External Interrupt Controller (eic)
1558generated interrupt. This behaviour can be explicitly requested with the "eic"
1559argument.
1560
1561Otherwise, for use with vectored interrupt mode, the argument passed should be
1562of the form "vector=LEVEL" where LEVEL is one of the following values:
1563"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
1564then set the interrupt mask to the corresponding level which will mask all
1565interrupts up to and including the argument.
1566
1567The semantics are as follows:
1568
1569- The prologue is modified so that the Exception Program Counter (EPC) and
1570  Status coprocessor registers are saved to the stack. The interrupt mask is
1571  set so that the function can only be interrupted by a higher priority
1572  interrupt. The epilogue will restore the previous values of EPC and Status.
1573
1574- The prologue and epilogue are modified to save and restore all non-kernel
1575  registers as necessary.
1576
1577- The FPU is disabled in the prologue, as the floating pointer registers are not
1578  spilled to the stack.
1579
1580- The function return sequence is changed to use an exception return instruction.
1581
1582- The parameter sets the interrupt mask for the function corresponding to the
1583  interrupt level specified. If no mask is specified the interrupt mask
1584  defaults to "eic".
1585  }];
1586}
1587
1588def MicroMipsDocs : Documentation {
1589  let Category = DocCatFunction;
1590  let Content = [{
1591Clang supports the GNU style ``__attribute__((micromips))`` and
1592``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
1593may be attached to a function definition and instructs the backend to generate
1594or not to generate microMIPS code for that function.
1595
1596These attributes override the `-mmicromips` and `-mno-micromips` options
1597on the command line.
1598  }];
1599}
1600
1601def MipsLongCallStyleDocs : Documentation {
1602  let Category = DocCatFunction;
1603  let Heading = "long_call, far";
1604  let Content = [{
1605Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
1606and ``__attribute__((near))`` attributes on MIPS targets. These attributes may
1607only be added to function declarations and change the code generated
1608by the compiler when directly calling the function. The ``near`` attribute
1609allows calls to the function to be made using the ``jal`` instruction, which
1610requires the function to be located in the same naturally aligned 256MB
1611segment as the caller.  The ``long_call`` and ``far`` attributes are synonyms
1612and require the use of a different call sequence that works regardless
1613of the distance between the functions.
1614
1615These attributes have no effect for position-independent code.
1616
1617These attributes take priority over command line switches such
1618as ``-mlong-calls`` and ``-mno-long-calls``.
1619  }];
1620}
1621
1622def MipsShortCallStyleDocs : Documentation {
1623  let Category = DocCatFunction;
1624  let Heading = "short_call, near";
1625  let Content = [{
1626Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
1627``__attribute__((short__call))``, and ``__attribute__((near))`` attributes
1628on MIPS targets. These attributes may only be added to function declarations
1629and change the code generated by the compiler when directly calling
1630the function. The ``short_call`` and ``near`` attributes are synonyms and
1631allow calls to the function to be made using the ``jal`` instruction, which
1632requires the function to be located in the same naturally aligned 256MB segment
1633as the caller.  The ``long_call`` and ``far`` attributes are synonyms and
1634require the use of a different call sequence that works regardless
1635of the distance between the functions.
1636
1637These attributes have no effect for position-independent code.
1638
1639These attributes take priority over command line switches such
1640as ``-mlong-calls`` and ``-mno-long-calls``.
1641  }];
1642}
1643
1644def RISCVInterruptDocs : Documentation {
1645  let Category = DocCatFunction;
1646  let Heading = "interrupt (RISCV)";
1647  let Content = [{
1648Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV
1649targets. This attribute may be attached to a function definition and instructs
1650the backend to generate appropriate function entry/exit code so that it can be
1651used directly as an interrupt service routine.
1652
1653Permissible values for this parameter are ``user``, ``supervisor``,
1654and ``machine``. If there is no parameter, then it defaults to machine.
1655
1656Repeated interrupt attribute on the same declaration will cause a warning
1657to be emitted. In case of repeated declarations, the last one prevails.
1658
1659Refer to:
1660https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
1661https://riscv.org/specifications/privileged-isa/
1662The RISC-V Instruction Set Manual Volume II: Privileged Architecture
1663Version 1.10.
1664  }];
1665}
1666
1667def AVRInterruptDocs : Documentation {
1668  let Category = DocCatFunction;
1669  let Heading = "interrupt (AVR)";
1670  let Content = [{
1671Clang supports the GNU style ``__attribute__((interrupt))`` attribute on
1672AVR targets. This attribute may be attached to a function definition and instructs
1673the backend to generate appropriate function entry/exit code so that it can be used
1674directly as an interrupt service routine.
1675
1676On the AVR, the hardware globally disables interrupts when an interrupt is executed.
1677The first instruction of an interrupt handler declared with this attribute is a SEI
1678instruction to re-enable interrupts. See also the signal attribute that
1679does not insert a SEI instruction.
1680  }];
1681}
1682
1683def AVRSignalDocs : Documentation {
1684  let Category = DocCatFunction;
1685  let Content = [{
1686Clang supports the GNU style ``__attribute__((signal))`` attribute on
1687AVR targets. This attribute may be attached to a function definition and instructs
1688the backend to generate appropriate function entry/exit code so that it can be used
1689directly as an interrupt service routine.
1690
1691Interrupt handler functions defined with the signal attribute do not re-enable interrupts.
1692}];
1693}
1694
1695def TargetDocs : Documentation {
1696  let Category = DocCatFunction;
1697  let Content = [{
1698Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute.
1699This attribute may be attached to a function definition and instructs
1700the backend to use different code generation options than were passed on the
1701command line.
1702
1703The current set of options correspond to the existing "subtarget features" for
1704the target with or without a "-mno-" in front corresponding to the absence
1705of the feature, as well as ``arch="CPU"`` which will change the default "CPU"
1706for the function.
1707
1708Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
1709"avx", "xop" and largely correspond to the machine specific options handled by
1710the front end.
1711
1712Additionally, this attribute supports function multiversioning for ELF based
1713x86/x86-64 targets, which can be used to create multiple implementations of the
1714same function that will be resolved at runtime based on the priority of their
1715``target`` attribute strings. A function is considered a multiversioned function
1716if either two declarations of the function have different ``target`` attribute
1717strings, or if it has a ``target`` attribute string of ``default``.  For
1718example:
1719
1720  .. code-block:: c++
1721
1722    __attribute__((target("arch=atom")))
1723    void foo() {} // will be called on 'atom' processors.
1724    __attribute__((target("default")))
1725    void foo() {} // will be called on any other processors.
1726
1727All multiversioned functions must contain a ``default`` (fallback)
1728implementation, otherwise usages of the function are considered invalid.
1729Additionally, a function may not become multiversioned after its first use.
1730}];
1731}
1732
1733def MinVectorWidthDocs : Documentation {
1734  let Category = DocCatFunction;
1735  let Content = [{
1736Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This
1737attribute may be attached to a function and informs the backend that this
1738function desires vectors of at least this width to be generated. Target-specific
1739maximum vector widths still apply. This means even if you ask for something
1740larger than the target supports, you will only get what the target supports.
1741This attribute is meant to be a hint to control target heuristics that may
1742generate narrower vectors than what the target hardware supports.
1743
1744This is currently used by the X86 target to allow some CPUs that support 512-bit
1745vectors to be limited to using 256-bit vectors to avoid frequency penalties.
1746This is currently enabled with the ``-prefer-vector-width=256`` command line
1747option. The ``min_vector_width`` attribute can be used to prevent the backend
1748from trying to split vector operations to match the ``prefer-vector-width``. All
1749X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
1750use of any of the X86-specific vector builtins will implicitly set this
1751attribute on the calling function. The intent is that explicitly writing vector
1752code using the X86 intrinsics will prevent ``prefer-vector-width`` from
1753affecting the code.
1754}];
1755}
1756
1757def DocCatAMDGPUAttributes : DocumentationCategory<"AMD GPU Attributes">;
1758
1759def AMDGPUFlatWorkGroupSizeDocs : Documentation {
1760  let Category = DocCatAMDGPUAttributes;
1761  let Content = [{
1762The flat work-group size is the number of work-items in the work-group size
1763specified when the kernel is dispatched. It is the product of the sizes of the
1764x, y, and z dimension of the work-group.
1765
1766Clang supports the
1767``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the
1768AMDGPU target. This attribute may be attached to a kernel function definition
1769and is an optimization hint.
1770
1771``<min>`` parameter specifies the minimum flat work-group size, and ``<max>``
1772parameter specifies the maximum flat work-group size (must be greater than
1773``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0``
1774as ``<min>, <max>`` implies the default behavior (``128, 256``).
1775
1776If specified, the AMDGPU target backend might be able to produce better machine
1777code for barriers and perform scratch promotion by estimating available group
1778segment size.
1779
1780An error will be given if:
1781  - Specified values violate subtarget specifications;
1782  - Specified values are not compatible with values provided through other
1783    attributes.
1784  }];
1785}
1786
1787def AMDGPUWavesPerEUDocs : Documentation {
1788  let Category = DocCatAMDGPUAttributes;
1789  let Content = [{
1790A compute unit (CU) is responsible for executing the wavefronts of a work-group.
1791It is composed of one or more execution units (EU), which are responsible for
1792executing the wavefronts. An EU can have enough resources to maintain the state
1793of more than one executing wavefront. This allows an EU to hide latency by
1794switching between wavefronts in a similar way to symmetric multithreading on a
1795CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
1796resources used by a single wavefront have to be limited. For example, the number
1797of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
1798but can result in having to spill some register state to memory.
1799
1800Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))``
1801attribute for the AMDGPU target. This attribute may be attached to a kernel
1802function definition and is an optimization hint.
1803
1804``<min>`` parameter specifies the requested minimum number of waves per EU, and
1805*optional* ``<max>`` parameter specifies the requested maximum number of waves
1806per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted,
1807then there is no restriction on the maximum number of waves per EU other than
1808the one dictated by the hardware for which the kernel is compiled. Passing
1809``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits).
1810
1811If specified, this attribute allows an advanced developer to tune the number of
1812wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
1813target backend can use this information to limit resources, such as number of
1814SGPRs, number of VGPRs, size of available group and private memory segments, in
1815such a way that guarantees that at least ``<min>`` wavefronts and at most
1816``<max>`` wavefronts are able to fit within the resources of an EU. Requesting
1817more wavefronts can hide memory latency but limits available registers which
1818can result in spilling. Requesting fewer wavefronts can help reduce cache
1819thrashing, but can reduce memory latency hiding.
1820
1821This attribute controls the machine code generated by the AMDGPU target backend
1822to ensure it is capable of meeting the requested values. However, when the
1823kernel is executed, there may be other reasons that prevent meeting the request,
1824for example, there may be wavefronts from other kernels executing on the EU.
1825
1826An error will be given if:
1827  - Specified values violate subtarget specifications;
1828  - Specified values are not compatible with values provided through other
1829    attributes;
1830  - The AMDGPU target backend is unable to create machine code that can meet the
1831    request.
1832  }];
1833}
1834
1835def AMDGPUNumSGPRNumVGPRDocs : Documentation {
1836  let Category = DocCatAMDGPUAttributes;
1837  let Content = [{
1838Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
1839``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
1840target. These attributes may be attached to a kernel function definition and are
1841an optimization hint.
1842
1843If these attributes are specified, then the AMDGPU target backend will attempt
1844to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
1845number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
1846allocation requirements or constraints of the subtarget. Passing ``0`` as
1847``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
1848
1849These attributes can be used to test the AMDGPU target backend. It is
1850recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
1851resources such as SGPRs and VGPRs since it is aware of the limits for different
1852subtargets.
1853
1854An error will be given if:
1855  - Specified values violate subtarget specifications;
1856  - Specified values are not compatible with values provided through other
1857    attributes;
1858  - The AMDGPU target backend is unable to create machine code that can meet the
1859    request.
1860  }];
1861}
1862
1863def DocCatCallingConvs : DocumentationCategory<"Calling Conventions"> {
1864  let Content = [{
1865Clang supports several different calling conventions, depending on the target
1866platform and architecture. The calling convention used for a function determines
1867how parameters are passed, how results are returned to the caller, and other
1868low-level details of calling a function.
1869  }];
1870}
1871
1872def PcsDocs : Documentation {
1873  let Category = DocCatCallingConvs;
1874  let Content = [{
1875On ARM targets, this attribute can be used to select calling conventions
1876similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and
1877"aapcs-vfp".
1878  }];
1879}
1880
1881def AArch64VectorPcsDocs : Documentation {
1882  let Category = DocCatCallingConvs;
1883  let Content = [{
1884On AArch64 targets, this attribute changes the calling convention of a
1885function to preserve additional floating-point and Advanced SIMD registers
1886relative to the default calling convention used for AArch64.
1887
1888This means it is more efficient to call such functions from code that performs
1889extensive floating-point and vector calculations, because fewer live SIMD and FP
1890registers need to be saved. This property makes it well-suited for e.g.
1891floating-point or vector math library functions, which are typically leaf
1892functions that require a small number of registers.
1893
1894However, using this attribute also means that it is more expensive to call
1895a function that adheres to the default calling convention from within such
1896a function. Therefore, it is recommended that this attribute is only used
1897for leaf functions.
1898
1899For more information, see the documentation for `aarch64_vector_pcs`_ on
1900the Arm Developer website.
1901
1902.. _`aarch64_vector_pcs`: https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi
1903  }];
1904}
1905
1906def RegparmDocs : Documentation {
1907  let Category = DocCatCallingConvs;
1908  let Content = [{
1909On 32-bit x86 targets, the regparm attribute causes the compiler to pass
1910the first three integer parameters in EAX, EDX, and ECX instead of on the
1911stack. This attribute has no effect on variadic functions, and all parameters
1912are passed via the stack as normal.
1913  }];
1914}
1915
1916def SysVABIDocs : Documentation {
1917  let Category = DocCatCallingConvs;
1918  let Content = [{
1919On Windows x86_64 targets, this attribute changes the calling convention of a
1920function to match the default convention used on Sys V targets such as Linux,
1921Mac, and BSD. This attribute has no effect on other targets.
1922  }];
1923}
1924
1925def MSABIDocs : Documentation {
1926  let Category = DocCatCallingConvs;
1927  let Content = [{
1928On non-Windows x86_64 targets, this attribute changes the calling convention of
1929a function to match the default convention used on Windows x86_64. This
1930attribute has no effect on Windows targets or non-x86_64 targets.
1931  }];
1932}
1933
1934def StdCallDocs : Documentation {
1935  let Category = DocCatCallingConvs;
1936  let Content = [{
1937On 32-bit x86 targets, this attribute changes the calling convention of a
1938function to clear parameters off of the stack on return. This convention does
1939not support variadic calls or unprototyped functions in C, and has no effect on
1940x86_64 targets. This calling convention is used widely by the Windows API and
1941COM applications.  See the documentation for `__stdcall`_ on MSDN.
1942
1943.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx
1944  }];
1945}
1946
1947def FastCallDocs : Documentation {
1948  let Category = DocCatCallingConvs;
1949  let Content = [{
1950On 32-bit x86 targets, this attribute changes the calling convention of a
1951function to use ECX and EDX as register parameters and clear parameters off of
1952the stack on return. This convention does not support variadic calls or
1953unprototyped functions in C, and has no effect on x86_64 targets. This calling
1954convention is supported primarily for compatibility with existing code. Users
1955seeking register parameters should use the ``regparm`` attribute, which does
1956not require callee-cleanup.  See the documentation for `__fastcall`_ on MSDN.
1957
1958.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx
1959  }];
1960}
1961
1962def RegCallDocs : Documentation {
1963  let Category = DocCatCallingConvs;
1964  let Content = [{
1965On x86 targets, this attribute changes the calling convention to
1966`__regcall`_ convention. This convention aims to pass as many arguments
1967as possible in registers. It also tries to utilize registers for the
1968return value whenever it is possible.
1969
1970.. _`__regcall`: https://software.intel.com/en-us/node/693069
1971  }];
1972}
1973
1974def ThisCallDocs : Documentation {
1975  let Category = DocCatCallingConvs;
1976  let Content = [{
1977On 32-bit x86 targets, this attribute changes the calling convention of a
1978function to use ECX for the first parameter (typically the implicit ``this``
1979parameter of C++ methods) and clear parameters off of the stack on return. This
1980convention does not support variadic calls or unprototyped functions in C, and
1981has no effect on x86_64 targets. See the documentation for `__thiscall`_ on
1982MSDN.
1983
1984.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx
1985  }];
1986}
1987
1988def VectorCallDocs : Documentation {
1989  let Category = DocCatCallingConvs;
1990  let Content = [{
1991On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
1992convention of a function to pass vector parameters in SSE registers.
1993
1994On 32-bit x86 targets, this calling convention is similar to ``__fastcall``.
1995The first two integer parameters are passed in ECX and EDX. Subsequent integer
1996parameters are passed in memory, and callee clears the stack.  On x86_64
1997targets, the callee does *not* clear the stack, and integer parameters are
1998passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
1999convention.
2000
2001On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
2002passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
2003passed in sequential SSE registers if enough are available. If AVX is enabled,
2004256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
2005cannot be passed in registers for any reason is passed by reference, which
2006allows the caller to align the parameter memory.
2007
2008See the documentation for `__vectorcall`_ on MSDN for more details.
2009
2010.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx
2011  }];
2012}
2013
2014def DocCatConsumed : DocumentationCategory<"Consumed Annotation Checking"> {
2015  let Content = [{
2016Clang supports additional attributes for checking basic resource management
2017properties, specifically for unique objects that have a single owning reference.
2018The following attributes are currently supported, although **the implementation
2019for these annotations is currently in development and are subject to change.**
2020  }];
2021}
2022
2023def SetTypestateDocs : Documentation {
2024  let Category = DocCatConsumed;
2025  let Content = [{
2026Annotate methods that transition an object into a new state with
2027``__attribute__((set_typestate(new_state)))``.  The new state must be
2028unconsumed, consumed, or unknown.
2029  }];
2030}
2031
2032def CallableWhenDocs : Documentation {
2033  let Category = DocCatConsumed;
2034  let Content = [{
2035Use ``__attribute__((callable_when(...)))`` to indicate what states a method
2036may be called in.  Valid states are unconsumed, consumed, or unknown.  Each
2037argument to this attribute must be a quoted string.  E.g.:
2038
2039``__attribute__((callable_when("unconsumed", "unknown")))``
2040  }];
2041}
2042
2043def TestTypestateDocs : Documentation {
2044  let Category = DocCatConsumed;
2045  let Content = [{
2046Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
2047returns true if the object is in the specified state..
2048  }];
2049}
2050
2051def ParamTypestateDocs : Documentation {
2052  let Category = DocCatConsumed;
2053  let Content = [{
2054This attribute specifies expectations about function parameters.  Calls to an
2055function with annotated parameters will issue a warning if the corresponding
2056argument isn't in the expected state.  The attribute is also used to set the
2057initial state of the parameter when analyzing the function's body.
2058  }];
2059}
2060
2061def ReturnTypestateDocs : Documentation {
2062  let Category = DocCatConsumed;
2063  let Content = [{
2064The ``return_typestate`` attribute can be applied to functions or parameters.
2065When applied to a function the attribute specifies the state of the returned
2066value.  The function's body is checked to ensure that it always returns a value
2067in the specified state.  On the caller side, values returned by the annotated
2068function are initialized to the given state.
2069
2070When applied to a function parameter it modifies the state of an argument after
2071a call to the function returns.  The function's body is checked to ensure that
2072the parameter is in the expected state before returning.
2073  }];
2074}
2075
2076def ConsumableDocs : Documentation {
2077  let Category = DocCatConsumed;
2078  let Content = [{
2079Each ``class`` that uses any of the typestate annotations must first be marked
2080using the ``consumable`` attribute.  Failure to do so will result in a warning.
2081
2082This attribute accepts a single parameter that must be one of the following:
2083``unknown``, ``consumed``, or ``unconsumed``.
2084  }];
2085}
2086
2087def NoSanitizeDocs : Documentation {
2088  let Category = DocCatFunction;
2089  let Content = [{
2090Use the ``no_sanitize`` attribute on a function or a global variable
2091declaration to specify that a particular instrumentation or set of
2092instrumentations should not be applied. The attribute takes a list of
2093string literals, which have the same meaning as values accepted by the
2094``-fno-sanitize=`` flag. For example,
2095``__attribute__((no_sanitize("address", "thread")))`` specifies that
2096AddressSanitizer and ThreadSanitizer should not be applied to the
2097function or variable.
2098
2099See :ref:`Controlling Code Generation <controlling-code-generation>` for a
2100full list of supported sanitizer flags.
2101  }];
2102}
2103
2104def NoSanitizeAddressDocs : Documentation {
2105  let Category = DocCatFunction;
2106  // This function has multiple distinct spellings, and so it requires a custom
2107  // heading to be specified. The most common spelling is sufficient.
2108  let Heading = "no_sanitize_address, no_address_safety_analysis";
2109  let Content = [{
2110.. _langext-address_sanitizer:
2111
2112Use ``__attribute__((no_sanitize_address))`` on a function or a global
2113variable declaration to specify that address safety instrumentation
2114(e.g. AddressSanitizer) should not be applied.
2115  }];
2116}
2117
2118def NoSanitizeThreadDocs : Documentation {
2119  let Category = DocCatFunction;
2120  let Heading = "no_sanitize_thread";
2121  let Content = [{
2122.. _langext-thread_sanitizer:
2123
2124Use ``__attribute__((no_sanitize_thread))`` on a function declaration to
2125specify that checks for data races on plain (non-atomic) memory accesses should
2126not be inserted by ThreadSanitizer. The function is still instrumented by the
2127tool to avoid false positives and provide meaningful stack traces.
2128  }];
2129}
2130
2131def NoSanitizeMemoryDocs : Documentation {
2132  let Category = DocCatFunction;
2133  let Heading = "no_sanitize_memory";
2134  let Content = [{
2135.. _langext-memory_sanitizer:
2136
2137Use ``__attribute__((no_sanitize_memory))`` on a function declaration to
2138specify that checks for uninitialized memory should not be inserted
2139(e.g. by MemorySanitizer). The function may still be instrumented by the tool
2140to avoid false positives in other places.
2141  }];
2142}
2143
2144def DocCatTypeSafety : DocumentationCategory<"Type Safety Checking"> {
2145  let Content = [{
2146Clang supports additional attributes to enable checking type safety properties
2147that can't be enforced by the C type system. To see warnings produced by these
2148checks, ensure that -Wtype-safety is enabled. Use cases include:
2149
2150* MPI library implementations, where these attributes enable checking that
2151  the buffer type matches the passed ``MPI_Datatype``;
2152* for HDF5 library there is a similar use case to MPI;
2153* checking types of variadic functions' arguments for functions like
2154  ``fcntl()`` and ``ioctl()``.
2155
2156You can detect support for these attributes with ``__has_attribute()``.  For
2157example:
2158
2159.. code-block:: c++
2160
2161  #if defined(__has_attribute)
2162  #  if __has_attribute(argument_with_type_tag) && \
2163        __has_attribute(pointer_with_type_tag) && \
2164        __has_attribute(type_tag_for_datatype)
2165  #    define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
2166  /* ... other macros ...  */
2167  #  endif
2168  #endif
2169
2170  #if !defined(ATTR_MPI_PWT)
2171  # define ATTR_MPI_PWT(buffer_idx, type_idx)
2172  #endif
2173
2174  int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
2175      ATTR_MPI_PWT(1,3);
2176  }];
2177}
2178
2179def ArgumentWithTypeTagDocs : Documentation {
2180  let Category = DocCatTypeSafety;
2181  let Heading = "argument_with_type_tag";
2182  let Content = [{
2183Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
2184type_tag_idx)))`` on a function declaration to specify that the function
2185accepts a type tag that determines the type of some other argument.
2186
2187This attribute is primarily useful for checking arguments of variadic functions
2188(``pointer_with_type_tag`` can be used in most non-variadic cases).
2189
2190In the attribute prototype above:
2191  * ``arg_kind`` is an identifier that should be used when annotating all
2192    applicable type tags.
2193  * ``arg_idx`` provides the position of a function argument. The expected type of
2194    this function argument will be determined by the function argument specified
2195    by ``type_tag_idx``. In the code example below, "3" means that the type of the
2196    function's third argument will be determined by ``type_tag_idx``.
2197  * ``type_tag_idx`` provides the position of a function argument. This function
2198    argument will be a type tag. The type tag will determine the expected type of
2199    the argument specified by ``arg_idx``. In the code example below, "2" means
2200    that the type tag associated with the function's second argument should agree
2201    with the type of the argument specified by ``arg_idx``.
2202
2203For example:
2204
2205.. code-block:: c++
2206
2207  int fcntl(int fd, int cmd, ...)
2208      __attribute__(( argument_with_type_tag(fcntl,3,2) ));
2209  // The function's second argument will be a type tag; this type tag will
2210  // determine the expected type of the function's third argument.
2211  }];
2212}
2213
2214def PointerWithTypeTagDocs : Documentation {
2215  let Category = DocCatTypeSafety;
2216  let Heading = "pointer_with_type_tag";
2217  let Content = [{
2218Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
2219on a function declaration to specify that the function accepts a type tag that
2220determines the pointee type of some other pointer argument.
2221
2222In the attribute prototype above:
2223  * ``ptr_kind`` is an identifier that should be used when annotating all
2224    applicable type tags.
2225  * ``ptr_idx`` provides the position of a function argument; this function
2226    argument will have a pointer type. The expected pointee type of this pointer
2227    type will be determined by the function argument specified by
2228    ``type_tag_idx``. In the code example below, "1" means that the pointee type
2229    of the function's first argument will be determined by ``type_tag_idx``.
2230  * ``type_tag_idx`` provides the position of a function argument; this function
2231    argument will be a type tag. The type tag will determine the expected pointee
2232    type of the pointer argument specified by ``ptr_idx``. In the code example
2233    below, "3" means that the type tag associated with the function's third
2234    argument should agree with the pointee type of the pointer argument specified
2235    by ``ptr_idx``.
2236
2237For example:
2238
2239.. code-block:: c++
2240
2241  typedef int MPI_Datatype;
2242  int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
2243      __attribute__(( pointer_with_type_tag(mpi,1,3) ));
2244  // The function's 3rd argument will be a type tag; this type tag will
2245  // determine the expected pointee type of the function's 1st argument.
2246  }];
2247}
2248
2249def TypeTagForDatatypeDocs : Documentation {
2250  let Category = DocCatTypeSafety;
2251  let Content = [{
2252When declaring a variable, use
2253``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that
2254is tied to the ``type`` argument given to the attribute.
2255
2256In the attribute prototype above:
2257  * ``kind`` is an identifier that should be used when annotating all applicable
2258    type tags.
2259  * ``type`` indicates the name of the type.
2260
2261Clang supports annotating type tags of two forms.
2262
2263  * **Type tag that is a reference to a declared identifier.**
2264    Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that
2265    identifier:
2266
2267    .. code-block:: c++
2268
2269      typedef int MPI_Datatype;
2270      extern struct mpi_datatype mpi_datatype_int
2271          __attribute__(( type_tag_for_datatype(mpi,int) ));
2272      #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
2273      // &mpi_datatype_int is a type tag. It is tied to type "int".
2274
2275  * **Type tag that is an integral literal.**
2276    Declare a ``static const`` variable with an initializer value and attach
2277    ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration:
2278
2279    .. code-block:: c++
2280
2281      typedef int MPI_Datatype;
2282      static const MPI_Datatype mpi_datatype_int
2283          __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
2284      #define MPI_INT ((MPI_Datatype) 42)
2285      // The number 42 is a type tag. It is tied to type "int".
2286
2287
2288The ``type_tag_for_datatype`` attribute also accepts an optional third argument
2289that determines how the type of the function argument specified by either
2290``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type
2291tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the
2292function argument specified by ``arg_idx`` is compared against the type
2293associated with the type tag. Also recall that for the ``pointer_with_type_tag``
2294attribute, the pointee type of the function argument specified by ``ptr_idx`` is
2295compared against the type associated with the type tag.) There are two supported
2296values for this optional third argument:
2297
2298  * ``layout_compatible`` will cause types to be compared according to
2299    layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
2300    layout-compatibility rules for two standard-layout struct types and for two
2301    standard-layout union types). This is useful when creating a type tag
2302    associated with a struct or union type. For example:
2303
2304    .. code-block:: c++
2305
2306      /* In mpi.h */
2307      typedef int MPI_Datatype;
2308      struct internal_mpi_double_int { double d; int i; };
2309      extern struct mpi_datatype mpi_datatype_double_int
2310          __attribute__(( type_tag_for_datatype(mpi,
2311                          struct internal_mpi_double_int, layout_compatible) ));
2312
2313      #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
2314
2315      int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
2316          __attribute__(( pointer_with_type_tag(mpi,1,3) ));
2317
2318      /* In user code */
2319      struct my_pair { double a; int b; };
2320      struct my_pair *buffer;
2321      MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ...  */); // no warning because the
2322                                                       // layout of my_pair is
2323                                                       // compatible with that of
2324                                                       // internal_mpi_double_int
2325
2326      struct my_int_pair { int a; int b; }
2327      struct my_int_pair *buffer2;
2328      MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ...  */); // warning because the
2329                                                        // layout of my_int_pair
2330                                                        // does not match that of
2331                                                        // internal_mpi_double_int
2332
2333  * ``must_be_null`` specifies that the function argument specified by either
2334    ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for
2335    the ``pointer_with_type_tag`` attribute) should be a null pointer constant.
2336    The second argument to the ``type_tag_for_datatype`` attribute is ignored. For
2337    example:
2338
2339    .. code-block:: c++
2340
2341      /* In mpi.h */
2342      typedef int MPI_Datatype;
2343      extern struct mpi_datatype mpi_datatype_null
2344          __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
2345
2346      #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
2347      int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
2348          __attribute__(( pointer_with_type_tag(mpi,1,3) ));
2349
2350      /* In user code */
2351      struct my_pair { double a; int b; };
2352      struct my_pair *buffer;
2353      MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ...  */); // warning: MPI_DATATYPE_NULL
2354                                                          // was specified but buffer
2355                                                          // is not a null pointer
2356  }];
2357}
2358
2359def FlattenDocs : Documentation {
2360  let Category = DocCatFunction;
2361  let Content = [{
2362The ``flatten`` attribute causes calls within the attributed function to
2363be inlined unless it is impossible to do so, for example if the body of the
2364callee is unavailable or if the callee has the ``noinline`` attribute.
2365  }];
2366}
2367
2368def FormatDocs : Documentation {
2369  let Category = DocCatFunction;
2370  let Content = [{
2371
2372Clang supports the ``format`` attribute, which indicates that the function
2373accepts a ``printf`` or ``scanf``-like format string and corresponding
2374arguments or a ``va_list`` that contains these arguments.
2375
2376Please see `GCC documentation about format attribute
2377<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
2378about attribute syntax.
2379
2380Clang implements two kinds of checks with this attribute.
2381
2382#. Clang checks that the function with the ``format`` attribute is called with
2383   a format string that uses format specifiers that are allowed, and that
2384   arguments match the format string.  This is the ``-Wformat`` warning, it is
2385   on by default.
2386
2387#. Clang checks that the format string argument is a literal string.  This is
2388   the ``-Wformat-nonliteral`` warning, it is off by default.
2389
2390   Clang implements this mostly the same way as GCC, but there is a difference
2391   for functions that accept a ``va_list`` argument (for example, ``vprintf``).
2392   GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
2393   functions.  Clang does not warn if the format string comes from a function
2394   parameter, where the function is annotated with a compatible attribute,
2395   otherwise it warns.  For example:
2396
2397   .. code-block:: c
2398
2399     __attribute__((__format__ (__scanf__, 1, 3)))
2400     void foo(const char* s, char *buf, ...) {
2401       va_list ap;
2402       va_start(ap, buf);
2403
2404       vprintf(s, ap); // warning: format string is not a string literal
2405     }
2406
2407   In this case we warn because ``s`` contains a format string for a
2408   ``scanf``-like function, but it is passed to a ``printf``-like function.
2409
2410   If the attribute is removed, clang still warns, because the format string is
2411   not a string literal.
2412
2413   Another example:
2414
2415   .. code-block:: c
2416
2417     __attribute__((__format__ (__printf__, 1, 3)))
2418     void foo(const char* s, char *buf, ...) {
2419       va_list ap;
2420       va_start(ap, buf);
2421
2422       vprintf(s, ap); // warning
2423     }
2424
2425   In this case Clang does not warn because the format string ``s`` and
2426   the corresponding arguments are annotated.  If the arguments are
2427   incorrect, the caller of ``foo`` will receive a warning.
2428  }];
2429}
2430
2431def AlignValueDocs : Documentation {
2432  let Category = DocCatType;
2433  let Content = [{
2434The align_value attribute can be added to the typedef of a pointer type or the
2435declaration of a variable of pointer or reference type. It specifies that the
2436pointer will point to, or the reference will bind to, only objects with at
2437least the provided alignment. This alignment value must be some positive power
2438of 2.
2439
2440   .. code-block:: c
2441
2442     typedef double * aligned_double_ptr __attribute__((align_value(64)));
2443     void foo(double & x  __attribute__((align_value(128)),
2444              aligned_double_ptr y) { ... }
2445
2446If the pointer value does not have the specified alignment at runtime, the
2447behavior of the program is undefined.
2448  }];
2449}
2450
2451def FlagEnumDocs : Documentation {
2452  let Category = DocCatType;
2453  let Content = [{
2454This attribute can be added to an enumerator to signal to the compiler that it
2455is intended to be used as a flag type. This will cause the compiler to assume
2456that the range of the type includes all of the values that you can get by
2457manipulating bits of the enumerator when issuing warnings.
2458  }];
2459}
2460
2461def EnumExtensibilityDocs : Documentation {
2462  let Category = DocCatType;
2463  let Content = [{
2464Attribute ``enum_extensibility`` is used to distinguish between enum definitions
2465that are extensible and those that are not. The attribute can take either
2466``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the
2467enum type takes a value that corresponds to one of the enumerators listed in the
2468enum definition or, when the enum is annotated with ``flag_enum``, a value that
2469can be constructed using values corresponding to the enumerators. ``open``
2470indicates a variable of the enum type can take any values allowed by the
2471standard and instructs clang to be more lenient when issuing warnings.
2472
2473.. code-block:: c
2474
2475  enum __attribute__((enum_extensibility(closed))) ClosedEnum {
2476    A0, A1
2477  };
2478
2479  enum __attribute__((enum_extensibility(open))) OpenEnum {
2480    B0, B1
2481  };
2482
2483  enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
2484    C0 = 1 << 0, C1 = 1 << 1
2485  };
2486
2487  enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
2488    D0 = 1 << 0, D1 = 1 << 1
2489  };
2490
2491  void foo1() {
2492    enum ClosedEnum ce;
2493    enum OpenEnum oe;
2494    enum ClosedFlagEnum cfe;
2495    enum OpenFlagEnum ofe;
2496
2497    ce = A1;           // no warnings
2498    ce = 100;          // warning issued
2499    oe = B1;           // no warnings
2500    oe = 100;          // no warnings
2501    cfe = C0 | C1;     // no warnings
2502    cfe = C0 | C1 | 4; // warning issued
2503    ofe = D0 | D1;     // no warnings
2504    ofe = D0 | D1 | 4; // no warnings
2505  }
2506
2507  }];
2508}
2509
2510def EmptyBasesDocs : Documentation {
2511  let Category = DocCatType;
2512  let Content = [{
2513The empty_bases attribute permits the compiler to utilize the
2514empty-base-optimization more frequently.
2515This attribute only applies to struct, class, and union types.
2516It is only supported when using the Microsoft C++ ABI.
2517  }];
2518}
2519
2520def LayoutVersionDocs : Documentation {
2521  let Category = DocCatType;
2522  let Content = [{
2523The layout_version attribute requests that the compiler utilize the class
2524layout rules of a particular compiler version.
2525This attribute only applies to struct, class, and union types.
2526It is only supported when using the Microsoft C++ ABI.
2527  }];
2528}
2529
2530def LifetimeBoundDocs : Documentation {
2531  let Category = DocCatFunction;
2532  let Content = [{
2533The ``lifetimebound`` attribute indicates that a resource owned by
2534a function parameter or implicit object parameter
2535is retained by the return value of the annotated function
2536(or, for a parameter of a constructor, in the value of the constructed object).
2537It is only supported in C++.
2538
2539This attribute provides an experimental implementation of the facility
2540described in the C++ committee paper [http://wg21.link/p0936r0](P0936R0),
2541and is subject to change as the design of the corresponding functionality
2542changes.
2543  }];
2544}
2545
2546def TrivialABIDocs : Documentation {
2547  let Category = DocCatVariable;
2548  let Content = [{
2549The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union.
2550It instructs the compiler to pass and return the type using the C ABI for the
2551underlying type when the type would otherwise be considered non-trivial for the
2552purpose of calls.
2553A class annotated with `trivial_abi` can have non-trivial destructors or copy/move constructors without automatically becoming non-trivial for the purposes of calls. For example:
2554
2555  .. code-block:: c++
2556
2557    // A is trivial for the purposes of calls because `trivial_abi` makes the
2558    // user-provided special functions trivial.
2559    struct __attribute__((trivial_abi)) A {
2560      ~A();
2561      A(const A &);
2562      A(A &&);
2563      int x;
2564    };
2565
2566    // B's destructor and copy/move constructor are considered trivial for the
2567    // purpose of calls because A is trivial.
2568    struct B {
2569      A a;
2570    };
2571
2572If a type is trivial for the purposes of calls, has a non-trivial destructor,
2573and is passed as an argument by value, the convention is that the callee will
2574destroy the object before returning.
2575
2576Attribute ``trivial_abi`` has no effect in the following cases:
2577
2578- The class directly declares a virtual base or virtual methods.
2579- The class has a base class that is non-trivial for the purposes of calls.
2580- The class has a non-static data member whose type is non-trivial for the purposes of calls, which includes:
2581
2582  - classes that are non-trivial for the purposes of calls
2583  - __weak-qualified types in Objective-C++
2584  - arrays of any of the above
2585  }];
2586}
2587
2588def MSInheritanceDocs : Documentation {
2589  let Category = DocCatType;
2590  let Heading = "__single_inhertiance, __multiple_inheritance, __virtual_inheritance";
2591  let Content = [{
2592This collection of keywords is enabled under ``-fms-extensions`` and controls
2593the pointer-to-member representation used on ``*-*-win32`` targets.
2594
2595The ``*-*-win32`` targets utilize a pointer-to-member representation which
2596varies in size and alignment depending on the definition of the underlying
2597class.
2598
2599However, this is problematic when a forward declaration is only available and
2600no definition has been made yet.  In such cases, Clang is forced to utilize the
2601most general representation that is available to it.
2602
2603These keywords make it possible to use a pointer-to-member representation other
2604than the most general one regardless of whether or not the definition will ever
2605be present in the current translation unit.
2606
2607This family of keywords belong between the ``class-key`` and ``class-name``:
2608
2609.. code-block:: c++
2610
2611  struct __single_inheritance S;
2612  int S::*i;
2613  struct S {};
2614
2615This keyword can be applied to class templates but only has an effect when used
2616on full specializations:
2617
2618.. code-block:: c++
2619
2620  template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
2621  template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
2622  template <> struct __single_inheritance A<int, float>;
2623
2624Note that choosing an inheritance model less general than strictly necessary is
2625an error:
2626
2627.. code-block:: c++
2628
2629  struct __multiple_inheritance S; // error: inheritance model does not match definition
2630  int S::*i;
2631  struct S {};
2632}];
2633}
2634
2635def MSNoVTableDocs : Documentation {
2636  let Category = DocCatType;
2637  let Content = [{
2638This attribute can be added to a class declaration or definition to signal to
2639the compiler that constructors and destructors will not reference the virtual
2640function table. It is only supported when using the Microsoft C++ ABI.
2641  }];
2642}
2643
2644def OptnoneDocs : Documentation {
2645  let Category = DocCatFunction;
2646  let Content = [{
2647The ``optnone`` attribute suppresses essentially all optimizations
2648on a function or method, regardless of the optimization level applied to
2649the compilation unit as a whole.  This is particularly useful when you
2650need to debug a particular function, but it is infeasible to build the
2651entire application without optimization.  Avoiding optimization on the
2652specified function can improve the quality of the debugging information
2653for that function.
2654
2655This attribute is incompatible with the ``always_inline`` and ``minsize``
2656attributes.
2657  }];
2658}
2659
2660def LoopHintDocs : Documentation {
2661  let Category = DocCatStmt;
2662  let Heading = "#pragma clang loop";
2663  let Content = [{
2664The ``#pragma clang loop`` directive allows loop optimization hints to be
2665specified for the subsequent loop. The directive allows pipelining to be
2666disabled, or vectorization, interleaving, and unrolling to be enabled or disabled.
2667Vector width, interleave count, unrolling count, and the initiation interval
2668for pipelining can be explicitly specified. See `language extensions
2669<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
2670for details.
2671  }];
2672}
2673
2674def UnrollHintDocs : Documentation {
2675  let Category = DocCatStmt;
2676  let Heading = "#pragma unroll, #pragma nounroll";
2677  let Content = [{
2678Loop unrolling optimization hints can be specified with ``#pragma unroll`` and
2679``#pragma nounroll``. The pragma is placed immediately before a for, while,
2680do-while, or c++11 range-based for loop.
2681
2682Specifying ``#pragma unroll`` without a parameter directs the loop unroller to
2683attempt to fully unroll the loop if the trip count is known at compile time and
2684attempt to partially unroll the loop if the trip count is not known at compile
2685time:
2686
2687.. code-block:: c++
2688
2689  #pragma unroll
2690  for (...) {
2691    ...
2692  }
2693
2694Specifying the optional parameter, ``#pragma unroll _value_``, directs the
2695unroller to unroll the loop ``_value_`` times.  The parameter may optionally be
2696enclosed in parentheses:
2697
2698.. code-block:: c++
2699
2700  #pragma unroll 16
2701  for (...) {
2702    ...
2703  }
2704
2705  #pragma unroll(16)
2706  for (...) {
2707    ...
2708  }
2709
2710Specifying ``#pragma nounroll`` indicates that the loop should not be unrolled:
2711
2712.. code-block:: c++
2713
2714  #pragma nounroll
2715  for (...) {
2716    ...
2717  }
2718
2719``#pragma unroll`` and ``#pragma unroll _value_`` have identical semantics to
2720``#pragma clang loop unroll(full)`` and
2721``#pragma clang loop unroll_count(_value_)`` respectively. ``#pragma nounroll``
2722is equivalent to ``#pragma clang loop unroll(disable)``.  See
2723`language extensions
2724<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
2725for further details including limitations of the unroll hints.
2726  }];
2727}
2728
2729def PipelineHintDocs : Documentation {
2730  let Category = DocCatStmt;
2731  let Heading = "#pragma clang loop pipeline, #pragma clang loop pipeline_initiation_interval";
2732  let Content = [{
2733    Software Pipelining optimization is a technique used to optimize loops by
2734  utilizing instruction-level parallelism. It reorders loop instructions to
2735  overlap iterations. As a result, the next iteration starts before the previous
2736  iteration has finished. The module scheduling technique creates a schedule for
2737  one iteration such that when repeating at regular intervals, no inter-iteration
2738  dependencies are violated. This constant interval(in cycles) between the start
2739  of iterations is called the initiation interval. i.e. The initiation interval
2740  is the number of cycles between two iterations of an unoptimized loop in the
2741  newly created schedule. A new, optimized loop is created such that a single iteration
2742  of the loop executes in the same number of cycles as the initiation interval.
2743    For further details see <https://llvm.org/pubs/2005-06-17-LattnerMSThesis-book.pdf>.
2744
2745  ``#pragma clang loop pipeline and #pragma loop pipeline_initiation_interval``
2746  could be used as hints for the software pipelining optimization. The pragma is
2747  placed immediately before a for, while, do-while, or a C++11 range-based for
2748  loop.
2749
2750  Using ``#pragma clang loop pipeline(disable)`` avoids the software pipelining
2751  optimization. The disable state can only be specified:
2752
2753  .. code-block:: c++
2754
2755  #pragma clang loop pipeline(disable)
2756  for (...) {
2757    ...
2758  }
2759
2760  Using ``#pragma loop pipeline_initiation_interval`` instructs
2761  the software pipeliner to try the specified initiation interval.
2762  If a schedule was found then the resulting loop iteration would have
2763  the specified cycle count. If a schedule was not found then loop
2764  remains unchanged. The initiation interval must be a positive number
2765  greater than zero:
2766
2767  .. code-block:: c++
2768
2769  #pragma loop pipeline_initiation_interval(10)
2770  for (...) {
2771    ...
2772  }
2773
2774  }];
2775}
2776
2777
2778
2779def OpenCLUnrollHintDocs : Documentation {
2780  let Category = DocCatStmt;
2781  let Content = [{
2782The opencl_unroll_hint attribute qualifier can be used to specify that a loop
2783(for, while and do loops) can be unrolled. This attribute qualifier can be
2784used to specify full unrolling or partial unrolling by a specified amount.
2785This is a compiler hint and the compiler may ignore this directive. See
2786`OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_
2787s6.11.5 for details.
2788  }];
2789}
2790
2791def OpenCLIntelReqdSubGroupSizeDocs : Documentation {
2792  let Category = DocCatStmt;
2793  let Content = [{
2794The optional attribute intel_reqd_sub_group_size can be used to indicate that
2795the kernel must be compiled and executed with the specified subgroup size. When
2796this attribute is present, get_max_sub_group_size() is guaranteed to return the
2797specified integer value. This is important for the correctness of many subgroup
2798algorithms, and in some cases may be used by the compiler to generate more optimal
2799code. See `cl_intel_required_subgroup_size
2800<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>`
2801for details.
2802  }];
2803}
2804
2805def OpenCLAccessDocs : Documentation {
2806  let Category = DocCatStmt;
2807  let Heading = "__read_only, __write_only, __read_write (read_only, write_only, read_write)";
2808  let Content = [{
2809The access qualifiers must be used with image object arguments or pipe arguments
2810to declare if they are being read or written by a kernel or function.
2811
2812The read_only/__read_only, write_only/__write_only and read_write/__read_write
2813names are reserved for use as access qualifiers and shall not be used otherwise.
2814
2815.. code-block:: c
2816
2817  kernel void
2818  foo (read_only image2d_t imageA,
2819       write_only image2d_t imageB) {
2820    ...
2821  }
2822
2823In the above example imageA is a read-only 2D image object, and imageB is a
2824write-only 2D image object.
2825
2826The read_write (or __read_write) qualifier can not be used with pipe.
2827
2828More details can be found in the OpenCL C language Spec v2.0, Section 6.6.
2829    }];
2830}
2831
2832def DocOpenCLAddressSpaces : DocumentationCategory<"OpenCL Address Spaces"> {
2833  let Content = [{
2834The address space qualifier may be used to specify the region of memory that is
2835used to allocate the object. OpenCL supports the following address spaces:
2836__generic(generic), __global(global), __local(local), __private(private),
2837__constant(constant).
2838
2839  .. code-block:: c
2840
2841    __constant int c = ...;
2842
2843    __generic int* foo(global int* g) {
2844      __local int* l;
2845      private int p;
2846      ...
2847      return l;
2848    }
2849
2850More details can be found in the OpenCL C language Spec v2.0, Section 6.5.
2851  }];
2852}
2853
2854def OpenCLAddressSpaceGenericDocs : Documentation {
2855  let Category = DocOpenCLAddressSpaces;
2856  let Content = [{
2857The generic address space attribute is only available with OpenCL v2.0 and later.
2858It can be used with pointer types. Variables in global and local scope and
2859function parameters in non-kernel functions can have the generic address space
2860type attribute. It is intended to be a placeholder for any other address space
2861except for '__constant' in OpenCL code which can be used with multiple address
2862spaces.
2863  }];
2864}
2865
2866def OpenCLAddressSpaceConstantDocs : Documentation {
2867  let Category = DocOpenCLAddressSpaces;
2868  let Content = [{
2869The constant address space attribute signals that an object is located in
2870a constant (non-modifiable) memory region. It is available to all work items.
2871Any type can be annotated with the constant address space attribute. Objects
2872with the constant address space qualifier can be declared in any scope and must
2873have an initializer.
2874  }];
2875}
2876
2877def OpenCLAddressSpaceGlobalDocs : Documentation {
2878  let Category = DocOpenCLAddressSpaces;
2879  let Content = [{
2880The global address space attribute specifies that an object is allocated in
2881global memory, which is accessible by all work items. The content stored in this
2882memory area persists between kernel executions. Pointer types to the global
2883address space are allowed as function parameters or local variables. Starting
2884with OpenCL v2.0, the global address space can be used with global (program
2885scope) variables and static local variable as well.
2886  }];
2887}
2888
2889def OpenCLAddressSpaceLocalDocs : Documentation {
2890  let Category = DocOpenCLAddressSpaces;
2891  let Content = [{
2892The local address space specifies that an object is allocated in the local (work
2893group) memory area, which is accessible to all work items in the same work
2894group. The content stored in this memory region is not accessible after
2895the kernel execution ends. In a kernel function scope, any variable can be in
2896the local address space. In other scopes, only pointer types to the local address
2897space are allowed. Local address space variables cannot have an initializer.
2898  }];
2899}
2900
2901def OpenCLAddressSpacePrivateDocs : Documentation {
2902  let Category = DocOpenCLAddressSpaces;
2903  let Content = [{
2904The private address space specifies that an object is allocated in the private
2905(work item) memory. Other work items cannot access the same memory area and its
2906content is destroyed after work item execution ends. Local variables can be
2907declared in the private address space. Function arguments are always in the
2908private address space. Kernel function arguments of a pointer or an array type
2909cannot point to the private address space.
2910  }];
2911}
2912
2913def OpenCLNoSVMDocs : Documentation {
2914  let Category = DocCatVariable;
2915  let Content = [{
2916OpenCL 2.0 supports the optional ``__attribute__((nosvm))`` qualifier for
2917pointer variable. It informs the compiler that the pointer does not refer
2918to a shared virtual memory region. See OpenCL v2.0 s6.7.2 for details.
2919
2920Since it is not widely used and has been removed from OpenCL 2.1, it is ignored
2921by Clang.
2922  }];
2923}
2924def NullabilityDocs : DocumentationCategory<"Nullability Attributes"> {
2925  let Content = [{
2926Whether 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``).
2927
2928The 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:
2929
2930  .. code-block:: c
2931
2932    // No meaningful result when 'ptr' is null (here, it happens to be undefined behavior).
2933    int fetch(int * _Nonnull ptr) { return *ptr; }
2934
2935    // 'ptr' may be null.
2936    int fetch_or_zero(int * _Nullable ptr) {
2937      return ptr ? *ptr : 0;
2938    }
2939
2940    // A nullable pointer to non-null pointers to const characters.
2941    const char *join_strings(const char * _Nonnull * _Nullable strings, unsigned n);
2942
2943In 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:
2944
2945  .. code-block:: objective-c
2946
2947    @interface NSView : NSResponder
2948      - (nullable NSView *)ancestorSharedWithView:(nonnull NSView *)aView;
2949      @property (assign, nullable) NSView *superview;
2950      @property (readonly, nonnull) NSArray *subviews;
2951    @end
2952  }];
2953}
2954
2955def TypeNonNullDocs : Documentation {
2956  let Category = NullabilityDocs;
2957  let Content = [{
2958The ``_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:
2959
2960  .. code-block:: c
2961
2962    int fetch(int * _Nonnull ptr);
2963
2964a 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.
2965  }];
2966}
2967
2968def TypeNullableDocs : Documentation {
2969  let Category = NullabilityDocs;
2970  let Content = [{
2971The ``_Nullable`` nullability qualifier indicates that a value of the ``_Nullable`` pointer type can be null. For example, given:
2972
2973  .. code-block:: c
2974
2975    int fetch_or_zero(int * _Nullable ptr);
2976
2977a caller of ``fetch_or_zero`` can provide null.
2978  }];
2979}
2980
2981def TypeNullUnspecifiedDocs : Documentation {
2982  let Category = NullabilityDocs;
2983  let Content = [{
2984The ``_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.
2985  }];
2986}
2987
2988def NonNullDocs : Documentation {
2989  let Category = NullabilityDocs;
2990  let Content = [{
2991The ``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:
2992
2993  .. code-block:: c
2994
2995    extern void * my_memcpy (void *dest, const void *src, size_t len)
2996                    __attribute__((nonnull (1, 2)));
2997
2998Here, the ``nonnull`` attribute indicates that parameters 1 and 2
2999cannot have a null value. Omitting the parenthesized list of parameter indices means that all parameters of pointer type cannot be null:
3000
3001  .. code-block:: c
3002
3003    extern void * my_memcpy (void *dest, const void *src, size_t len)
3004                    __attribute__((nonnull));
3005
3006Clang 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:
3007
3008  .. code-block:: c
3009
3010    extern void * my_memcpy (void *dest __attribute__((nonnull)),
3011                             const void *src __attribute__((nonnull)), size_t len);
3012
3013Note 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.
3014  }];
3015}
3016
3017def ReturnsNonNullDocs : Documentation {
3018  let Category = NullabilityDocs;
3019  let Content = [{
3020The ``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:
3021
3022  .. code-block:: c
3023
3024    extern void * malloc (size_t size) __attribute__((returns_nonnull));
3025
3026The ``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
3027}];
3028}
3029
3030def NoAliasDocs : Documentation {
3031  let Category = DocCatFunction;
3032  let Content = [{
3033The ``noalias`` attribute indicates that the only memory accesses inside
3034function are loads and stores from objects pointed to by its pointer-typed
3035arguments, with arbitrary offsets.
3036  }];
3037}
3038
3039def OMPDeclareSimdDocs : Documentation {
3040  let Category = DocCatFunction;
3041  let Heading = "#pragma omp declare simd";
3042  let Content = [{
3043The `declare simd` construct can be applied to a function to enable the creation
3044of one or more versions that can process multiple arguments using SIMD
3045instructions from a single invocation in a SIMD loop. The `declare simd`
3046directive is a declarative directive. There may be multiple `declare simd`
3047directives for a function. The use of a `declare simd` construct on a function
3048enables the creation of SIMD versions of the associated function that can be
3049used to process multiple arguments from a single invocation from a SIMD loop
3050concurrently.
3051The syntax of the `declare simd` construct is as follows:
3052
3053  .. code-block:: none
3054
3055    #pragma omp declare simd [clause[[,] clause] ...] new-line
3056    [#pragma omp declare simd [clause[[,] clause] ...] new-line]
3057    [...]
3058    function definition or declaration
3059
3060where clause is one of the following:
3061
3062  .. code-block:: none
3063
3064    simdlen(length)
3065    linear(argument-list[:constant-linear-step])
3066    aligned(argument-list[:alignment])
3067    uniform(argument-list)
3068    inbranch
3069    notinbranch
3070
3071  }];
3072}
3073
3074def OMPDeclareTargetDocs : Documentation {
3075  let Category = DocCatFunction;
3076  let Heading = "#pragma omp declare target";
3077  let Content = [{
3078The `declare target` directive specifies that variables and functions are mapped
3079to a device for OpenMP offload mechanism.
3080
3081The syntax of the declare target directive is as follows:
3082
3083  .. code-block:: c
3084
3085    #pragma omp declare target new-line
3086    declarations-definition-seq
3087    #pragma omp end declare target new-line
3088  }];
3089}
3090
3091def NoStackProtectorDocs : Documentation {
3092  let Category = DocCatFunction;
3093  let Content = [{
3094Clang supports the ``__attribute__((no_stack_protector))`` attribute which disables
3095the stack protector on the specified function. This attribute is useful for
3096selectively disabling the stack protector on some functions when building with
3097``-fstack-protector`` compiler option.
3098
3099For example, it disables the stack protector for the function ``foo`` but function
3100``bar`` will still be built with the stack protector with the ``-fstack-protector``
3101option.
3102
3103.. code-block:: c
3104
3105    int __attribute__((no_stack_protector))
3106    foo (int x); // stack protection will be disabled for foo.
3107
3108    int bar(int y); // bar can be built with the stack protector.
3109
3110    }];
3111}
3112
3113def NotTailCalledDocs : Documentation {
3114  let Category = DocCatFunction;
3115  let Content = [{
3116The ``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``.
3117
3118For example, it prevents tail-call optimization in the following case:
3119
3120  .. code-block:: c
3121
3122    int __attribute__((not_tail_called)) foo1(int);
3123
3124    int foo2(int a) {
3125      return foo1(a); // No tail-call optimization on direct calls.
3126    }
3127
3128However, it doesn't prevent tail-call optimization in this case:
3129
3130  .. code-block:: c
3131
3132    int __attribute__((not_tail_called)) foo1(int);
3133
3134    int foo2(int a) {
3135      int (*fn)(int) = &foo1;
3136
3137      // not_tail_called has no effect on an indirect call even if the call can be
3138      // resolved at compile time.
3139      return (*fn)(a);
3140    }
3141
3142Marking virtual functions as ``not_tail_called`` is an error:
3143
3144  .. code-block:: c++
3145
3146    class Base {
3147    public:
3148      // not_tail_called on a virtual function is an error.
3149      [[clang::not_tail_called]] virtual int foo1();
3150
3151      virtual int foo2();
3152
3153      // Non-virtual functions can be marked ``not_tail_called``.
3154      [[clang::not_tail_called]] int foo3();
3155    };
3156
3157    class Derived1 : public Base {
3158    public:
3159      int foo1() override;
3160
3161      // not_tail_called on a virtual function is an error.
3162      [[clang::not_tail_called]] int foo2() override;
3163    };
3164  }];
3165}
3166
3167def NoThrowDocs : Documentation {
3168  let Category = DocCatFunction;
3169  let Content = [{
3170Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style
3171``__declspec(nothrow)`` attribute as an equivalent of `noexcept` on function
3172declarations. This attribute informs the compiler that the annotated function
3173does not throw an exception. This prevents exception-unwinding. This attribute
3174is particularly useful on functions in the C Standard Library that are
3175guaranteed to not throw an exception.
3176    }];
3177}
3178
3179def InternalLinkageDocs : Documentation {
3180  let Category = DocCatFunction;
3181  let Content = [{
3182The ``internal_linkage`` attribute changes the linkage type of the declaration to internal.
3183This is similar to C-style ``static``, but can be used on classes and class methods. When applied to a class definition,
3184this attribute affects all methods and static data members of that class.
3185This can be used to contain the ABI of a C++ library by excluding unwanted class methods from the export tables.
3186  }];
3187}
3188
3189def ExcludeFromExplicitInstantiationDocs : Documentation {
3190  let Category = DocCatFunction;
3191  let Content = [{
3192The ``exclude_from_explicit_instantiation`` attribute opts-out a member of a
3193class template from being part of explicit template instantiations of that
3194class template. This means that an explicit instantiation will not instantiate
3195members of the class template marked with the attribute, but also that code
3196where an extern template declaration of the enclosing class template is visible
3197will not take for granted that an external instantiation of the class template
3198would provide those members (which would otherwise be a link error, since the
3199explicit instantiation won't provide those members). For example, let's say we
3200don't want the ``data()`` method to be part of libc++'s ABI. To make sure it
3201is not exported from the dylib, we give it hidden visibility:
3202
3203  .. code-block:: c++
3204
3205    // in <string>
3206    template <class CharT>
3207    class basic_string {
3208    public:
3209      __attribute__((__visibility__("hidden")))
3210      const value_type* data() const noexcept { ... }
3211    };
3212
3213    template class basic_string<char>;
3214
3215Since an explicit template instantiation declaration for ``basic_string<char>``
3216is provided, the compiler is free to assume that ``basic_string<char>::data()``
3217will be provided by another translation unit, and it is free to produce an
3218external call to this function. However, since ``data()`` has hidden visibility
3219and the explicit template instantiation is provided in a shared library (as
3220opposed to simply another translation unit), ``basic_string<char>::data()``
3221won't be found and a link error will ensue. This happens because the compiler
3222assumes that ``basic_string<char>::data()`` is part of the explicit template
3223instantiation declaration, when it really isn't. To tell the compiler that
3224``data()`` is not part of the explicit template instantiation declaration, the
3225``exclude_from_explicit_instantiation`` attribute can be used:
3226
3227  .. code-block:: c++
3228
3229    // in <string>
3230    template <class CharT>
3231    class basic_string {
3232    public:
3233      __attribute__((__visibility__("hidden")))
3234      __attribute__((exclude_from_explicit_instantiation))
3235      const value_type* data() const noexcept { ... }
3236    };
3237
3238    template class basic_string<char>;
3239
3240Now, the compiler won't assume that ``basic_string<char>::data()`` is provided
3241externally despite there being an explicit template instantiation declaration:
3242the compiler will implicitly instantiate ``basic_string<char>::data()`` in the
3243TUs where it is used.
3244
3245This attribute can be used on static and non-static member functions of class
3246templates, static data members of class templates and member classes of class
3247templates.
3248  }];
3249}
3250
3251def DisableTailCallsDocs : Documentation {
3252  let Category = DocCatFunction;
3253  let Content = [{
3254The ``disable_tail_calls`` attribute instructs the backend to not perform tail call optimization inside the marked function.
3255
3256For example:
3257
3258  .. code-block:: c
3259
3260    int callee(int);
3261
3262    int foo(int a) __attribute__((disable_tail_calls)) {
3263      return callee(a); // This call is not tail-call optimized.
3264    }
3265
3266Marking virtual functions as ``disable_tail_calls`` is legal.
3267
3268  .. code-block:: c++
3269
3270    int callee(int);
3271
3272    class Base {
3273    public:
3274      [[clang::disable_tail_calls]] virtual int foo1() {
3275        return callee(); // This call is not tail-call optimized.
3276      }
3277    };
3278
3279    class Derived1 : public Base {
3280    public:
3281      int foo1() override {
3282        return callee(); // This call is tail-call optimized.
3283      }
3284    };
3285
3286  }];
3287}
3288
3289def AnyX86NoCallerSavedRegistersDocs : Documentation {
3290  let Category = DocCatFunction;
3291  let Content = [{
3292Use this attribute to indicate that the specified function has no
3293caller-saved registers. That is, all registers are callee-saved except for
3294registers used for passing parameters to the function or returning parameters
3295from the function.
3296The compiler saves and restores any modified registers that were not used for
3297passing or returning arguments to the function.
3298
3299The user can call functions specified with the 'no_caller_saved_registers'
3300attribute from an interrupt handler without saving and restoring all
3301call-clobbered registers.
3302
3303Note that 'no_caller_saved_registers' attribute is not a calling convention.
3304In fact, it only overrides the decision of which registers should be saved by
3305the caller, but not how the parameters are passed from the caller to the callee.
3306
3307For example:
3308
3309  .. code-block:: c
3310
3311    __attribute__ ((no_caller_saved_registers, fastcall))
3312    void f (int arg1, int arg2) {
3313      ...
3314    }
3315
3316  In this case parameters 'arg1' and 'arg2' will be passed in registers.
3317  In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as
3318  register parameters. However, it will not assume any scratch registers and
3319  should save and restore any modified registers except for ECX and EDX.
3320  }];
3321}
3322
3323def X86ForceAlignArgPointerDocs : Documentation {
3324  let Category = DocCatFunction;
3325  let Content = [{
3326Use this attribute to force stack alignment.
3327
3328Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
3329(like 'movaps') that work with the stack require operands to be 16-byte aligned.
3330This attribute realigns the stack in the function prologue to make sure the
3331stack can be used with SSE instructions.
3332
3333Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
3334Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
3335rare cases where the caller does not align the stack properly (e.g. flow
3336jumps from i386 arch code).
3337
3338  .. code-block:: c
3339
3340    __attribute__ ((force_align_arg_pointer))
3341    void f () {
3342      ...
3343    }
3344
3345  }];
3346}
3347
3348def AnyX86NoCfCheckDocs : Documentation{
3349  let Category = DocCatFunction;
3350  let Content = [{
3351Jump Oriented Programming attacks rely on tampering with addresses used by
3352indirect call / jmp, e.g. redirect control-flow to non-programmer
3353intended bytes in the binary.
3354X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
3355Enforcement Technology (CET). IBT instruments ENDBR instructions used to
3356specify valid targets of indirect call / jmp.
3357The ``nocf_check`` attribute has two roles:
33581. Appertains to a function - do not add ENDBR instruction at the beginning of
3359the function.
33602. Appertains to a function pointer - do not track the target function of this
3361pointer (by adding nocf_check prefix to the indirect-call instruction).
3362}];
3363}
3364
3365def SwiftCallDocs : Documentation {
3366  let Category = DocCatVariable;
3367  let Content = [{
3368The ``swiftcall`` attribute indicates that a function should be called
3369using the Swift calling convention for a function or function pointer.
3370
3371The lowering for the Swift calling convention, as described by the Swift
3372ABI documentation, occurs in multiple phases.  The first, "high-level"
3373phase breaks down the formal parameters and results into innately direct
3374and indirect components, adds implicit paraameters for the generic
3375signature, and assigns the context and error ABI treatments to parameters
3376where applicable.  The second phase breaks down the direct parameters
3377and results from the first phase and assigns them to registers or the
3378stack.  The ``swiftcall`` convention only handles this second phase of
3379lowering; the C function type must accurately reflect the results
3380of the first phase, as follows:
3381
3382- Results classified as indirect by high-level lowering should be
3383  represented as parameters with the ``swift_indirect_result`` attribute.
3384
3385- Results classified as direct by high-level lowering should be represented
3386  as follows:
3387
3388  - First, remove any empty direct results.
3389
3390  - If there are no direct results, the C result type should be ``void``.
3391
3392  - If there is one direct result, the C result type should be a type with
3393    the exact layout of that result type.
3394
3395  - If there are a multiple direct results, the C result type should be
3396    a struct type with the exact layout of a tuple of those results.
3397
3398- Parameters classified as indirect by high-level lowering should be
3399  represented as parameters of pointer type.
3400
3401- Parameters classified as direct by high-level lowering should be
3402  omitted if they are empty types; otherwise, they should be represented
3403  as a parameter type with a layout exactly matching the layout of the
3404  Swift parameter type.
3405
3406- The context parameter, if present, should be represented as a trailing
3407  parameter with the ``swift_context`` attribute.
3408
3409- The error result parameter, if present, should be represented as a
3410  trailing parameter (always following a context parameter) with the
3411  ``swift_error_result`` attribute.
3412
3413``swiftcall`` does not support variadic arguments or unprototyped functions.
3414
3415The parameter ABI treatment attributes are aspects of the function type.
3416A function type which which applies an ABI treatment attribute to a
3417parameter is a different type from an otherwise-identical function type
3418that does not.  A single parameter may not have multiple ABI treatment
3419attributes.
3420
3421Support for this feature is target-dependent, although it should be
3422supported on every target that Swift supports.  Query for this support
3423with ``__has_attribute(swiftcall)``.  This implies support for the
3424``swift_context``, ``swift_error_result``, and ``swift_indirect_result``
3425attributes.
3426  }];
3427}
3428
3429def SwiftContextDocs : Documentation {
3430  let Category = DocCatVariable;
3431  let Content = [{
3432The ``swift_context`` attribute marks a parameter of a ``swiftcall``
3433function as having the special context-parameter ABI treatment.
3434
3435This treatment generally passes the context value in a special register
3436which is normally callee-preserved.
3437
3438A ``swift_context`` parameter must either be the last parameter or must be
3439followed by a ``swift_error_result`` parameter (which itself must always be
3440the last parameter).
3441
3442A context parameter must have pointer or reference type.
3443  }];
3444}
3445
3446def SwiftErrorResultDocs : Documentation {
3447  let Category = DocCatVariable;
3448  let Content = [{
3449The ``swift_error_result`` attribute marks a parameter of a ``swiftcall``
3450function as having the special error-result ABI treatment.
3451
3452This treatment generally passes the underlying error value in and out of
3453the function through a special register which is normally callee-preserved.
3454This is modeled in C by pretending that the register is addressable memory:
3455
3456- The caller appears to pass the address of a variable of pointer type.
3457  The current value of this variable is copied into the register before
3458  the call; if the call returns normally, the value is copied back into the
3459  variable.
3460
3461- The callee appears to receive the address of a variable.  This address
3462  is actually a hidden location in its own stack, initialized with the
3463  value of the register upon entry.  When the function returns normally,
3464  the value in that hidden location is written back to the register.
3465
3466A ``swift_error_result`` parameter must be the last parameter, and it must be
3467preceded by a ``swift_context`` parameter.
3468
3469A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some
3470type T.  Note that no qualifiers are permitted on the intermediate level.
3471
3472It is undefined behavior if the caller does not pass a pointer or
3473reference to a valid object.
3474
3475The standard convention is that the error value itself (that is, the
3476value stored in the apparent argument) will be null upon function entry,
3477but this is not enforced by the ABI.
3478  }];
3479}
3480
3481def SwiftIndirectResultDocs : Documentation {
3482  let Category = DocCatVariable;
3483  let Content = [{
3484The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall``
3485function as having the special indirect-result ABI treatment.
3486
3487This treatment gives the parameter the target's normal indirect-result
3488ABI treatment, which may involve passing it differently from an ordinary
3489parameter.  However, only the first indirect result will receive this
3490treatment.  Furthermore, low-level lowering may decide that a direct result
3491must be returned indirectly; if so, this will take priority over the
3492``swift_indirect_result`` parameters.
3493
3494A ``swift_indirect_result`` parameter must either be the first parameter or
3495follow another ``swift_indirect_result`` parameter.
3496
3497A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for
3498some object type ``T``.  If ``T`` is a complete type at the point of
3499definition of a function, it is undefined behavior if the argument
3500value does not point to storage of adequate size and alignment for a
3501value of type ``T``.
3502
3503Making indirect results explicit in the signature allows C functions to
3504directly construct objects into them without relying on language
3505optimizations like C++'s named return value optimization (NRVO).
3506  }];
3507}
3508
3509def SuppressDocs : Documentation {
3510  let Category = DocCatStmt;
3511  let Content = [{
3512The ``[[gsl::suppress]]`` attribute suppresses specific
3513clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable
3514way. The attribute can be attached to declarations, statements, and at
3515namespace scope.
3516
3517.. code-block:: c++
3518
3519  [[gsl::suppress("Rh-public")]]
3520  void f_() {
3521    int *p;
3522    [[gsl::suppress("type")]] {
3523      p = reinterpret_cast<int*>(7);
3524    }
3525  }
3526  namespace N {
3527    [[clang::suppress("type", "bounds")]];
3528    ...
3529  }
3530
3531.. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement
3532  }];
3533}
3534
3535def AbiTagsDocs : Documentation {
3536  let Category = DocCatFunction;
3537  let Content = [{
3538The ``abi_tag`` attribute can be applied to a function, variable, class or
3539inline namespace declaration to modify the mangled name of the entity. It gives
3540the ability to distinguish between different versions of the same entity but
3541with different ABI versions supported. For example, a newer version of a class
3542could have a different set of data members and thus have a different size. Using
3543the ``abi_tag`` attribute, it is possible to have different mangled names for
3544a global variable of the class type. Therefore, the old code could keep using
3545the old manged name and the new code will use the new mangled name with tags.
3546  }];
3547}
3548
3549def PreserveMostDocs : Documentation {
3550  let Category = DocCatCallingConvs;
3551  let Content = [{
3552On X86-64 and AArch64 targets, this attribute changes the calling convention of
3553a function. The ``preserve_most`` calling convention attempts to make the code
3554in the caller as unintrusive as possible. This convention behaves identically
3555to the ``C`` calling convention on how arguments and return values are passed,
3556but it uses a different set of caller/callee-saved registers. This alleviates
3557the burden of saving and recovering a large register set before and after the
3558call in the caller. If the arguments are passed in callee-saved registers,
3559then they will be preserved by the callee across the call. This doesn't
3560apply for values returned in callee-saved registers.
3561
3562- On X86-64 the callee preserves all general purpose registers, except for
3563  R11. R11 can be used as a scratch register. Floating-point registers
3564  (XMMs/YMMs) are not preserved and need to be saved by the caller.
3565
3566The idea behind this convention is to support calls to runtime functions
3567that have a hot path and a cold path. The hot path is usually a small piece
3568of code that doesn't use many registers. The cold path might need to call out to
3569another function and therefore only needs to preserve the caller-saved
3570registers, which haven't already been saved by the caller. The
3571`preserve_most` calling convention is very similar to the ``cold`` calling
3572convention in terms of caller/callee-saved registers, but they are used for
3573different types of function calls. ``coldcc`` is for function calls that are
3574rarely executed, whereas `preserve_most` function calls are intended to be
3575on the hot path and definitely executed a lot. Furthermore ``preserve_most``
3576doesn't prevent the inliner from inlining the function call.
3577
3578This calling convention will be used by a future version of the Objective-C
3579runtime and should therefore still be considered experimental at this time.
3580Although this convention was created to optimize certain runtime calls to
3581the Objective-C runtime, it is not limited to this runtime and might be used
3582by other runtimes in the future too. The current implementation only
3583supports X86-64 and AArch64, but the intention is to support more architectures
3584in the future.
3585  }];
3586}
3587
3588def PreserveAllDocs : Documentation {
3589  let Category = DocCatCallingConvs;
3590  let Content = [{
3591On X86-64 and AArch64 targets, this attribute changes the calling convention of
3592a function. The ``preserve_all`` calling convention attempts to make the code
3593in the caller even less intrusive than the ``preserve_most`` calling convention.
3594This calling convention also behaves identical to the ``C`` calling convention
3595on how arguments and return values are passed, but it uses a different set of
3596caller/callee-saved registers. This removes the burden of saving and
3597recovering a large register set before and after the call in the caller. If
3598the arguments are passed in callee-saved registers, then they will be
3599preserved by the callee across the call. This doesn't apply for values
3600returned in callee-saved registers.
3601
3602- On X86-64 the callee preserves all general purpose registers, except for
3603  R11. R11 can be used as a scratch register. Furthermore it also preserves
3604  all floating-point registers (XMMs/YMMs).
3605
3606The idea behind this convention is to support calls to runtime functions
3607that don't need to call out to any other functions.
3608
3609This calling convention, like the ``preserve_most`` calling convention, will be
3610used by a future version of the Objective-C runtime and should be considered
3611experimental at this time.
3612  }];
3613}
3614
3615def DeprecatedDocs : Documentation {
3616  let Category = DocCatFunction;
3617  let Content = [{
3618The ``deprecated`` attribute can be applied to a function, a variable, or a
3619type. This is useful when identifying functions, variables, or types that are
3620expected to be removed in a future version of a program.
3621
3622Consider the function declaration for a hypothetical function ``f``:
3623
3624.. code-block:: c++
3625
3626  void f(void) __attribute__((deprecated("message", "replacement")));
3627
3628When spelled as `__attribute__((deprecated))`, the deprecated attribute can have
3629two optional string arguments. The first one is the message to display when
3630emitting the warning; the second one enables the compiler to provide a Fix-It
3631to replace the deprecated name with a new name. Otherwise, when spelled as
3632`[[gnu::deprecated]] or [[deprecated]]`, the attribute can have one optional
3633string argument which is the message to display when emitting the warning.
3634  }];
3635}
3636
3637def IFuncDocs : Documentation {
3638  let Category = DocCatFunction;
3639  let Content = [{
3640``__attribute__((ifunc("resolver")))`` is used to mark that the address of a declaration should be resolved at runtime by calling a resolver function.
3641
3642The symbol name of the resolver function is given in quotes.  A function with this name (after mangling) must be defined in the current translation unit; it may be ``static``.  The resolver function should return a pointer.
3643
3644The ``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.
3645
3646Not all targets support this attribute. ELF target support depends on both the linker and runtime linker, and is available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc v2.11.1 and later, and FreeBSD 9.1 and later. Non-ELF targets currently do not support this attribute.
3647  }];
3648}
3649
3650def LTOVisibilityDocs : Documentation {
3651  let Category = DocCatType;
3652  let Content = [{
3653See :doc:`LTOVisibility`.
3654  }];
3655}
3656
3657def RenderScriptKernelAttributeDocs : Documentation {
3658  let Category = DocCatFunction;
3659  let Content = [{
3660``__attribute__((kernel))`` is used to mark a ``kernel`` function in
3661RenderScript.
3662
3663In RenderScript, ``kernel`` functions are used to express data-parallel
3664computations.  The RenderScript runtime efficiently parallelizes ``kernel``
3665functions to run on computational resources such as multi-core CPUs and GPUs.
3666See the RenderScript_ documentation for more information.
3667
3668.. _RenderScript: https://developer.android.com/guide/topics/renderscript/compute.html
3669  }];
3670}
3671
3672def XRayDocs : Documentation {
3673  let Category = DocCatFunction;
3674  let Heading = "xray_always_instrument, xray_never_instrument, xray_log_args";
3675  let Content = [{
3676``__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.
3677
3678Conversely, ``__attribute__((xray_never_instrument))`` or ``[[clang::xray_never_instrument]]`` will inhibit the insertion of these instrumentation points.
3679
3680If 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.
3681
3682``__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.
3683  }];
3684}
3685
3686def TransparentUnionDocs : Documentation {
3687  let Category = DocCatType;
3688  let Content = [{
3689This attribute can be applied to a union to change the behaviour of calls to
3690functions that have an argument with a transparent union type. The compiler
3691behaviour is changed in the following manner:
3692
3693- A value whose type is any member of the transparent union can be passed as an
3694  argument without the need to cast that value.
3695
3696- The argument is passed to the function using the calling convention of the
3697  first member of the transparent union. Consequently, all the members of the
3698  transparent union should have the same calling convention as its first member.
3699
3700Transparent unions are not supported in C++.
3701  }];
3702}
3703
3704def ObjCSubclassingRestrictedDocs : Documentation {
3705  let Category = DocCatType;
3706  let Content = [{
3707This attribute can be added to an Objective-C ``@interface`` declaration to
3708ensure that this class cannot be subclassed.
3709  }];
3710}
3711
3712def ObjCNonLazyClassDocs : Documentation {
3713  let Category = DocCatType;
3714  let Content = [{
3715This attribute can be added to an Objective-C ``@interface`` declaration to
3716add the class to the list of non-lazily initialized classes. A non-lazy class
3717will be initialized eagerly when the Objective-C runtime is loaded.  This is
3718required for certain system classes which have instances allocated in
3719non-standard ways, such as the classes for blocks and constant strings.  Adding
3720this attribute is essentially equivalent to providing a trivial `+load` method 
3721but avoids the (fairly small) load-time overheads associated with defining and
3722calling such a method.
3723  }];
3724}
3725
3726def SelectAnyDocs : Documentation {
3727  let Category = DocCatType;
3728  let Content = [{
3729This attribute appertains to a global symbol, causing it to have a weak
3730definition (
3731`linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_
3732), allowing the linker to select any definition.
3733
3734For more information see
3735`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_
3736or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_.
3737}]; }
3738
3739def WebAssemblyImportModuleDocs : Documentation {
3740  let Category = DocCatFunction;
3741  let Content = [{
3742Clang supports the ``__attribute__((import_module(<module_name>)))`` 
3743attribute for the WebAssembly target. This attribute may be attached to a
3744function declaration, where it modifies how the symbol is to be imported
3745within the WebAssembly linking environment.
3746
3747WebAssembly imports use a two-level namespace scheme, consisting of a module
3748name, which typically identifies a module from which to import, and a field
3749name, which typically identifies a field from that module to import. By
3750default, module names for C/C++ symbols are assigned automatically by the
3751linker. This attribute can be used to override the default behavior, and
3752reuqest a specific module name be used instead.
3753  }];
3754}
3755
3756def WebAssemblyImportNameDocs : Documentation {
3757  let Category = DocCatFunction;
3758  let Content = [{
3759Clang supports the ``__attribute__((import_name(<name>)))`` 
3760attribute for the WebAssembly target. This attribute may be attached to a
3761function declaration, where it modifies how the symbol is to be imported
3762within the WebAssembly linking environment.
3763
3764WebAssembly imports use a two-level namespace scheme, consisting of a module
3765name, which typically identifies a module from which to import, and a field
3766name, which typically identifies a field from that module to import. By
3767default, field names for C/C++ symbols are the same as their C/C++ symbol
3768names. This attribute can be used to override the default behavior, and
3769reuqest a specific field name be used instead.
3770  }];
3771}
3772
3773def ArtificialDocs : Documentation {
3774  let Category = DocCatFunction;
3775  let Content = [{
3776The ``artificial`` attribute can be applied to an inline function. If such a
3777function is inlined, the attribute indicates that debuggers should associate
3778the resulting instructions with the call site, rather than with the
3779corresponding line within the inlined callee.
3780  }];
3781}
3782
3783def NoDerefDocs : Documentation {
3784  let Category = DocCatType;
3785  let Content = [{
3786The ``noderef`` attribute causes clang to diagnose dereferences of annotated pointer types.
3787This is ideally used with pointers that point to special memory which cannot be read
3788from or written to, but allowing for the pointer to be used in pointer arithmetic.
3789The following are examples of valid expressions where dereferences are diagnosed:
3790
3791.. code-block:: c
3792
3793  int __attribute__((noderef)) *p;
3794  int x = *p;  // warning
3795
3796  int __attribute__((noderef)) **p2;
3797  x = **p2;  // warning
3798
3799  int * __attribute__((noderef)) *p3;
3800  p = *p3;  // warning
3801
3802  struct S {
3803    int a;
3804  };
3805  struct S __attribute__((noderef)) *s;
3806  x = s->a;    // warning
3807  x = (*s).a;  // warning
3808
3809Not all dereferences may diagnose a warning if the value directed by the pointer may not be
3810accessed. The following are examples of valid expressions where may not be diagnosed:
3811
3812.. code-block:: c
3813
3814  int *q;
3815  int __attribute__((noderef)) *p;
3816  q = &*p;
3817  q = *&p;
3818
3819  struct S {
3820    int a;
3821  };
3822  struct S __attribute__((noderef)) *s;
3823  p = &s->a;
3824  p = &(*s).a;
3825
3826``noderef`` is currently only supported for pointers and arrays and not usable for
3827references or Objective-C object pointers.
3828
3829.. code-block: c++
3830
3831  int x = 2;
3832  int __attribute__((noderef)) &y = x;  // warning: 'noderef' can only be used on an array or pointer type
3833
3834.. code-block: objc
3835
3836  id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type
3837}];
3838}
3839
3840def ReinitializesDocs : Documentation {
3841  let Category = DocCatFunction;
3842  let Content = [{
3843The ``reinitializes`` attribute can be applied to a non-static, non-const C++
3844member function to indicate that this member function reinitializes the entire
3845object to a known state, independent of the previous state of the object.
3846
3847This attribute can be interpreted by static analyzers that warn about uses of an
3848object that has been left in an indeterminate state by a move operation. If a
3849member function marked with the ``reinitializes`` attribute is called on a
3850moved-from object, the analyzer can conclude that the object is no longer in an
3851indeterminate state.
3852
3853A typical example where this attribute would be used is on functions that clear
3854a container class:
3855
3856.. code-block:: c++
3857
3858  template <class T>
3859  class Container {
3860  public:
3861    ...
3862    [[clang::reinitializes]] void Clear();
3863    ...
3864  };
3865  }];
3866}
3867
3868def AlwaysDestroyDocs : Documentation {
3869  let Category = DocCatVariable;
3870  let Content = [{
3871The ``always_destroy`` attribute specifies that a variable with static or thread
3872storage duration should have its exit-time destructor run. This attribute is the
3873default unless clang was invoked with -fno-c++-static-destructors.
3874  }];
3875}
3876
3877def NoDestroyDocs : Documentation {
3878  let Category = DocCatVariable;
3879  let Content = [{
3880The ``no_destroy`` attribute specifies that a variable with static or thread
3881storage duration shouldn't have its exit-time destructor run. Annotating every
3882static and thread duration variable with this attribute is equivalent to
3883invoking clang with -fno-c++-static-destructors.
3884  }];
3885}
3886
3887def UninitializedDocs : Documentation {
3888  let Category = DocCatVariable;
3889  let Content = [{
3890The command-line parameter ``-ftrivial-auto-var-init=*`` can be used to
3891initialize trivial automatic stack variables. By default, trivial automatic
3892stack variables are uninitialized. This attribute is used to override the
3893command-line parameter, forcing variables to remain uninitialized. It has no
3894semantic meaning in that using uninitialized values is undefined behavior,
3895it rather documents the programmer's intent.
3896  }];
3897}
3898
3899def CallbackDocs : Documentation {
3900  let Category = DocCatVariable;
3901  let Content = [{
3902The ``callback`` attribute specifies that the annotated function may invoke the
3903specified callback zero or more times. The callback, as well as the passed
3904arguments, are identified by their parameter name or position (starting with
39051!) in the annotated function. The first position in the attribute identifies
3906the callback callee, the following positions declare describe its arguments.
3907The callback callee is required to be callable with the number, and order, of
3908the specified arguments. The index `0`, or the identifier `this`, is used to
3909represent an implicit "this" pointer in class methods. If there is no implicit
3910"this" pointer it shall not be referenced. The index '-1', or the name "__",
3911represents an unknown callback callee argument. This can be a value which is
3912not present in the declared parameter list, or one that is, but is potentially
3913inspected, captured, or modified. Parameter names and indices can be mixed in
3914the callback attribute.
3915
3916The ``callback`` attribute, which is directly translated to ``callback``
3917metadata <http://llvm.org/docs/LangRef.html#callback-metadata>, make the
3918connection between the call to the annotated function and the callback callee.
3919This can enable interprocedural optimizations which were otherwise impossible.
3920If a function parameter is mentioned in the ``callback`` attribute, through its
3921position, it is undefined if that parameter is used for anything other than the
3922actual callback. Inspected, captured, or modified parameters shall not be
3923listed in the ``callback`` metadata.
3924
3925Example encodings for the callback performed by `pthread_create` are shown
3926below. The explicit attribute annotation indicates that the third parameter
3927(`start_routine`) is called zero or more times by the `pthread_create` function,
3928and that the fourth parameter (`arg`) is passed along. Note that the callback
3929behavior of `pthread_create` is automatically recognized by Clang. In addition,
3930the declarations of `__kmpc_fork_teams` and `__kmpc_fork_call`, generated for 
3931`#pragma omp target teams` and `#pragma omp parallel`, respectively, are also
3932automatically recognized as broker functions. Further functions might be added
3933in the future.
3934
3935  .. code-block:: c
3936
3937    __attribute__((callback (start_routine, arg)))
3938    int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
3939                       void *(*start_routine) (void *), void *arg);
3940
3941    __attribute__((callback (3, 4)))
3942    int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
3943                       void *(*start_routine) (void *), void *arg);
3944
3945  }];
3946}
3947
3948def GnuInlineDocs : Documentation {
3949  let Category = DocCatFunction;
3950  let Content = [{
3951The ``gnu_inline`` changes the meaning of ``extern inline`` to use GNU inline
3952semantics, meaning:
3953
3954* If any declaration that is declared ``inline`` is not declared ``extern``,
3955  then the ``inline`` keyword is just a hint. In particular, an out-of-line
3956  definition is still emitted for a function with external linkage, even if all
3957  call sites are inlined, unlike in C99 and C++ inline semantics.
3958
3959* If all declarations that are declared ``inline`` are also declared
3960  ``extern``, then the function body is present only for inlining and no
3961  out-of-line version is emitted.
3962
3963Some important consequences: ``static inline`` emits an out-of-line
3964version if needed, a plain ``inline`` definition emits an out-of-line version
3965always, and an ``extern inline`` definition (in a header) followed by a
3966(non-``extern``) ``inline`` declaration in a source file emits an out-of-line
3967version of the function in that source file but provides the function body for
3968inlining to all includers of the header.
3969
3970Either ``__GNUC_GNU_INLINE__`` (GNU inline semantics) or
3971``__GNUC_STDC_INLINE__`` (C99 semantics) will be defined (they are mutually
3972exclusive). If ``__GNUC_STDC_INLINE__`` is defined, then the ``gnu_inline``
3973function attribute can be used to get GNU inline semantics on a per function
3974basis. If ``__GNUC_GNU_INLINE__`` is defined, then the translation unit is
3975already being compiled with GNU inline semantics as the implied default. It is
3976unspecified which macro is defined in a C++ compilation.
3977
3978GNU inline semantics are the default behavior with ``-std=gnu89``,
3979``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.
3980  }];
3981}
3982
3983def SpeculativeLoadHardeningDocs : Documentation {
3984  let Category = DocCatFunction;
3985  let Content = [{
3986  This attribute can be applied to a function declaration in order to indicate
3987  that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
3988  should be enabled for the function body. This can also be applied to a method
3989  in Objective C. This attribute will take precedence over the command line flag in
3990  the case where `-mno-speculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
3991
3992  Speculative Load Hardening is a best-effort mitigation against
3993  information leak attacks that make use of control flow
3994  miss-speculation - specifically miss-speculation of whether a branch
3995  is taken or not. Typically vulnerabilities enabling such attacks are
3996  classified as "Spectre variant #1". Notably, this does not attempt to
3997  mitigate against miss-speculation of branch target, classified as
3998  "Spectre variant #2" vulnerabilities.
3999
4000  When inlining, the attribute is sticky. Inlining a function that
4001  carries this attribute will cause the caller to gain the
4002  attribute. This is intended to provide a maximally conservative model
4003  where the code in a function annotated with this attribute will always
4004  (even after inlining) end up hardened.
4005  }];
4006}
4007
4008def NoSpeculativeLoadHardeningDocs : Documentation {
4009  let Category = DocCatFunction;
4010  let Content = [{
4011  This attribute can be applied to a function declaration in order to indicate
4012  that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
4013  is *not* needed for the function body. This can also be applied to a method
4014  in Objective C. This attribute will take precedence over the command line flag in
4015  the case where `-mspeculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
4016
4017  Warning: This attribute may not prevent Speculative Load Hardening from being
4018  enabled for a function which inlines a function that has the
4019  'speculative_load_hardening' attribute. This is intended to provide a
4020  maximally conservative model where the code that is marked with the
4021  'speculative_load_hardening' attribute will always (even when inlined)
4022  be hardened. A user of this attribute may want to mark functions called by
4023  a function they do not want to be hardened with the 'noinline' attribute.
4024
4025  For example:
4026
4027  .. code-block:: c
4028
4029    __attribute__((speculative_load_hardening))
4030    int foo(int i) {
4031      return i;
4032    }
4033
4034    // Note: bar() may still have speculative load hardening enabled if
4035    // foo() is inlined into bar(). Mark foo() with __attribute__((noinline))
4036    // to avoid this situation.
4037    __attribute__((no_speculative_load_hardening))
4038    int bar(int i) {
4039      return foo(i);
4040    }
4041  }];
4042}
4043
4044def ObjCExternallyRetainedDocs : Documentation {
4045  let Category = DocCatVariable;
4046  let Content = [{
4047The ``objc_externally_retained`` attribute can be applied to strong local
4048variables, functions, methods, or blocks to opt into
4049`externally-retained semantics
4050<https://clang.llvm.org/docs/AutomaticReferenceCounting.html#externally-retained-variables>`_.
4051
4052When applied to the definition of a function, method, or block, every parameter
4053of the function with implicit strong retainable object pointer type is
4054considered externally-retained, and becomes ``const``. By explicitly annotating
4055a parameter with ``__strong``, you can opt back into the default
4056non-externally-retained behaviour for that parameter. For instance,
4057``first_param`` is externally-retained below, but not ``second_param``:
4058
4059.. code-block:: objc
4060
4061  __attribute__((objc_externally_retained))
4062  void f(NSArray *first_param, __strong NSArray *second_param) {
4063    // ...
4064  }
4065
4066Likewise, when applied to a strong local variable, that variable becomes
4067``const`` and is considered externally-retained.
4068
4069When compiled without ``-fobjc-arc``, this attribute is ignored.
4070}]; }
4071
4072def MIGConventionDocs : Documentation {
4073  let Category = DocCatType;
4074  let Content = [{
4075  The Mach Interface Generator release-on-success convention dictates
4076functions that follow it to only release arguments passed to them when they
4077return "success" (a ``kern_return_t`` error code that indicates that
4078no errors have occured). Otherwise the release is performed by the MIG client
4079that called the function. The annotation ``__attribute__((mig_server_routine))``
4080is applied in order to specify which functions are expected to follow the
4081convention. This allows the Static Analyzer to find bugs caused by violations of
4082that convention. The attribute would normally appear on the forward declaration
4083of the actual server routine in the MIG server header, but it may also be
4084added to arbitrary functions that need to follow the same convention - for
4085example, a user can add them to auxiliary functions called by the server routine
4086that have their return value of type ``kern_return_t`` unconditionally returned
4087from the routine. The attribute can be applied to C++ methods, and in this case
4088it will be automatically applied to overrides if the method is virtual. The
4089attribute can also be written using C++11 syntax: ``[[mig::server_routine]]``.
4090}];
4091}
4092
4093def MSAllocatorDocs : Documentation {
4094  let Category = DocCatType;
4095  let Content = [{
4096The ``__declspec(allocator)`` attribute is applied to functions that allocate
4097memory, such as operator new in C++. When CodeView debug information is emitted
4098(enabled by ``clang -gcodeview`` or ``clang-cl /Z7``), Clang will attempt to
4099record the code offset of heap allocation call sites in the debug info. It will
4100also record the type being allocated using some local heuristics. The Visual
4101Studio debugger uses this information to `profile memory usage`_.
4102
4103.. _profile memory usage: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage
4104
4105This attribute does not affect optimizations in any way, unlike GCC's
4106``__attribute__((malloc))``.
4107}];
4108}
4109